How To Select Top XML Nodes using XPath

This example shows how to select Top N nodes of the specific name from an XML document. To select nodes from XML use method XmlNode.Selec­tNodes. Pass XPath expression as a parameter and the method returns a list of selected nodes. Suppose we have this XML file.

<Names>
    <Name>James</Name>
    <Name>John</Name>
    <Name>Robert</Name>
    <Name>Michael</Name>
    <Name>William</Name>
    <Name>David</Name>
    <Name>Richard</Name>
</Names>
XmlDocument xml = new XmlDocument();
xml.LoadXml(str);  // suppose that str string contains "<Names>...</Names>"

XmlNodeList xnList = xml.SelectNodes("/Names/Name[position() <= 5]");
foreach (XmlNode xn in xnList)
{
  Console.WriteLine(xn.InnerText);
}

Post a Comment

Please do not post any spam link in the comment box😊

Previous Post Next Post

Blog ads

CodeGuru