Read XSLT 2.0 and XPath 2.0 Programmer's Reference, 4th Edition Online
Authors: Michael Kay
Conditional expressions are one of the few places in the XPath language where you get a guarantee that an expression will or will not be evaluated. Specifically, if the condition is true then the
else
branch will not be evaluated, while if it is false, the
then
branch will not be evaluated. This means you can safely use expressions that could otherwise cause errors, for example:
if ($cols ne 0) then (count($items) idiv $cols) else ()
I personally prefer putting in the explicit test
$cols ne 0
rather than writing
if ($cols)..
and relying on the fact that zero is treated as false.
Changes in XPath 2.0
Conditional expressions are new in XPath 2.0. In the context of an XSLT stylesheet, they often make it possible to replace a cumbersome
can now be replaced with:
select=“if ($day eq ‘Sunday’) then ‘white’ else ‘red’”/>
The rules for calculating the effective boolean value of an expression have been carefully chosen to be compatible with the rules for converting strings, numbers, or node-sets to booleans in XPath 1.0, while at the same time generalizing them to handle an arbitrary sequence. If they seem arbitrary, blame history.
Examples
Expression | Description |
if (@x) then @x else 0 | Returns the attribute node @x if it exists, or the xs:integer value zero otherwise. (This can also be expressed as (@x,0)[1] .) |
if ($area/sales) then avg($area/sales/@value) else number(‘NaN’) | Returns the average sales value for the selected area if there were any sales, or the not-a-number value NaN otherwise. |
if (normalize-space(.)) then string(.) else () | Returns the context item converted to a string if it contains any non-whitespace characters; otherwise, returns the empty sequence. This relies on the fact that normalize-space() returns a zero-length string (which is treated as false ) if all the characters in the string are whitespace. |