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"?>




            <dept id="accounts">






            <dept id="HR">













Accessing nodes with XPath

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 eliminate few nodes returned from the XPath expression and can choose specific node and node that contains specific value. Predicates are embedded in [] brackets.

Predicates in XPath

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


XPath wildcards are used to select XML elements regardless of their name.

Wildcards in XPath





Selects all elements

/data/* - Selects all child elements of data element.


›› go to examples ››