c# .net

How to appending an existing XML file in c#?

How to appending an existing XML file in c#?, someone asked me to explain?

In this article I will show how to append new data to an xml file using c#. If you want to add data to xml file without reloading the xml file appending data to the first row using the xElement addBeforeSelf and save xml file using the xDocument.

append to xml file c#

C# Code:

   protected void Page_Load(object sender, EventArgs e)
            if (File.Exists(Server.MapPath("Test.xml")) == false)
                XmlWriterSettings xmlWriterSettings = new XmlWriterSettings();
                xmlWriterSettings.Indent = true;
               xmlWriterSettings.NewLineOnAttributes = true;
                using (XmlWriter xmlWriter = XmlWriter.Create(Server.MapPath("Test.xml"), xmlWriterSettings))
                   xmlWriter.WriteElementString("FirstName", "Abdul");
                   xmlWriter.WriteElementString("LastName", "Rasik");
                XDocument xDocument = XDocument.Load(Server.MapPath("Test.xml"));
                XElement root = xDocument.Element("School");
                IEnumerable<XElement> rows = root.Descendants("Student");
                XElement firstRow = rows.First();
                   new XElement("Student",
                   new XElement("FirstName", "mohamed"),
                   new XElement("LastName", "mohideen")));

Description: Run the application, if the XML file is not in the location, it will create a new xml file with name Test.xml. If xml file already exists, then it will append and overwrite the xml file. 

Post your comments / questions