How to use Using XPath in C#

No.of Views1626
Bookmarked0 times
Downloads 
Votes0
By  amalhashim   On  15 Feb 2010 23:02:11
Tag : CSharp , How to
How to use Using XPath in C#
emailbookmarkadd commentsprint

Images in this article missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at info@codegain.com

 

Introduction

In this article 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.

{codecitation class="brush: csharp; gutter: true;" width="700px"}





Amal
26

333 Indiana Street



Munna
20
222 West Region




{/codecitation}

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

{codecitation class="brush: csharp; gutter: true;" width="700px"}


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

{/codecitation}

Image Loading....

Try changing the XPath expression as demonstrated below.

{codecitation class="brush: csharp; gutter: true;" width="700px"}



iterator = navigator.Select("/Employees/Employee");

iterator = navigator.Select("/Employees/Employee[Age>22]");

iterator = navigator.Select("/Employees/Employee[Age>22]/Name");

{/codecitation}

I hope this is help to all.

Thank you

Amal

 
Sign Up to vote for this article
 
About Author
 
amalhashim
Occupation-Software Engineer
Company-Aditi Technologies
Member Type-Senior
Location-Not Provided
Joined date-07 Jun 2009
Home Page-http://lamahashim.blogspot.com
Blog Page-http://lamahashim.blogspot.com
I have done my masters in Computer Applications and graduation in Computer Science. I have great passion in working with Microsoft tool and technologies. I am also a Microsoft Most Valuable Professional. Personally my objective is to design/develop applications which eases user experience and performs better in long run.
 
 
Other popularSectionarticles
Comments
There is no comments for this articles.
Leave a Reply
Title:
Display Name:
Email:
(not display in page for the security purphase)
Website:
Message:
Please refresh your screen using Ctrl+F5
If you can't read this number refresh your screen
Please input the anti-spam code that you can read in the image.
^ Scroll to Top