Apr 25, 2012

How to open and read an XML file in C#

Xml file:


<Table>

<Product>

<Product_id>1</Product_id>

<Product_name>Product 1</Product_name>

<Product_price>1000</Product_price>
</Product>

<Product>

<Product_id>2</Product_id>

<Product_name>Product 2</Product_name>

<Product_price>2000</Product_price>
</Product>

<Product>

<Product_id>3</Product_id>

<Product_name>Product 3</Product_name>

<Product_price>3000</Product_price>
</Product>

<Product>

<Product_id>4</Product_id>

<Product_name>Product 4</Product_name>

<Product_price>4000</Product_price>
</Product>
</Table>


Source code for C#:

using System;
using System.Data;
using System.Windows.Forms;
using System.Xml;
using System.IO; 

namespace WindowsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            XmlDataDocument xmldoc = new XmlDataDocument();
            XmlNodeList xmlnode ;
            int i = 0;
            string str = null;
            string strXmlLoc=null;
          string strXmlLoc = "C:\\Users\\Desktop\\products.xml";
            xmldoc.Load(strXmlLoc);
           
            xmlnode = xmldoc.GetElementsByTagName("Product");
            for (i = 0; i <= xmlnode.Count - 1; i++)
            {
                xmlnode[i].ChildNodes.Item(0).InnerText.Trim();
                str = xmlnode[i].ChildNodes.Item(0).InnerText.Trim() + " | " + xmlnode[i].ChildNodes.Item(1).InnerText.Trim() + " | " + xmlnode[i].ChildNodes.Item(2).InnerText.Trim();
                MessageBox.Show (str);
            }
        }
    }
}

No comments:

Post a Comment