Create XML File at runtime using CSharp

There are many advantages to using XML for information exchange, and they offer many benefits to the user.
In this Example i am describing how to Create a Xml file dynamically using C#.

Step1
Create a function for generating Xml Document

// xmlpath = D:/xmlfolder
   private void CreateXmlFile(string xmlpath)
        {
            string xmlfilepath = xmlpath + @"\" + "xmlsample.xml";
            if (!System.IO.Directory.Exists(xmlpath  + @"\"))
            {
                System.IO.Directory.CreateDirectory(xmlpath  + @"\");
            }
            if (!System.IO.File.Exists(xmlfilepath ))
            {
                using (var file = System.IO.File.Create(xmlfilepath)) ;
            }
            using (XmlTextWriter myXmlWriter = new XmlTextWriter(xmlfilepath, null))
            {
                myXmlWriter.Formatting = Formatting.Indented;
                myXmlWriter.Indentation = 4;
                myXmlWriter.WriteStartElement("issues");
                int i = 0;
                for (i = 1; i <= 5; i++)
                {
                myXmlWriter.WriteStartElement("job");// see next line
                myXmlWriter.WriteAttributeString("dt", "");
                myXmlWriter.WriteAttributeString("mid", "");
                myXmlWriter.WriteAttributeString("shipment", "");
                myXmlWriter.WriteAttributeString("name", "Ashish + i");
                myXmlWriter.WriteElementString("sername", "Sharma + i");
                }
                myXmlWriter.WriteEndElement();
                myXmlWriter.Flush();
                myXmlWriter.Close();
            }
        }

Output XML will be

<?xml version="1.0"?>
<issues>
<job name="ashish1" shipment="" mid="" dt="">
 <sername>sharma1</sername> 
</job>
<job name="ashish2" shipment="" mid="" dt="">
 <sername>sharma2</sername> 
</job>
.
.
.
.
.
.
.
.
 </issues>

Advertisements
This entry was posted in Grid View. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s