c#,xml,nodes,attribute

Kerim 8/13/2016 0

This Code Shows How to Select XML Nodes by Attribute Value

C#
 [XML]
<Names>
    <Name>James</Name>
    <Name>John</Name>
    <Name>Robert</Name>
    <Name>Michael</Name>
    <Name>William</Name>
    <Name>David</Name>
    <Name>Richard</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]. See the example below.

[C#]
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);
}

The output is:

James
John
Robert
Michael
William 

Report Bug

Please Login to Report Bug

Reported Bugs

Comments

Please Login to Comment

Comments