XPath can quickly navigate to a node or attribute in the XML. The XPath syntax is simple, but powerful enough, and it is also the basic knowledge of using XSLT.
Sample xml:
| 1234567891011121314151617181920212223242526272829 |
<?xmlversion="1.0" encoding="utf-8" ?><pets> <cat color="black" weight="10"> <price>100</price> <desc>this is a black cat</desc> </cat> <catcolor="white" weight="9"> <price>80</price> <desc>this is a white cat</desc> </cat> <catcolor="yellow" weight="15"> <price>80</price> <desc>this is a yellow cat</desc> </cat> <dogcolor="black" weight="10"> <price>100</price> <desc>this is a black dog</desc> </dog> <dogcolor="white" weight="9"> <price>80</price> <desc>this is a white dog</desc> </dog> <dogcolor="yellow" weight="15"> <price>80</price> <desc>this is a yellow dog</desc> </dog></pets> |
Syntax for XPath:
1. Symbols in XPath
Symbol |
Description |
Example |
Example description |
/ |
Represents the start of the root node selection |
/pets |
Select the root node pets |
Represents a spacer between a node and a child node |
/pets/dog |
Select the Dog node under the Pets node |
Xx |
Represents a lookup from an entire XML document regardless of the current node location |
Price |
Select all the price nodes in the document |
. |
A single English half-width period indicates the selection of the current node |
/pets/. |
Select Pets Node |
.. |
Two points, which means selecting the parent node |
/pets/dog[0]/. |
Represents the Pets node, the parent node of the first dog node |
@xx |
Represents a selection attribute |
dog/@color |
Represents a collection of color properties that select all the dog nodes |
[...] |
The brackets indicate the selection criteria, which are the conditions in parentheses |
dog[@color = ' White '] |
All dog nodes that are color white |
DOG[/PRICE<100] |
All dog nodes with a price byte point value less than 100 |
The number in brackets is the node index, like in C # and other languages, array subscript is starting from 1 |
DOG[1] |
A 1th dog node |
Dog[last ()] |
The last dog node, finally () is an XPath built-in function |
| |
Single vertical bar indicates merge node combination |
dog[@color = ' White ' | cat[@color = ' White '] |
The Color property is White's dog node and the color property is White's cat node |
* |
An asterisk indicates the node or attribute of any name |
dog/* |
Represents all child nodes of the dog node |
dog/@* |
All attribute nodes that represent the dog node |
XPath syntax using XPath examples in C #