XPath Reference

Predicates & Operators

Predicates are the square-bracket filters that narrow a node-set down to the items you actually want. Combined with comparison and boolean operators, they turn XPath into a tiny query language — pick the third item, the last one, the ones whose price is over ten, the ones with a particular attribute and not another. This is where most real XPath work happens.

[n]

Position predicate (1-based)

A numeric predicate selects the node at that position within its context. Positions start at 1, not 0. So ingredient[2] selects the second ingredient child. This is one of the most common predicates — use it whenever you need a specific item from an ordered set.

Example: book[1]

[last()]

Last item in context

The last() function returns the position of the final node in the current context. Using it as a predicate selects only the last node in a set. It's perfect when you need the final step, the last ingredient, or the most recent entry without knowing how many there are.

Example: item[last()]

[position() < 3]

First two items

The position() function returns the 1-based index of each node in its context. You can use comparison operators with it to select ranges — position() < 3 gives the first two items, position() > 2 skips them. This is how you do slicing and pagination in XPath.

Example: li[position() < 3]

=, !=

Equality / inequality

The equality operator compares values. When used with attributes or element content, it performs string comparison. When comparing node-sets, it returns true if any node in the set matches. Inequality (!=) is the opposite — true if the values differ.

Example: @type = 'fiction'

<, >, <=, >=

Comparison operators

Standard comparison operators for numeric and string comparisons. In XPath, values are automatically converted to numbers when used with these operators. They're essential for filtering by quantities, dates, or any ordered values.

Example: price > 10

and, or, not()

Boolean operators

Boolean logic for combining conditions in predicates. 'and' requires both conditions to be true, 'or' requires at least one, and not() inverts a condition. These let you build complex filters — for example, selecting elements that have one attribute but lack another.

Example: @a and @b

|

Union of node-sets

The union operator combines two node-sets into one. The result contains all nodes from both sets, with duplicates removed and document order preserved. It's how you select multiple different things in a single expression — like grabbing both names and cuisine elements at once.

Example: title | name

← Back to full reference