Select Specific Nodes From XML Using XPath in C#
This example shows how to use an XPath expression in C#. In the sample code, there are two queries. The first of them selects top 2 nodes(vegetable) from xml document. Another query selects price nodes with price > 15. To select nodes from XML, we use the method “XmlDocument.SelectNodes” in System.Xml namespace. Then we pass XPath expression as a parameter.
//Suppose we have this XML file.
string xml =
"" +
" " +
" Pepper " +
" 10 " +
" " +
" " +
" Onion " +
" 20 " +
" " +
" " +
" Garlic " +
" 5 " +
" " +
" " +
" Corn " +
" 35 " +
" " +
" ";
//
// Creates an XmlDocument to load the xml data.
//
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.LoadXml(xml);
//
// Select top 2 vegetables from the xml document.
//
string expression = "/Vegetables/Vegetable[position() <= 2]";
XmlNodeList nodes = xmlDocument.SelectNodes(expression);
foreach (XmlNode node in nodes)
{
Console.WriteLine("Vegetable: {0}", node["Name"].InnerText);
}
//Output:
//Vegetable: Pepper
//Vegetable: Onion
//
// Select price nodes with price > 15
//
expression = "/Vegetables/Vegetable[Price>15]/Price";
nodes = xmlDocument.SelectNodes(expression);
foreach (XmlNode node in nodes)
{
Console.WriteLine("Price: {0}", node.InnerText);
}
//Output:
//Price: 20
//Price: 35