XML technologies / XSLT / Introduction to XSLT 2.0 / XSLT and XPath – round three / Dates, durations and timestamps / Constructing date, time and timestamp values

(Excerpt from “XSLT 2.0 & XPath 2.0” by Frank Bongers, chapter 3.)

XPath 2.0, and therefore XSLT 2.0, performs no implicit typecasting. The author must ensure values have the types an operation requires. Two dates can be subtracted, producing a duration xs:duration or similar. Operator “-” normally expects numeric types and produces a duration only when both operands have type xs:date or a comparable type.

Trying this with strings, even syntactically valid dates, causes an error: no automatic conversion takes place. This does not work:

<xsl:variable name="datum_1" select="'2007-01-01'"/>
<xsl:variable name="datum_2" select="'2007-07-01'"/>

<!-- Achtung: Fehler!!! -->
Zeitabstand: <xsl:value-of select="$datum_2 - datum_1"/>

The error is “Arithmetic operator is not defined for arguments of types (xs:string, xs:string)”. Strings cannot meaningfully be subtracted; typecasting or prior construction of the required type is necessary.

The construction of a type needs a constructor function accepting an input value. Its name conveniently matches its XML Schema type: xs:date() for dates of type xs:date. The variable itself can be input, constructing the value during output:

<xsl:value-of select="xs:date($datum_2)-xs:date($datum_1)"/>

Code example: kap03/3.05/date.xsl (excerpt).

Construction could also occur when declaring the variable:

<xsl:variable name="datum_1" select="xs:date('2007-01-01')"/>
  

Code example: kap03/3.05/date.xsl (excerpt).

A typecast is slightly more cumbersome, using operator cast as. This also works:

$datum_2 cast as xs:date - $datum_1 cast as xs:date

The result is duration P181D, the difference in days. This approach allows checking beforehand whether conversion is possible with test castable as:

if ($datum_3 castable as xs:date)
  then($datum_3 cast as xs:date)
  else(fn:error(err:konvertierungsfehler,'Casting nicht möglich'))

Code example: kap03/3.05/date.xsl (excerpt).

If the value in $datum_3 cannot be converted, fn:error() sends an error to SystemOut, but processing stops without a result!

<xsl:variable name="datum_3" select="'Hahaha'"/>
  

Storing an unconvertible string in $datum_3, as here, makes Saxon report:

FOER0000: Casting nicht möglich net.sf.saxon.trans.DynamicError: Casting nicht möglich

Here, FOER0000 means “unidentifiable error”. The first argument of function fn:error() is a QName identifying the error. Here the QName is unknown to the system, which still outputs the requested message. The error QName uses XPath error namespace "http://www.w3.org/2005/xqt-errors" and prefix err.

   

back to top