XPath cheat sheet

The XML Example Document

We will use the following XML document in the examples below.

<?xml version="1.0" encoding="ISO-8859-1"?>

<bookstore>

<book>

<title lang="eng">Harry Potter</title>

<price>29.99</price>

</book>

<book>

<title lang="eng">Learning XML</title>

<price>39.95</price>

</book>

</bookstore>

Selecting Nodes

XPath uses path expressions to select nodes in an XML document. The node is selected by following a path or steps. The most useful path expressions are listed below:

In the table below we have listed some path expressions and the result of the expressions:

Predicates

Predicates are used to find a specific node or a node that contains a specific value.

Predicates are always embedded in square brackets.

In the table below we have listed some path expressions with predicates and the result of the expressions:

Selecting Unknown Nodes

XPath wildcards can be used to select unknown XML elements.

In the table below we have listed some path expressions and the result of the expressions:

Selecting Several Paths

By using the | operator in an XPath expression you can select several paths.

In the table below we have listed some path expressions and the result of the expressions:

XPath Axes

An axis defines a node-set relative to the current node.

Location Path Expression

A location path can be absolute or relative.

An absolute location path starts with a slash ( / ) and a relative location path does not. In both cases the location path consists of one or more steps, each separated by a slash:

An absolute location path:

/step/step/...

A relative location path:

step/step/...

Each step is evaluated against the nodes in the current node-set.

A step consists of:

  • an axis (defines the tree-relationship between the selected nodes and the current node)
  • a node-test (identifies a node within an axis)
  • zero or more predicates (to further refine the selected node-set)

The syntax for a location step is:

axisname::nodetest[predicate]

Examples