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

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

Filter Expressions

A filter expression is used to apply one or more
Predicates
to a sequence, selecting those items in the sequence that satisfy some condition.

Expression
Syntax
FilterExpr
PrimaryExpr Predicate*
Predicate
[
Expr
]

A
FilterExpr
consists of a
PrimaryExpr
whose value is a sequence, followed by zero or more
Predicates
that select a subset of the items in the sequence. Each predicate consists of an expression enclosed in square brackets, for example
[@name = ‘London’]
or
[position() = 1]
.

Since in XPath 2.0 every value is a sequence, it is possible to apply predicates to any value whatsoever. For example, the expression
concat($n, “ error”, “s”[$n!=1])
outputs a string such as “0 errors”, “1 error”, or “5 errors”. In the case where
$n
is 1, the third argument to
concat()
is an empty sequence, which contributes nothing to the output.

Recall from Chapter 7 that a
PrimaryExpr
is a literal, a variable reference,
.
, a function call, or a parenthesized expression. This means that if you want to filter the result of any expression other than the first four in this list, you will have to write it in parentheses.

Each predicate is applied to the sequence in turn; only those items in the sequence for which the predicate is true pass through to the next stage. The final result consists of those items in the original sequence that satisfy each of the predicates, retaining their original order.

A predicate may be either a numeric predicate (for example
[1]
or
[last()-1]
), or a boolean predicate (for example
[count(*) gt 5]
or
[@name and @address]
). If the value of the expression is a single number, it is treated as a numeric predicate; otherwise, it is converted, if necessary, to an
xs:boolean
and is treated as a boolean predicate. The conversion is done using the rules for computing the
effective boolean value
, which are the same rules as are used for the condition in an
if
expression (described in Chapter 7 on page 551) or for the operand of the
boolean()
function (described in Chapter 13 on page 721), except that if the value is a single number—which might be an integer, decimal, float, or double—then the predicate is treated as a numeric predicate rather than a boolean predicate.

Other books

Firefox Down by Craig Thomas
The Godforsaken Daughter by Christina McKenna
Sellevision by Augusten Burroughs
Win, Lose or Die by John Gardner
The Bloody White Baron by James Palmer
Carrie Goes Off the Map by Phillipa Ashley