The Typeswitch Expression
The typeswitch expression provides a convenient syntax for performing special processing based on the type of an expression. An example is shown in Example 14-1.
Example 14-1. Binding variables to typeswitch expressions
typeswitch ($myProduct)
case element(*,prod:HatType) return xs:string($myProduct/size)
case element(*,prod:ShirtType)
return xs:string(concat($myProduct/size/@system, ": ",
$myProduct/size))
case element(*,prod:UmbrellaType) return "none"
default return "n/a"The example assumes that $myProduct is bound to a product element. In the schema, assume that product elements are declared to have type ProductType. However, in the input document, a product element may carry an xsi:type attribute that indicates another type that is derived by extension from ProductType, such as HatType, ShirtType, or UmbrellaType.
ProductType itself does not allow a size child. Depending on which subtype it has, it may or may not have a size child. The typeswitch expression will return a different value depending on the type annotation of the product element.
The syntax of a typeswitch expression is shown in Figure 14-1. The typeswitch keyword is followed by an expression in parentheses (called the operand expression), which evaluates to the sequence whose type is to be evaluated. This is followed by one or more case clauses, plus a required default clause that indicates the value if none of the case clauses applies.
Figure 14-1. Syntax of a typeswitch expression ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access