RSS

Select Top XML Nodes using XPath in C#

Wed, Dec 2, 2009

Programming, Tutorials

Following exampel demonstrates how can we select Top N nodes from an XML document.
We can use method XmlNode.Selec­tNodes and Pass XPath expression as a parameter to select Xml Node.

Sample XML file

1
2
3
4
5
6
7
8
9
<Names>
    <Name>James</Name>
    <Name>Wyane</Name>
    <Name>Green</Name>
    <Name>Ballack</Name>
    <Name>Gallass</Name>
    <Name>Rahul</Name>
    <Name>Cashmen</Name>
</Names>

We can get all nodes by using this XPath expression:

 /Names/Name.

We can get only top 5 nodes by using XPath expression:

 /Names/Name[position() <= 5]

Sample Code

1
2
3
4
5
6
7
XmlDocument doc = new XmlDocument();
doc.LoadXml(str);
XmlNodeList nodes = doc.SelectNodes("/Names/Name[position() <= 5]");
foreach (XmlNode node in nodes)
{
  Console.WriteLine(node.InnerText);
}

OUTPUT:

Frank
Wyane
Green
Ballack
Gallass
Sharing ~ Helping Other:
  • Print
  • email
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • BlinkList
  • DZone
  • Slashdot
  • YahooMyWeb
  • StumbleUpon
  • Live
  • IndianPad
  • DotNetKicks
  • Technorati

Related Posts:

, , ,

This post was written by:

eXclusiveMinds - who has written 498 posts on eXclusiveMinds.


Contact the author

Leave a Reply

You must be logged in to post a comment.