Wednesday, 20 March 2013

How to Read XML file in c#

How to Read XML file in c#

here i am first showing you an xml which we are going to read.

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


<customer id="1">

    <address>3 Kingston Road, Toronto, Canada</address>
<customer id="2">
<address>983 Damujs park</address>
<customer id="3">
    <address>9 cars diver</address>
<customer id="4">
    <address>1 New homes drive</address>
<customer id="5">
<address>786 Ahmadiyya Ave, Maple, ON L6A 3A2</address>
Above is an xml and we have saved it as mycompany.xml in the root directory...
and here is the code to read xml nodes names dynamically and then the method to read xml nodes.

using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Xml;
using System.Net;
using System.IO;
using System.Collections.Generic;

public partial class _Default : System.Web.UI.Page
    protected void Page_Load(object sender, EventArgs e)
        /* below is code to read  node names */

        XmlTextReader reader = new XmlTextReader(Server.MapPath("mycompany.xml"));

        reader.WhitespaceHandling = WhitespaceHandling.None;
        XmlDocument xmlDoc = new XmlDocument();

        foreach (System.Xml.XmlNode node in xmlDoc.SelectNodes("root/customer"))
            List<string> nodeNames = new List<string>();
            foreach (System.Xml.XmlNode child in node.ChildNodes)
                if (!nodeNames.Contains(child.Name))
                    ltrblog.Text += child.Name;
                    ltrblog.Text += "/";
            ltrblog.Text += "<br/>";

         /* below is method call to read node values */


    public void ProcessNodes(XmlNodeList nodelist)
        ltrblog.Text += "<br/><br/>";

            foreach (XmlNode x in nodelist)
                ltrblog.Text += x.SelectSingleNode("fname") != null ? x.SelectSingleNode("fname").InnerText : "";
                ltrblog.Text += "<br/>";
                ltrblog.Text += x.SelectSingleNode("lname") != null ? x.SelectSingleNode("lname").InnerText : "";
                ltrblog.Text += "<br/>";
                ltrblog.Text += x.SelectSingleNode("address") != null ? x.SelectSingleNode("address").InnerText : "";
                ltrblog.Text += "<br/>";


and its out put is labled in literal named as ltrblog...
so out put will be as below.