Filtering of node sets by using predicates

XPath expressions are used to select nodes within XML trees. XPath expressions can be used for complex problems if there is a possibility to filter the current expressions once again in order to define more exact target volumes of nodes. For this application, XPath expressions may contain so-called predicates. Predicates are expressions which return a Boolean value (true or false) and thus define for each selected node a new filter. If a node from a node set matches with the expression of a predicate (which means the condition is true), this node remains in the result node set. If the Boolean value is false for a node, it will be filtered out of the node set. The initial situation is always a node volume which will be refined (limited).

Filtering of node sets

The //adresse expression selects all "adresse" (address) element nodes of the document. In a second step, namely the application of a predicate on the selected node volume, the volume is reduced. Only those elements remain in the node volume which meet the condition that the "ort" (location) child element has the value "Stuttgart". All other elements are filtered out.

The expression in a predicate can also express other value comparisons in addition to a string comparison. Examples are:

Pure string comparison address[name="Willy Wonka"]
Numerical comparison (greater) Album[@evaluation > 3]
Numerical comparison (less than or equal) //Song[@year <= 1990]
Combination of "greater" and "not equal" Album[@evaluation < 2]/Song[@year != 2000]

In addition to a value comparison, a node set can also be checked for coexistence of other elements.

/addressList[address] Check for existence of a "address" child element.
/addressList/address[@cat] Check for existence of a "cat" attribute within "address".

Attention: A predicate only checks for true or false. Implicit convertion into Boolean.

 

<< back next >>

Copyright © dpunkt.verlag GmbH 2007
Printing of the online version is permitted exclusively for private use. Otherwise this chapter from the book "Professionelle XML-Verarbeitung mit Word" is subject to the same provisions as those applicable for the hardcover edition: The work including all its components is protected by copyright. All rights reserved, including reproduction, translation, microfilming as well as storage and processing in electronic systems.

dpunkt.verlag GmbH, Ringstraße 19B, 69115 Heidelberg, fon 06221-14830, fax 06221-148399, hallo(at)dpunkt.de