Jun 8, 2013

How to get XML nodes using XPath expression?

1 comment
To find nodes in an XML file we can use XPath expressions. System.Xml namespace provides following methods to retrieve nodes using xpath expression,
  1. XmlNode.SelectNodes - returns a list of nodes selected by the xpath string.
  2. XmlNode.SelectSingleNode – returns a first node that matches the xpath string.
We will write code using the following sample XML file.

<Employees>
  <Employee Gender=’F’>
    <Name>
        <FirstName>Aashi</FirstName>
        <LastName>Mishra</LastName>
    </Name>
  </Employee>
  <Employee Gender=’M’>
    <Name>
        <FirstName>Cameron</FirstName>
        <LastName>White</LastName>
    </Name>
  </Employee>
</Employees>

To get all nodes use xpath expression /Employees/Employee/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 we can use index of XmlNode with the node name: node["FirstName"].InnerText

See the example below.

XmlDocument xml = new XmlDocument();

// xmlString contains the above mentioned xml data
xml.LoadXml(xmlString);
XmlNodeList nodes = xml.SelectNodes("/Employees/ Employee/Name");
foreach (XmlNode node in nodes)
{
  string firstName = node["FirstName"].InnerText;
  string lastName = node["LastName"].InnerText;
  Console.WriteLine("Employee Name: {0} {1}", firstName, lastName);
}

In the above example, we are retrieving values of XMLElement. Similar way, we can get data of XMLAttribute using xpath expression. 

Here I will give an example to get values of Gender attribute, /Employees/Employee/@Gender

1 comment :