Add, Edit and Edit XML Element From XML File in C#


We can edit the XML file in C# by using XmlDocument, XmlElement classes under System.Xml namespace. In this article we discuss about how to edit existing XML element, how to insert the new XML element and how to delete the existing XML element.


Create some XML File with the below content.
























Insert new XML element as shown below.


           // loading xml file

            XmlDocument xdoc = new XmlDocument();



            //Creating childnode to root node using Xmlelement

            XmlElement xelement = xdoc.CreateElement("Employee");

            //creating subnode to childnode using XmlElement

            XmlElement xID = xdoc.CreateElement("ID");

            xID.InnerText = "4";



            //creating subnode to childnode using XmlElement

            XmlElement xName = xdoc.CreateElement("Name");

            xName.InnerText = "E";



            //Adding child node to the root node.(in my case "NewElement is root node")




As shown above first load XML file through XmlDocument class and new XML elemnt by using XMLElement class. After adding the XML element append element by using AppendChild() method and save the XML file by using XmlDocument Save() method.

Update the existing XML element as shown below.


                 XmlDocument xmldoc = new XmlDocument();


                // Index value will be obtained at lvEmployee_ItemEditing ,that index value

                //is used here for update.

                XmlNode xmlnode = xmldoc.DocumentElement.ChildNodes.Item(i);//here i is the index of the XML element

                xmlnode["ID"].InnerText = lblid.Text;

                xmlnode["Name"].InnerText = txtnameTextBox.Text;

                // save xml file and reload listview.



Delete the existing XML element as shown below.


            XmlDocument xmlDoc = new XmlDocument();


            XmlNodeList newXMLNodes = xmlDoc.SelectNodes("/Employees/Employee");

            // here i am searching based on id and name.So i am concatenating data into one string variable.

            string value = "XML Element text";


            // code to remove child node from xml based on selection(matches all the data in xml file)

            //when a match is found removes that childnode from root node.

            foreach (XmlNode newXMLNode in newXMLNodes)


                if (newXMLNode.InnerText == value)





            //saving back xml file and reloading listview.



Add comment