Wednesday, January 12, 2011

Extra unwanted empty namespace when adding XElement

I've been scratching my head over a problem today. While writing a program to modify an XML document I discovered that adding an XElement and then writing the document out to file results in an extra and unwanted xmlns="" being output. For example:

Original XML=

<root>
 <doodaa>value</doodaa>
</root>

When we add an element to the root we get:

<root>
 <doodaa>value</doodaa>
 <wimwam xmlns="">value</wimwam>
</root>

This often upsets things which is a pain and happens when the XML document has a namespace specified somewhere.

To overcome this problem we need to ensure that the namespace of the added element is the same as that of its parent so we can interrogate the parent element and set the namespace accordingly.

In my example I just looked at the document root element but you may have a more complex scheme to cope with. The actual code I used was as follows:

XDocument doc = XDocument.Load("somestuff.xml");
string docNS=((XElement)doc.FirstNode).Name.NamespaceName;
XElement ne = new XElement(XName.Get("wimwam", docNS), false);

Now, writing out the document I get the desired effect of:

<root>
 <doodaa>value</doodaa>
 <wimwam>value</wimwam>
</root>

No comments: