XSLT 2.0 and XPath 2.0 Programmer's Reference, 4th Edition (315 page)

BOOK: XSLT 2.0 and XPath 2.0 Programmer's Reference, 4th Edition
10.16Mb size Format: txt, pdf, ePub
  • By the expression
    $S cast as xs:boolean
  • By the
    xs:boolean()
    constructor function (note the difference from the
    boolean()
    function in the core library, sometimes written as
    fn:boolean()
    to emphasize the difference)
  • When an
    xs:untypedAtomic
    value is implicitly converted to an
    xs:boolean
    value in the course of a function call, where one of the function arguments has a required type of
    xs:boolean

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

instruction. For example, the following:


  

    white

    red

  


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.

Other books

His Love by Jennifer Gracen
The Devil To Pay by Ellery Queen
The Taliban Don't Wave by Robert Semrau
Touch to Surrender by Cara Dee
Wrapped Around My Finger by Kristen Strassel
Stone Cold by Joel Goldman
A Very Dirty Wedding by Sabrina Paige
Dangerously Mine by A.M. Griffin
Angel's Curse by Melanie Tomlin