XML technologies / XPath / XPath 2.0: language reference / XPath expressions: operators and keywords / Conditional expressions
(Excerpt from "XSLT 2.0 & XPath 2.0" by Frank Bongers, chapter 4.)
Keywords: if, then, else
XPath supports conditional evaluation of subexpressions using a test expression in an if-then-else construct:
if testausdruck
then ausdruck_1
else ausdruck_2
The expression after if is treated as a Boolean test. If its effective Boolean value is true, the subexpression after then is evaluated and the one after else is ignored. Conversely, if the test yields false, only the branch after else is executed. Dynamic errors in the branch that is not evaluated are ignored.
Runtime errors therefore matter only in the branch actually evaluated. Here, a comparison serves as the test:
if ($haendler1/preis < $haendler2/preis)
then $bestellung1
else $bestellung2
Parentheses around the preceding comparison are not strictly necessary because operator “<” has higher precedence than keyword “if”. They do, however, make the expression clearer visually.
The following example tests whether attribute schulrabatt exists and selects different ordering options accordingly. Its actual value is irrelevant:
if (@schulrabatt)
then $buch/klassensatzbestellung
else $buch/einzelbestellung
Looking back at XPath 1.0
Control structures were introduced in XPath 2.0. XPath 1.0 cannot express conditional subexpressions within an XPath expression.
Copyright © Galileo Press, Bonn 2008
You may print the online version for private use.
Otherwise, this chapter from "XSLT 2.0 & XPath 2.0 ― Das umfassende Handbuch" is subject to the same terms as the bound edition: the work and all its parts are protected by copyright. All rights reserved, including reproduction, translation, microfilming, storage and processing in electronic systems.
Galileo Press, Rheinwerkallee 4, 53227 Bonn