Create XML File using XmlTextWriter in C#

 

As we know XML file is the combination of parent and child elements. Sometimes we might require to create XML file dynamically. Today we discuss about how to create XML file dynamically in C# by using XmlTextWriter class.

 

XmlTextWriter class belongs to System.Xml namespace. Open Microsoft Visual Studio => create Asp.Net Web Application, Write below code to create the XML file by using XmlTextWriter class.

 

using System;

using System.Text;

using System.Xml;

 

namespace CreateXMLExp

{

    public partial class _Default : System.Web.UI.Page

    {

        protected void Page_Load(object sender, EventArgs e)

        {

 

        }

 

        protected void btn_Click(object sender, EventArgs e)

        {

            XmlTextWriter xmlWriter = new  XmlTextWriter(Server.MapPath("Employees.xml"), Encoding.UTF8);

 

            xmlWriter.WriteStartDocument();

            xmlWriter.WriteStartElement("Employees");

 

            xmlWriter.WriteStartElement("Employee");

            xmlWriter.WriteStartElement("Id");

            xmlWriter.WriteString("1");

            xmlWriter.WriteEndElement();

            xmlWriter.WriteStartElement("Name");

            xmlWriter.WriteString("John");

            xmlWriter.WriteEndElement();

            xmlWriter.WriteEndElement();

 

            xmlWriter.WriteStartElement("Employee");

            xmlWriter.WriteStartElement("Id");

            xmlWriter.WriteString("2");

            xmlWriter.WriteEndElement();

            xmlWriter.WriteStartElement("Name");

            xmlWriter.WriteString("Smith");

            xmlWriter.WriteEndElement();

            xmlWriter.WriteEndElement();

 

            xmlWriter.WriteStartElement("Employee");

            xmlWriter.WriteStartElement("Id");

            xmlWriter.WriteString("3");

            xmlWriter.WriteEndElement();

            xmlWriter.WriteStartElement("Name");

            xmlWriter.WriteString("Bob");

            xmlWriter.WriteEndElement();

            xmlWriter.WriteEndElement();

 

            xmlWriter.WriteEndElement();

            xmlWriter.WriteEndDocument();

            xmlWriter.Flush();

            xmlWriter.Close();

           

            Response.Redirect(Server.MapPath("Employees.xml"));

        }

    }

}

 

Now execute the application and the output is as shown below.

 

 

                                                                                                                            CreateXMLExp.zip (151.11 kb)