XSLT 2.0 and XPath 2.0 Programmer's Reference, 4th Edition (437 page)

BOOK: XSLT 2.0 and XPath 2.0 Programmer's Reference, 4th Edition
10.63Mb size Format: txt, pdf, ePub

A consequence of the rule is that if the predicate is a number that is not equal to an integer, the result will be an empty sequence. For example,
$S[last() div 2]
will select nothing when the value of
last()
is an odd number. If you want to select a single item close to the middle of the sequence, use
$S[last() idiv 2]
, because the
idiv
operator always returns an integer.

In nearly all practical cases, a numeric predicate selects either a single item from the sequence or no items at all. But this is not part of the definition. To give a counter-example,
$x[count(*)]
selects every node whose position is the same as the number of children it has.

As discussed in Chapter 7, every XPath expression is evaluated in some context. For an expression used as a predicate, the context is different from the context of the containing expression. While evaluating each predicate, the context is established as follows:

  • The
    context item
    (the item referenced as
    .
    ) is the item being tested.
  • The
    context position
    (the value of the
    position()
    function) is the position of that item within the sequence of items surviving from the previous stage.
  • The
    context size
    (the value of the
    last()
    function) is the number of items surviving from the previous stage.

To see how this works, consider the filter expression
$headings[self::h1][last()]
. This starts with the sequence of nodes that is the value of the variable
$headings
(if this sequence contains items that are not nodes, then evaluating the predicate
self::h1
will raise an error). The first predicate is
[self::h1]
. This is applied to each node in
$headings
in turn. While it is being applied, the context node is that particular node. The expression
self::h1
is a path expression consisting of a single
AxisStep
: it selects a sequence of nodes. If the context node is an


element this sequence will contain a single nodeā€”the context node. Otherwise, the sequence will be empty. When this value is converted to a boolean, it will be
true
if it contains a node, and
false
if it is empty. So the first predicate is actually filtering through those nodes in
$headings

Other books

Possession by C. J. Archer
An Uncomplicated Life by Paul Daugherty
The Dryad in Her Pool by Allie Standifer