XQuery

XQuery

(pwalmsley@datypic.com)

ISBN: 1491915103

2nd edition, , O'Reilly Media, Inc.

Chapter 15: Static Typing

Please note that the book contains many inline examples and informal tables that are not provided here.

Example 15-1. A typeswitch expression
declare namespace prod = "http://datypic.com/prod";
typeswitch ($myProd)
  case element(*, prod:HatType) return xs:string($myProd/size)
  case element(*, prod:ShirtType)
       return xs:string(concat($myProd/size/@system, ": ",
                               $myProd/size))
  case element(*, prod:UmbrellaType) return "none"
  default return "n/a"
Example 15-2. Binding variables to typeswitch expressions
declare namespace prod = "http://datypic.com/prod";
typeswitch ($myProd)
  case $h as element(*, prod:HatType) return xs:string($h/size)
  case $s as element(*, prod:ShirtType)
       return xs:string(concat($s/size/@system, ": ", $s/size))
  case element(*, prod:UmbrellaType) return "none"
  default return "n/a"
Example 15-3. Alternative to a typeswitch expression
declare namespace prod = "http://datypic.com/prod";
if ($myProd instance of element(*, prod:HatType))
then xs:string($myProd/size)
else if ($myProd instance of element(*, prod:ShirtType))
     then xs:string(concat($myProd/size/@system, ": ", $myProd/size))
     else if ($myProd instance of element(*, prod:UmbrellaType))
          then "none"
          else "n/a"
Example 15-4. A query without a treat expression
declare namespace prod = "http://datypic.com/prod";
if ($myProd instance of element(*, prod:HatType))
then <p>The size is: {data($myProd/size)}</p>
else ()
Example 15-5. A query with a treat expression
declare namespace prod = "http://datypic.com/prod";
if ($myProd instance of element(*, prod:HatType))
then
  <p>The size is: {data( ($myProd treat as element(*, prod:HatType))/size)}</p>
else ()
Example 15-6. A FLWOR with a type declaration
declare namespace prod = "http://datypic.com/prod";
for $prod as element(*, prod:ProductType) in doc("catalog.xml")/catalog/*
order by $prod/name
return $prod/name
Example 15-7. A quantified expression with a type declaration
every $number as element(*, xs:integer) in
  doc("catalog.xml")//number satisfies ($number > 0)
Datypic XQuery Services