This post explains how to create XML element without namespace attribute in C#. This post also is answer to following topics,
How to prevent blank xmlns attributes in output from .NET’s XmlDocument?
Avoid unwanted (empty) xmlns attribute added by appendChild
Consider an XML file which is having one or more Namespace URI (xmlns) defined. When you add a new XML element to this XML docment, you will notice a namespace attribute appearing in the added XML element with an empty string value (xmlns = “”).
This will end up in unwanted results while parsing/querying the XML document.
It is fine that in an XML file you can have namespaceuri for the document and for individual elements.
So you need to take care while adding a new element to associate it to correct namespace.Best option to remove the unwanted xmlns namespace is by creating the child element in the same namespace of its parent node.
That means the child element has to be added to the namespaceuri of its parent node, not to the document namespace. See the solution for this issue in this article.
This is an XML file which stores the country details,
<!--?xml version="1.0" encoding="UTF-8"?-->
<country xmlns="http://www.countrys.org/2013/5/Country" version="1.2">
<state name="Maharashtra">
<city>Pune</city>
<city>Mumbai </city>
</state>
</country>
In the above-mentioned XML file, I need to add another state element. So my code snippet is as below
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(@"D:\Country.xml"); //give full path of your xml file
XmlNode newStateNode = xmlDoc.GetElementsByTagName("Country")[0];
XmlElement newElement = xmlDoc.CreateElement("State", newStateNode.NamespaceURI);
newElement.SetAttribute("Name", "Tamil Nadu");
newStateNode.AppendChild(newElement);
See that I am specific in adding the namespace URI of the parent node while adding the new element.
XmlElement newElement = xmlDoc.CreateElement("State", newStateNode.NamespaceURI);
Without this newStateNode. Namespace URI, you will get an extra attribute xmlns=” ” for the newly added element.
Summary
Hope this article helped you to remove empty xmlns attribute added by AppendChild.If any doubt, write to us in the comments section below.We will reply within 48 hours.
Leave a Reply