This blog is moved to
http://amalhashim.wordpress.com

Tuesday, November 3, 2009

Using XPath in C#

In this blog I am going to give an overview of how we can easily parse and get the data from an XML file. For demonstrating, I have created a sample XML file listed below.

<?xml version="1.0" encoding="utf-8" ?>
<
Employees>
<
Employee>
<
Name>Amal</Name>
<
Age>26</Age>
<
Address>333 Indiana Street</Address>
</
Employee>
<
Employee>
<
Name>Munna</Name>
<
Age>20</Age>
<
Address>222 West Region</Address>
</
Employee>
</
Employees>

Add the following namespace in your application

using System.Xml.XPath;

Now we can open the XPathDocument object as follows

XPathDocument Doc = new XPathDocument("emp.xml");

Once this is done, we need a XPathNavigator

XPathNavigator navigator = Doc.CreateNavigator();

Using this navigator object, we can traverse through the document. We can provide XPath expressions as shown below

XPathNodeIterator iterator = navigator.Select("/Employees");
while (iterator.MoveNext())
{
Console.WriteLine(iterator.Current.Name);
Console.WriteLine(iterator.Current.Value);
}

1

Try changing the XPath expression as demonstrated below.

iterator = navigator.Select("/Employees/Employee");
iterator = navigator.Select("/Employees/Employee[Age>22]");
iterator = navigator.Select("/Employees/Employee[Age>22]/Name");
Hope this helps :-)

No comments: