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.WriteStartDocument();
                   xmlWriter.WriteStartElement("School");
                   xmlWriter.WriteStartElement("Student");
                   xmlWriter.WriteElementString("FirstName", "Abdul");
                   xmlWriter.WriteElementString("LastName", "Rasik");
                   xmlWriter.WriteEndElement();
                   xmlWriter.WriteEndElement();
                   xmlWriter.WriteEndDocument();
                   xmlWriter.Flush();
                   xmlWriter.Close();
                }
            }
            else
            {
                XDocument xDocument = XDocument.Load(Server.MapPath("Test.xml"));
                XElement root = xDocument.Element("School");
                IEnumerable<XElement> rows = root.Descendants("Student");
                XElement firstRow = rows.First();
                firstRow.AddBeforeSelf(
                   new XElement("Student",
                   new XElement("FirstName", "mohamed"),
                   new XElement("LastName", "mohideen")));
                xDocument.Save(Server.MapPath("Test.xml"));
            }
        }

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