Friday, June 11, 2010

Select XML Nodes by Name [C#]

To find nodes in an XML file you can use XPath expressions. Method XmlNode.Selec­tNodes returns a list of nodes selected by the XPath string. Method XmlNode.Selec­tSingleNode finds the first node that matches the XPath string.




Suppose we have this XML file.



[XML]







Juby /FirstName>

Varghese





James

White





To get all nodes use XPath expression /Names/Name. The first slash means that the node must be a root node. SelectNodes method returns collection XmlNodeList which will contain the nodes. To get value of sub node 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 "..."



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