Conditional expression based on if
, then
,
and else
.
An IfExpr
implements a conditional expression. The
expression following the if
keyword is called the test
expression, the expression following the then
keyword is
called the then-expression and the final one is called the
else-expression. If the effective boolean value of the test expression
is true, then the value of the then-expression is returned, otherwise the value
of the else-expression is returned.
In contrast to other languages the else-expression is mandatory. If you do not need the else-expression, you can return an empty string, or a NaN value if you need a numerical value.
Return all books with their titles and net prices:
for $a in input()/bib/book let $vatrate := 16 let $net := if ($a/price) then xs:decimal($a/price) - xs:decimal($a/price) div ( 100 + $vatrate ) * $vatrate else xs:double("NaN") return <book> <title>{$a/title}</title> <price> <net>{ $net }</net> </price> </book>
The conditional expression checks for the presence of a
book
child element price
and returns the price minus the value added tax rate. Alternatively, you can
place the IfExpr
in the return clause:
for $a in input()/bib/book let $vatrate := 16 return <book> <title>{$a/title}</title> <price> <net>{ if ($a/price) then xs:decimal($a/price) - xs:decimal($a/price) div ( 100 + $vatrate ) * $vatrate else xs:double("NaN") }</net> </price> </book>
The following construct(s) refer to this construct: