Predicates
There’s one more aspect of XPath expressions that we
haven’t discussed: predicates. These are filters
that restrict the nodes selected by an XPath expression. Each
predicate is evaluated and converted to a Boolean value (either
true
or false
). If the predicate is true
for a given node, that node will be
selected; otherwise, it isn’t. Predicates always appear inside square
brackets ([]
). Here’s an
example:
<xsl:apply-templates select="line[position() = 7]"/>
This expression selects the seventh <line>
element in the current context.
If there are six or fewer <line>
elements in the current
context, this XPath expression returns an empty node-set. Several
things can be part of a predicate; we’ll go through them here.
Numbers in predicates
Instead of using the position()
function, we can use a
number. For example, the XPath expression line[7]
selects the seventh <line>
element in the context node;
this means exactly the same thing as line[position() = 7]
. XPath also
provides the boolean and
and
or
operators as well as the union
operator (|
) to combine
predicates. The expression line[position()=3 and @style]
matches
all <line>
elements that
occur third and that have a style
attribute, while line[position()=3 or
@style]
matches all <line>
elements that either occur
third or have a style
attribute.
You can use more than one predicate if you like;
line[3][@style]
or line[@style][3]
are both legal. They aren’t equivalent, however. Predicates are evaluated from left to right. The XSLT ...
Get XSLT, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.