The Treat Expression
The treat expression, like the typeswitch expression, is used to assure the processor that only values of a certain type will participate in a particular function or operation. The syntax of a treat expression is shown in Figure 14-2.
Figure 14-2. Syntax of a treat expression
Building on the ProductType/HatType example from the previous section, suppose you would like to display the size of a product, if it is a hat. Although ProductType doesn't allow a size child, HatType does. You could use the query shown in Example 14-4.
Example 14-4. A query without a treat expression
if ($myProduct instance of element(*,prod:HatType))
then <p>The size is: {data($myProduct/size)}</p>
else ( )It tests to see if the product is a hat, and if it is, constructs a p element that contains its size. Unfortunately, an implementation that supports static typing will raise a type error with this query. This is because, as far as the processor knows, $myProduct has type ProductType, which does not allow a size child. As discussed in the previous section, it does not matter that you check the type of $myProduct in the enclosing if expression.
Example 14-5 shows a revised query that uses a treat expression to assure the processor that $myProduct is indeed an element of type HatType.
Example 14-5. A query with a treat expression
if ($myProduct instance of element(*,prod:HatType)) then <p>The ...
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