[ACCEPTED]-How can I remove empty xmlns attribute from node created by XElement-linq-to-xml

Accepted answer
Score: 88

It's all about how you handle your namespaces. The 6 code below creates child items with different 5 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");

var child1 = new XElement(otherNs + "child1");

var child2 = new XElement(defaultNs + "child2");

var child3 = new XElement("child3");

It will produce XML that looks 4 like this:

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

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

More Related questions