Friday, December 7, 2012

Read XML File in C#.NET


First create your XML file.


<?xml version="1.0" encoding="utf-8" ?>
<customers>
  <customer age="19" gender="female">
    <name>Kevin Anders</name>
    <phone>555.555.5555</phone>
  </customer>
  <customer age="22" gender="male">
    <name>Staci Richard</name>
    <phone>555.122.1552</phone>
  </customer>
</customers>

customers - Root element
customer - Node element
age, gender - Node attributes
name, phone - TextNode

Below method will read the XML documents each attribute and the elements.

 private void readXMLNodes()
    {
        //Create XML document object
        XmlDocument doc = new XmlDocument();
        doc.Load(Server.MapPath("~/XMLFile.xml"));
        //get the node list
        XmlNodeList customers = doc.SelectNodes("//customer");

        foreach (XmlNode customer in customers)
        {
            //Display the text in each element.
            Response.Write("Name: " + customer["name"].InnerText +" - "+"Phone: "+customer["phone"].InnerText);
            Response.Write("<br/>");
            //Display the text in each attribute.
            Response.Write("Gender: "+customer.Attributes["gender"].Value.ToString());
            Response.Write("<br/>");
            Response.Write("Age: "+customer.Attributes["age"].Value.ToString());
            Response.Write("<br/>");
            Response.Write("<br/>");
          
        }
    }

Out put:
Name: Kevin Anders - Phone: 555.555.5555
Gender: female
Age: 19

Name: Staci Richard - Phone: 555.122.1552
Gender: male
Age: 22

No comments:
Write comments
Recommended Posts × +