Read XSLT 2.0 and XPath 2.0 Programmer's Reference, 4th Edition Online
Authors: Michael Kay
The following table shows some examples of positional predicates.
Expression | Description |
para[1] | Selects the first |
para[last()] | Selects the last |
para[position()! = 1] | Selects all |
para[position() = 1 to 5] | Selects the first five = operator returns true if the left-hand operand ( position() ) contains a value that is equal to one of the items in the right-hand operand ( 1 to 5 ), which is true if position() is in the range 1 to 5 . |
para[last()-1] | Returns the last but one |
para[3.2] | Returns an empty sequence. The value 3.2 is treated as a numeric predicate. The value of position() will never be equal to 3.2, so no elements are selected. |
para[position()] | Selects all child [position()= position()] , which is always true . |
para[position()-1] | Returns an empty sequence. The predicate expands to [position() = position()-1] , which is always false . |
para[number(@nr)] | Returns every child nr attribute whose numeric value is equal to the position of the |
An
AxisStep
can contain a sequence of zero or more predicates. Specifying two separate predicates is not the same thing as combining the two predicates into one with an
and
operator. The reason is that the context for the second predicate is different from the context for the first. Specifically, in the second predicate, the context position (the value of the
position()
function) and the context size (the value of the
last()
function) consider only those nodes that successfully passed through the previous predicate. What this means in practice is shown in the examples below:
Expression | Description |
book[author = “P. D. James”][1] | The first book that was written by P. D. James. |
book[1][author = “P. D. James”] | The first book, provided that it was written by P. D. James. |
book[position() = 1 and author = “P. D. James”] | The first book, provided that it was written by P. D. James. This is the same as the previous example, because in that example the second predicate is not dependant on the context position. |
Abbreviated Axis Steps
Logically, an axis step has three parts, which we have examined in the previous sections: the axis, the node test, and the predicates. However, the most commonly used axis steps can be written in an abbreviated notation, and in this section we will look at these abbreviations.
In XPath 1.0, the expression
.
was considered to be an abbreviation for the step
self::node()
. In XPath 2.0 this is no longer the case, because
.
can also be used when the context item is an atomic value rather than a node. For this reason,
.
is now classified as a primary expression in its own right, and was therefore covered with the other kinds of primary expression in Chapter 7.