Custom Search

Saturday, July 17, 2010

Xml document edition

In the previous post I showed you how to create a XmlDocument following some easy steps. The idea now is to read the created xml and find elements by a specific tag. Then we are going to change that value and save the edited xml.


For the first book element, we are going to add inner text:

XmlDocument xmlDoc = new XmlDocument();

//Load the Xml created previously

xmlDoc.Load(@"C:\XML\" + "xmlTest.xml");

XmlNodeList books;

books = xmlDoc.GetElementsByTagName("book-1");

//Since there is only one element with this tag, the loop is not necessary.

foreach (XmlNode node in books)


node.InnerText = "Great Book";


For the second element, we are changing the attributes values:

books = xmlDoc.GetElementsByTagName("book-2");

foreach (XmlNode node in books)


node.Attributes[0].Value = "Time";


xmlDoc.Save(@"C:\XML\" + "xmlTest.xml");


No comments: