Select XML Nodes by Name
To find nodes in an XML file you can use XPath expressions. Method XmlNode.SelectNodes returns a list of nodes selected by the XPath string. Method XmlNode.SelectSingleNode finds the first node that matches the XPath string.Suppose we have this XML file.
[XML]
<Names> <Name> <FirstName>John</FirstName> <LastName>Smith</LastName> </Name> <Name> <FirstName>James</FirstName> <LastName>White</LastName> </Name></Names>
To get all <Name> nodes use XPath expression
/Names/Name
. The first slash means that the <Names> node must be a root node. SelectNodes method returns collection XmlNodeList which will contain the <Name> nodes. To get value of sub node <FirstName> you can simply index XmlNode with the node name: xmlNode["FirstName"].InnerText
. See the example below.[C#]
XmlDocument xml = new XmlDocument(); xml.LoadXml(myXmlString); // suppose that myXmlString contains "<Names>...</Names>"XmlNodeList xnList = xml.SelectNodes("/Names/Name"); foreach (XmlNode xn in xnList) { string firstName = xn["FirstName"].InnerText; string lastName = xn["LastName"].InnerText; Console.WriteLine("Name: {0} {1}", firstName, lastName); }The output is:
Name: John Smith Name: James White
Select XML Nodes by Attribute Value
This example shows how to select nodes from XML document by attribute value. Use method XmlNode.SelectNodes to get list of nodes selected by the XPath expression. Suppose we have this XML file.
[XML]
<Names> <Name type="M">John</Name> <Name type="F">Susan</Name> <Name type="M">David</Name> </Names>
/Names/Name
. To get only male names (to select all nodes with specific XML attribute) use XPath expression /Names/Name[@type='M']
.
[C#]
XmlDocument xml = new XmlDocument(); xml.LoadXml(str); // suppose that str string contains "<Names>...</Names>"XmlNodeList xnList = xml.SelectNodes("/Names/Name[@type='M']"); foreach (XmlNode xn in xnList) { Console.WriteLine(xn.InnerText); }The output is:
John David
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.SelectNodes. Pass XPath expression as a parameter and the method returns a list of selected nodes. Suppose we have this XML file.
[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
No comments:
Post a Comment