Net-informations.com
SiteMap  | About    

How to open and read an XML file in C#

XML is a self describing language and it gives the data as well as the rules to extract what data it contains. Reading an XML file means that we are reading the information embedded in XML tags in an XML file.

In the previous program we create an XML file and named it as products.xml. The following C# program read that file and extract the contents inside the XML tag. We can read an XML file in several ways depends on our requirement. This program read the content in Node wise . Here we are using XmlDataDocument Class to read the XML file . In this program it search the Node and its child Nodes and extract the data in child nodes.




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;
            FileStream fs = new FileStream("product.xml", FileMode.Open, FileAccess.Read);
            xmldoc.Load(fs);
            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);
            }
        }
    }
}

Click here to download the input file : product.xml

 C# XML - Related Contents