简体   繁体   中英

XDocument xmlns url attributes persist to child nodes

Based on this SO solution , adding the same namespace to your child node will prevent creating empty xmlns="" attributes. I'm not getting empty attributes, instead it duplicates the same xmlns in root to child node.

My current output:

<Root xmlns="http://my.namespace">     
     <FirstElement xmlns="http://my.namespace"/> 
</Root>

Expected output:

<Root xmlns="http://my.namespace">     
     <FirstElement/> 
</Root>

Sharing my code:


        private XDocument CreateRootTag()
        {
            XNamespace xmlns = XNamespace.Get("http://my.namespace");
            var xdec = new XDeclaration("1.0", "utf-8", "yes");
            XDocument xml = new XDocument(
                    xdec,
                    new XElement(
                        xmlns + "Root",
                        new XAttribute("version", "1.0"),
                        CreateFirstElementTag()));  // <--- adding child node containing duplicate xmlns as root

            return xml;
        }



        private XElement CreateFirstElementTag()
        {
            XNamespace xmlns = XNamespace.Get("http://my.namespace");
            XElement firstElementTag = new XElement(xmlns + "FirstElement","hello");
            return firstElementTag;
        }


How to prevent persisting xmlns="my.namespace" attributes in child node?

Please let me know if you have any questions. Thanks.

I ran your code as follows. And didn't encounter any issues.

c#

void Main()
{
    XDocument xdoc = CreateRootTag();
    Console.WriteLine(xdoc);
}

private XDocument CreateRootTag()
{
    XNamespace xmlns = XNamespace.Get("http://my.namespace");
    var xdec = new XDeclaration("1.0", "utf-8", "yes");
    XDocument xml = new XDocument(
            xdec,
            new XElement(
                xmlns + "Root",
                new XAttribute("version", "1.0"),
                CreateFirstElementTag()));  // <--- adding child node containing duplicate xmlns as root

    return xml;
}

private XElement CreateFirstElementTag()
{
    XNamespace xmlns = XNamespace.Get("http://my.namespace");
    XElement firstElementTag = new XElement(xmlns + "FirstElement", "hello");
    return firstElementTag;
}

Output

<Root version="1.0" xmlns="http://my.namespace">
  <FirstElement>hello</FirstElement>
</Root>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM