Monday, December 14, 2009

How to Insert/Update in XML File.

There isn't any direct update and insert methods available for XML document . we have logically to append and remove child nodes from xml document.
There is good stuff provided for managing xml document in "System.Xml" name space in .net.
here are the steps to perform this simple but most handy task whilse development.
(1) string xmlPath = Server.MapPath("~/states.xml"); //Get path of xml file
(2) XmlDocument xDoc = new XmlDocument(); //Use XmlDocument class to perform operation.
(3) xDoc.Load(xmlPath); //Load xml file in to xml document.

(4)
string xNodeFilter = "/states/state[@ID='" + StateID + "']"; //Create filter for Select Node if it it already Exists in File.

(5)
XmlNode xNodeState = xDoc.SelectSingleNode(xNodeFilter); //Select Node if it it already Exists in File.

(6)
if (xNodeState != null) { xDoc.ChildNodes[0].RemoveChild(xNodeState); } //Remove Node if it is already there in File

(7)
XmlAttribute xAttrID = xDoc.CreateAttribute("ID"); XmlAttribute xAttrRegionID = xDoc.CreateAttribute("RegionId"); XmlAttribute xAttrName = xDoc.CreateAttribute("Name"); XmlAttribute xAttrColor = xDoc.CreateAttribute("Colour");

//Create Attribute of node to be added.

(8)
xNodeState = xDoc.CreateNode(XmlNodeType.Element, "state", "");//Create node to be added.

(9)
xAttrID.Value = "1"; xAttrRegionID.Value = "0"; xAttrName.Value = "Gujarat"; xAttrColor.Value = "#00ff00";//Set Values Of attribute just created.

(10)
xNodeState.Attributes.Append(xAttrID); xNodeState.Attributes.Append(xAttrRegionID); xNodeState.Attributes.Append(xAttrName); xNodeState.Attributes.Append(xAttrColor); //Append Attribures to node.

(11) xNodeState.InnerXml="This is my mother land"; //Set Inner data of Node

(12) xDoc.ChildNodes[0].AppendChild(xNodeState); xDoc.Save(xmlPath); //Add child to document and Save document.
This are the steps. after putting this steps.please make sure that xml file is not read only.
hope this will help you.
Thanks.