The filter expression is used to filter sequences. Filters are commonly used in combination with path expressions to create more precise selectors.
Context item expression
Before you can get started with filters, you'll need to know what a context item expression is and how it works. It is a very simple expression, but very useful while filtering sequences.
Context item expression example
A filter expression consists of a base expression and a predicate. The base expression will be evaluated first. This will result in an input sequence that will be filtered. The predicate is an expression written in square brackets ("
[" and "
]") and directly follows the base expression. You can identify filter expressions by these square brackets.
Since the predicate is an expression, it can be evaluated. It will be evaluated for each item in the input sequence. The predicate is evaluated with an inner focus. This means that:
The predicate may return anything since it is just a regular expression. The result of the predicate is turned into an xs:boolean value. This value is called the predicate truth value. If the predicate truth value is true, the item for which the predicate is evaluated will be kept. If the predicate truth value is false, the item for which the predicate is evaluated will be discarded.
The predicate truth value is determined by applying two rules to the result of the predicate. First, if the result is a singleton atomic value of a numeric type or derived from a numeric type, the predicate truth value is true if the result is equal to the context position, and false otherwise. For all other data types, the predicate truth is the effective boolean value of the result.
The ordering of the resulting sequence is the same as the ordering of the input sequence.
Whew, that was a lot of information. Here are some examples of filter expressions.
Filtering atomic values
This is a short example. The base expression creates a sequence of xs:integer values using a range expression. The filter will keep every item with a value greater than 5. As you can see here, the context item is used to compare the value of each individual item in the input sequence.
(1 to 10)[. gt 5]
Ordering of items
This short example shows that the ordering of items in the input sequence is the same as the ordering in the resulting sequence. The predicate will be false for every value that is an odd value.
(1 to 10)[. mod 2 eq 0]
Accessing members of a sequence
You may have seen a similar example before. The predicate returns a numeric value. According to the rules for determining the predicate truth value, it is compared to the context position. If it is equal to the context position, the predicate truth value is true, returning the item from the sequence on position two.
("a", "b", "c")