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

GrzesiekO picture GrzesiekO · Aug 20, 2012 · Viewed 21.6k times · Source

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?

Answer

Christoffer Lette picture Christoffer Lette · Aug 20, 2012

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.