How to select Top N nodes of the specific name from an XML document.

Prabhukiran345
Posted by Prabhukiran345 under C# category on | Points: 40 | Views : 466
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>Kiran</Name>
<Name>Prabhu</Name>
<Name>Govind</Name>
<Name>Sravan</Name>
<Name>Raghu</Name>
<Name>Srinath</Name>
<Name>Syam</Name>
</Names>

To get all <Name> nodes use XPath expression /Names/Name. If you don't want to selected all nodes, but only top 5 nodes, you can uses XPath expression like this /Names/Name[position() <= 5].
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);
}


OutPut:
Kiran
Prabhu
Govind
Sravan
Raghu

Comments or Responses

Login to post response