Wednesday 8 August 2012

How to add xml node in existing XML file ?


Let's say a XML file having format like :

XML file format :
-------------------------------
<?xml version="1.0" encoding="utf-8"?>
<items>
  <item id="1">
    <content>Get groceries</content>
    <status>false</status>
  </item>
  <item id="2">
    <content>Wash your car</content>
    <status>true</status>
  </item>  
</items>
Now we want to add new element in existing XML file. 

Add new Node to existing XML file:
-------------------------------------
 using System.Xml;
 using System.IO;
 
//call this method from page load
 private void AddNodeXML(string strFilePath)
 {
//get the existing xml file full path
 string XMLFile = Path.GetFullPath(strFilePath);

//create object of XML Document
 XmlDocument xDoc = new XmlDocument();
//load XML document from given URL
 xDoc.Load(XMLFile);

//get the root node in which you want to add new node
 XmlNode menu = xDoc.SelectSingleNode("//items");

//now,create new node with name,id and value
 XmlNode newNode = xDoc.CreateNode(XmlNodeType.Element, "item", null);
 XmlAttribute xa = xDoc.CreateAttribute("id");
 xa.Value = "3";
 newNode.Attributes.Append(xa);
//append new node as child node
 menu.AppendChild(newNode);

//create new element
 XmlNode newContent = xDoc.CreateElement("content");
 newContent.InnerText = "Clean Table";
 newNode.AppendChild(newContent);
 XmlNode newStatus = xDoc.CreateElement("status");
 newStatus.InnerText = "true";
//append new created element in node
 newNode.AppendChild(newStatus);
//save xml file 
 xDoc.Save(XMLFile);
 }