Simple XML pursing with XPath

Hello again. Today i will talk about how to purse XML simply with .NET’s XPath features.We know XML now days gets very important thing for transferring or what ever. I will show how simply we can Purse a XML file.
Suppose we have a XML file named “Sample.xml” and the structure of that XML file is as bellow:
   1:  <?xml version="1.0" encoding="utf-8" ?>
   2:  <items>
   3:    <item>
   4:      <name>Tanvir</name>
   5:      <id>03-04304-3</id>
   6:    </item>
   7:    <item>
   8:      <name>Anowar</name>
   9:      <id>04-04304-2</id>
  10:    </item>
  11:  </items>

now open a Default.aspx page and import the sub class Xml,and Xml.XPath by writing as bellow:

   1:  using System.Xml;
   2:  using System.Xml.XPath;

Now making a XPathDocument document we can iterate our queries as given in nav.Select("/items/item/name") . here /items/item/name is our query ,where Items is the root node . item is the child node and name is our desired node which is going to be explored.
The following code is in C#.NET for exploring XML node with XPath.

 XPathDocument xmlDoc = new XPathDocument(MapPath("Sample.xml"));
 XPathNavigator nav = xmlDoc.CreateNavigator();
 XPathNodeIterator iterate = nav.Select("/items/item/name");
    Response.Write(iterate.Current.Name); // print the node name
    Response.Write(iterate.Current.Value); // print the value
    Response.Write("<br />"); 

Leave a Reply