• +49-(0)721-402485-12
Your experts for XML, XQuery and XML Databases

Type expressions

XQuery introduces some expressions for dealing with types being unknown in this form in other languages. The type conversion for atomic types (cast as) has already been dealt with. It may result in a runtime error, if the type conversion cannot be successfully executed. Therefore, the castable operator exists which only checks whether a conversion is possible without executing it.

Testing and converting of complex types is possible with the help of validate. In addition, there is the treat operation which may ensure that a certain type is available and operations by which can be queried whether a certain type is available.

Type testing

XQuery allows the testing whether a type conversion by means of cast would be successful (which means allowed). For this purpose, the castable operator exists which returns false or true, depending on whether a cast would generate a type error or not.

CastableExpr::=Exprcastable asAtomicType??

The following example uses conditional expressions in order to convert the current allocation of the $x variables successfully to a date without or with time indications and to a duration in days. In case all alternatives are not promising, the value is converted to a character string.

if ($x castable as xs:date)
then $x cast as xs:date
else if ($x castable as xs:dateTime)
then $x cast as xs:dateTime
else if ($x castable as xdt:dayTimeDuration)
then $x cast as xdt:dayTimeDuration
else $x cast as xs:string

The testing for a promising type conversion before the call of a cast operator is advisable because in this way, a targeted response instead of a runtime error can be ensured when dealing with unexpected data. So, the following FLWOR expression will produce a runtime error since the conversion cannot be performed (the format of the string corresponds to the one required for xs:date, but the value is not allowed):

let $x := xs:string("2004-02-31")
let $y := $x cast as xs:date
return fn:get-year-from-date($y)

 

Source: "XQuery – Grundlagen und fortgeschrittene Methoden", dpunkt-Verlag, Heidelberg (2004)

<< backnext >>