Predicates are used in a path expression to filter the results to contain only nodes that meet specific criteria. Using a predicate, you can, for example, select only the elements that have a certain value for an attribute or child element, using a predicate like [@dept="ACC"]. You can also select only elements that have a particular attribute child element, using a predicate such as [color], or elements that occur in a particular position within their parent, using a predicate such as [3].
The syntax of a predicate is simply an expression in square brackets ([ and ]). Table 4-6 shows some examples of predicates.
Table 4-6. Predicates (examples start with doc("catalog.xml")/catalog/)
Example
Meaning
product[name = "Floppy Sun Hat"]
All productelements that have a namechild whose value is equal to Floppy Sun Hat
product[number < 500]
All productelements that have a numberchild whose value is less than 500
product[@dept = "ACC"]
All productelements that have a deptattribute whose value is ACC
product[desc]
All productelements that have at least one descchild
product[@dept]
All productelements that have a deptattribute
product[@dept]/number
All numberchildren of productelements that have a deptattribute
If the expression evaluates to anything other than a number, its effective Boolean value is determined. This means that if it evaluates to the xs:boolean value false, the number 0 or NaN, a zero-length string, or the empty sequence, it is considered false. In most other cases, it is considered true. If the effective Boolean value is true for a particular node, that node is returned. If it is false, the node is not returned.
If the expression evaluates to a number, it is interpreted as the position as described in "Using Positions in Predicates" later in this chapter.
As you can see from the last example, the predicate is not required to appear at the end of the path expression; it can appear at the end of any step.
Note that product[number] is different from product/number. While both expressions filter out products that have no number child, in the former expression, the product element is returned. In the latter case, the number element is returned.