CSharp examples for XML:XPath
XPath Expression Syntax
Expression | Description | Example |
---|---|---|
/ | Starts an absolute path /Order/Items/Item selects all Item elements that are children that selects from the root of an Items element, which is itself a child of the root Order node. element. | |
// | Starts a relative path that selects nodes anywhere. | //Item/Name selects all the Name elements that are children of an Item element, regardless of where they appear in the document. |
@ | Selects an attribute of a node. | /Order/@id selects the attribute named id from the root Order element. |
* | Selects any element in the path. | /Order/* selects both Items and Client nodes because both are contained by a root Order element. |
| | Combines multiple paths. | /Order/Items/Item/Name|Order/Client/Name selects the Name nodes used to describe a Client and the Name nodes used to describe an Item. |
. | Indicates the current (default) node. | If the current node is an Order, the expression ./Items refers to the related items for that order. |
.. | Indicates the parent node. | //Name/.. selects any element that is parent to a Name, which includes the Client and Item elements. |
[ ] | Defines selection criteria that can test a contained node or an attribute value. | /Order[@id="2020-01-30.195496"] selects the Order elements with the indicated attribute value. /Order/Items/Item[Price > 50] selects products higher than $50 in price. /Order/Items/Item[Price > 50 and Name="Laser Printer"] selects products that match two criteria. |
starts- with | Retrieves elements based on what text a contained element starts with. | /Order/Items/Item[starts-with(Name, "C")] finds all Item elements that have a Name element that starts with the letter C. |
position | Retrieves elements based on position. | /Order/Items/Item[position ()=2] selects the second Item element. |
count | Counts elements. You specify the name of the child element to count or an asterisk (*) for all children. | /Order/Items/Item[count(Price) = 1] retrieves Item elements that have exactly one nested Price element. |
using System;//from w w w .j a va 2 s .com using System.Xml; public class XPathSelectNodes { [STAThread] private static void Main() { // Load the document. XmlDocument doc = new XmlDocument(); doc.Load("orders.xml"); XmlNodeList nodes = doc.SelectNodes("/Order/Items/Item/Name"); foreach (XmlNode node in nodes) { Console.WriteLine(node.InnerText); } Console.ReadLine(); } }