c# .net Adsense ADO.NET Linq Viruses/security asp.net MVC JQuery Angular-js Node-js SEO Java C++ SQL API Networking vb.net .Net Css JavaScript Generics c#.Net entity framework HTML Website host Website Construction Guide HTTP tutorial W3C tutorial Web Services JSON Psychology Ionic framework Angular ReactJS Python Computer Android
c# .net

How to appending an existing XML file in c#?

| | ASP-NET , CSharp

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.

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.