How to create XML file in C#

        Today i'm going to show you how to create simple XML file in C#. Actually, XML stands for extensible markup language. 
       So what XML is used for, is to outsource data. Rather than integrating them into the HTML document, they are stored in separate XML file. Since XML stores data in plain text format, the storage is independent of your platform and your data can be exported, imported, or simply moved much easier.
       In order to creating a new XML file in C#, here we are using XmlTextWriter class. Below is the code to create XML file in C#


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();
        }
    }
}

This is the output of above code:

<?xml version="1.0" encoding="utf-8" standalone="yes"?>

<Table>

  <Product>

     <Product_id>1</Product_id>

     <Product_name>Product 1</Product_name>

     <Product_price>1000</Product_price>

  </Product>

  <Product>

     <Product_id>1</Product_id>

     <Product_name>Product 1</Product_name>

     <Product_price>1000</Product_price>

  </Product>

  <Product>

     <Product_id>1</Product_id>

     <Product_name>Product 1</Product_name>

     <Product_price>1000</Product_price>

  </Product>

  <Product>

     <Product_id>1</Product_id>

     <Product_name>Product 1</Product_name>

     <Product_price>1000</Product_price>

  </Product>

</Table>
How to create XML file in C# How to create XML file in C# Reviewed by Vijay Vardhan on 10:01:00 Rating: 5

No comments: