Friday, December 7, 2012

Read XML File in C#.NET

First create your XML file.

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

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();
        //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);
            //Display the text in each attribute.
            Response.Write("Gender: "+customer.Attributes["gender"].Value.ToString());
            Response.Write("Age: "+customer.Attributes["age"].Value.ToString());

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 × +