Select XML Nodes by Name [C#]
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.
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
See also
- [C#] Select XML Nodes by Attribute Value – how to get xml nodes by attribute value
- [C#] Select Top XML Nodes using XPath – how to select first N nodes from XML
- XmlNode – MSDN – base class for all types of xml nodes
- XmlNodeList – MSDN – collection of XmlNode objects
- XmlNode.SelectNodes – MSDN – returns a list of nodes matching the XPath expression
- XmlNode.SelectSingleNode – MSDN – returns the first node matching the XPath