The XPath is primarily used to access elements and attributes. The syntax and example shows accessing elements in an XML document.
Example how to elements and attributes with XPath
<?xml version="1.0" encoding="UTF-8"?>
<data>
<employee>
<office>
<dept id="accounts">
<name>Raju</name>
<age>50<age>
</dept>
</office>
<office>
<dept id="HR">
<name>Malini</name>
<age>30<age>
</dept>
</office>
</employee>
<student>
<school>
<name>Lucy</name>
</school>
</student>
</data>
Expression | Description | Example (from document given above) |
---|---|---|
nodename | Selects all nodes with name ‘nodename’ | employee : selects all nodes with name ‘employee’ |
/ | Selects from root node | / root – Selects root element “data”. |
// | Selects nodes, from current node that matches the selection. The match can be found anywhere in the document | //name – selects all the name elements from the document. |
. | Selects current node | ./office – Selects all elements within name context |
.. | Selects parent of the current node | ../office – Selects parent of the current node |
| | This operator selects several paths | //office | //school – Selects all the office and school elements |
Predicates
Predicates eliminate few nodes returned from the XPath expression and can choose specific node and node that contains specific value. Predicates are embedded in []
brackets.
Path Expression | Result |
---|---|
/data/employee/office[1] | Selects first book element that is child of /data/employee |
/data/employee/office[last()] | Selects last office element that is child of /data/employee |
/data/employee/office[last()-1] | Selects last but one office element that is child of /data/employee |
/data/employee/office[position() < 10] | Selects first nine office element that is children of /data/employee |
/data/employee/office[age<40]/name | Selects “name” of all office elements that have age less than 40 |
/data/employee/office[age<40] | Selects all office elements with age element less than 40 |
Wildcards
XPath wildcards are used to select XML elements regardless of their name.
Wildcard |
Description |
Example |
---|---|---|
* |
Selects all elements |
/data/* - Selects all child elements of data element. |
Comments
No comments have been made yet.
Please login to leave a comment. Login now