CREATE A XML FILE IN C#

Ankit Singh

Total Post:341

Points:2389
Posted by  Ankit Singh
C# 
C#
 1074  View(s)
Ratings:
Rate this:
Hi Experts,

How can I create a XML file in C#

Thanks in advance.

  1. Sumit Kesarwani

    Post:378

    Points:2694
    Re: Create a XML file in C#

    Hi Ankit,

    You can use this code:

    using System;

    using System.Data;

    using System.Windows.Forms;

    using System.Xml;

     

    namespace WindowsApplication1

    {

        public partial class Form1 : Form

        {

            public Form1()

            {

                InitializeComponent();

            }

     

            private void button1_Click(object sender, EventArgs e)

            {

                XmlTextWriter writer = new XmlTextWriter("product.xml", System.Text.Encoding.UTF8);

                writer.WriteStartDocument(true);

                writer.Formatting = Formatting.Indented;

                writer.Indentation = 2;

                writer.WriteStartElement("Table");

                createNode("1", "Product 1", "1000", writer);

                createNode("2", "Product 2", "2000", writer);

                createNode("3", "Product 3", "3000", writer);

                createNode("4", "Product 4", "4000", writer);

                writer.WriteEndElement();

                writer.WriteEndDocument();

                writer.Close();

                MessageBox.Show("XML File created ! ");

            }

     

            private void createNode(string pID, string pName, string pPrice, XmlTextWriter writer)

            {

                writer.WriteStartElement("Product");

                writer.WriteStartElement("Product_id");

                writer.WriteString(pID);

                writer.WriteEndElement();

                writer.WriteStartElement("Product_name");

                writer.WriteString(pName);

                writer.WriteEndElement();

                writer.WriteStartElement("Product_price");

                writer.WriteString(pPrice);

                writer.WriteEndElement();

                writer.WriteEndElement();

            }

        }

    }

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!