How can I remove empty xmlns attribute from node created by XElement

23,459

It's all about how you handle your namespaces. The code below creates child items with different namespaces:

XNamespace defaultNs = "http://www.tempuri.org/default";
XNamespace otherNs = "http://www.tempuri.org/other";

var root = new XElement(defaultNs + "root");
root.Add(new XAttribute(XNamespace.Xmlns + "otherNs", otherNs));

var parent = new XElement(otherNs + "parent");
root.Add(parent);

var child1 = new XElement(otherNs + "child1");
parent.Add(child1);

var child2 = new XElement(defaultNs + "child2");
parent.Add(child2);

var child3 = new XElement("child3");
parent.Add(child3);

It will produce XML that looks like this:

<root xmlns:otherNs="http://www.tempuri.org/other" xmlns="http://www.tempuri.org/default">
    <otherNs:parent>
        <otherNs:child1 />
        <child2 />
        <child3 xmlns="" />
    </otherNs:parent>
</root>

Look at the difference between child1, child2 and child3. child2 is created using the default namespace, which is probably what you want, while child3 is what you have now.

Share:
23,459
GrzesiekO
Author by

GrzesiekO

.NET Developer since 2011 ( ͡◉ ͜ʖ ͡◉)

Updated on February 03, 2021

Comments

  • GrzesiekO
    GrzesiekO about 3 years

    This is my code:

    XElement itemsElement = new XElement("Items", string.Empty);
    //some code
    parentElement.Add(itemsElement);
    

    After that I got this:

    <Items xmlns=""></Items>
    

    Parent element hasn't any namespace. What can I do, to get an Items element without the empty namespace attribute?

  • cedd
    cedd over 5 years
    I think the code in this answer will result in "System.Xml.XmlException: 'The ':' character, hexadecimal value 0x3A, cannot be included in a name.'". To avoid this use new XElement(XName.Get("child1", otherNs)); in place of new XElement(otherNs + "child1");
  • Christoffer Lette
    Christoffer Lette over 5 years
    @cedd Did you try it? It works on my machine. In fact, Console.Out.WriteLine(root.ToString()); produces exactly what I show in the answer above. I'm running this in a Console app on .Net Framework 4.6.2. What did you do to get this error?
  • Christoffer Lette
    Christoffer Lette over 5 years
    @cedd Ok, I can force that exact error if I use var when declaring the namespaces. They will then become strings, which will not work. They must be explicitly typed as XNamespace.
  • SubqueryCrunch
    SubqueryCrunch over 3 years
    Dude i love you. Such a complete example. You helped me so much...
  • Christoffer Lette
    Christoffer Lette over 3 years
    I love you too, @SubqueryCrunch. 😂 Glad to have helped. Happy new year and good luck to you in your endeavors.