TechyMedia

A .NET Technology blog | .NET,C# Progamming,C# tutorials,WPF WCF|Software Engineer

NAVIGATION - SEARCH

Add XML element without namespace attribute - C#,VB.NET

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 cause unwanted results while parsing/querying the xml document.How to get rid of this unwanted namespace,xmlns.Read this article..

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 cause unwanted results while parsing/querying the xml document.
In an XML file you can have namespaceuri for the document and for individual elements.So you need to take care while adding new element to associate it to correct namespace.
The element has to be added to the namespaceuri of it's 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>Mumbai</City>
    <City>Pune</City>
  </State> 
</Country>

In the above mentioned xml file I need to add another state.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.NamespaceURI,you will get an extra attribute xmlns="" for the newly added element.

Add comment

  Country flag

biuquote
  • Comment
  • Preview
Loading