Blog Post

xml - How to insert attribute to an existing element

Monday, September 26, 2016 9:13 AM

I needed to insert attribute to a node in existing xml document.

Here is an example with the solution.

We will start the solution as from defining xml document

XmlDocument xmlDoc = new XmlDocument();

Now we will define the document data we are going to use for the demo

xmlDoc.LoadXml("<root><Item><Type>Tyre</Type><Level>10</Level></Item></root>");

Now we will select all times we want to update using selector "/root/Item"

foreach(XmlNode xn in xmlDoc.SelectNodes("/root/Item")) {

Now we will select node we will work on and we could do this by extracting this logic into method at later stage

XmlNode typeNode = xn.SelectSingleNode("Type");

Now lets just check anyway for nulls

if(typeNode != null) {

Now we need to get the element we want to add the attribute

XmlNode levelNode = xn.SelectSingleNode("Level");

Lets create the attribute. Please note it has to come through xmlDoc - the main xml document 

XmlAttribute typeAttr = xmlDoc.CreateAttribute("Type");

Now we can set the value for the attribute

typeAttr.Value = "newValue";

And finally we can push the new attribute we have created into the list of attributes for the element

levelNode.Attributes.Append(typeAttr);

 

The full code in c#:

XmlDocument xmlDoc = new XmlDocument();

xmlDoc.LoadXml("<root><Item><Type>Tyre</Type><Level>10</Level></Item><Item><Type>Ring</Type><Level>09</Level></Item></root>");


foreach(XmlNode xn in xmlDoc.SelectNodes("/root/Item")) {

XmlNode typeNode = xn.SelectSingleNode("Type");

if(typeNode != null) {

XmlNode levelNode = xn.SelectSingleNode("Level");

XmlAttribute typeAttr = xmlDoc.CreateAttribute("Type");

typeAttr.Value = typeNode.InnerText;

levelNode.Attributes.Append(typeAttr);

xn.RemoveChild(typeNode);

}

}

Console.WriteLine(xmlDoc.OuterXml);