Chitika

Monday, July 6, 2015

Read XML using XMLDocument class by tag / attribute / value in C#

We can read XML from C# in many ways, here is the easiest way to do that.

Let's take the below XML for reference,
<Regions>
  <Region name="ASIA" code="ASI">
    <Country name="India" code="IND"></Country>
    <Country>Pakistan</Country>
    <Country>Japan</Country>
    <Country>China</Country>
  </Region>
  <Region name="Europe" code="Eu">
    <Country name="Greece" code="GR"></Country>
    <Country>Russia</Country>
    <Country>Italy</Country>
    <Country>United Kingdom</Country>
  </Region>
</Regions>

We have Regions as root tag and Region as child nodes for that.
Each region will have multiple countries as child nodes to region tag.

First read the XML using XMLDocument class, which is under System.XML name space.

            var xmlDo = new XmlDocument();
            xmlDo.Load("d:\\Countries.xml");

I have hard coded the path above, but you can refer dynamically from project folder.

           To get all the xml nodes with tag name
            XmlNodeList itemNodes = xmlDo.SelectNodes("Regions/Region");
By using above statement we get two xml nodes, because we have two "Region" tags in xml.

We can get single region by providing any of the unique property for the region .
       To get all the xml nodes by filter with value
      XmlNodeList itemNodesbyValue = xmlDo.SelectNodes("Regions/Region[@name='ASIA']");
Here we have used ASIA as filter now we get only one region tag with name as "ASIA".

We can get single node by using "SelectSingleNode" method as below,

        XmlNode xnode = xmlDo.SelectSingleNode("Regions/Region[@name='ASIA']");

As we got the xml node we can find the values of the properties for that node using attributes as below,
         
            string nodeValue = xnode.Attributes["code"].Value;
From the above statement we can get value as "ASI" of attribute "code".
Like the one we can get any value of the attribute, once we get the XML node.

In the above you can observe the top-down approach, first we got all the XML nodes by using the tag, then we filtered using the property of the tags, then we got single node reading, then after we read the value of the property.

Happy coding ,,,

No comments:

Post a Comment