Filter expressions

A filter expression consists of a primary expression that is followed by zero or more predicates. The predicates, if present, filter the sequence that is returned by the primary expression.

The result of the filter expression consists of all of the items with a predicate truth value of true that are returned by the primary expression. If no predicates are specified, the result is simply the result of the primary expression. The items in the result sequence are in the same order as the items that are returned by the primary expression. During evaluation of a predicate, each item has a context position that represents its position in the sequence that is being filtered by that predicate. The first context position is 1.

Syntax

Read syntax diagramSkip visual syntax diagramPrimaryExpression[PredicateExpression]
PrimaryExpression
A primary expression.
PredicateExpression
An expression that determines whether items of the sequence are retained or discarded.

Examples

The following examples use filter expressions to return a filtered sequence:
  • Given a sequence of products bound to a variable, this expression returns only those products with a price that is greater than 100:
    $products[price gt 100]
  • This expression uses a range expression with a predicate to list all integers from 1 to 100 that are divisible by 5. The range expression is processed as a primary expression because it is enclosed in parentheses:
    (1 to 100)[. mod 5 eq 0]
  • This expression results in the integer 5:
    (1 to 21)[5]
  • This expression uses a filter expression as a step in a path expression. The expression returns the last chapter or appendix within the book that is bound to the variable $book:
    $book/(chapter | appendix)[fn:last()]