XSLT 2.0 and XPath 2.0 Programmer's Reference, 4th Edition (480 page)

BOOK: XSLT 2.0 and XPath 2.0 Programmer's Reference, 4th Edition
6.32Mb size Format: txt, pdf, ePub
ads

The
treat as
Operator

The
treat
as
operator can be regarded as an assertion; the programmer is asserting that at runtime, the value of an expression will conform to a given type. If the assertion turns out to be wrong, evaluation of the expression will fail with a runtime error.

This is the syntax:

Expression
Syntax
TreatExpr
CastableExpr
(
treat
as
SequenceType )?

The
treat
as
operator is extremely important if you are using an XPath processor that does strict static type checking (or if you want to write code that is portable between processors that do such checking and those that don't). However, if you want to write robust code, there is no harm in using
treat
as
to make explicit any assumptions you are making about types even in a system that does all its type checking dynamically, which will generally be the case when XPath is used within XSLT stylesheets.

Suppose that you are using a schema that defines a union type, an attribute
quantity
, say, whose value can be either an integer or one of the two strings
out-of-stock
or
unknown
. It might look reasonable to write:

BOOK: XSLT 2.0 and XPath 2.0 Programmer's Reference, 4th Edition
6.32Mb size Format: txt, pdf, ePub
ads

Other books

Dog Lived (and So Will I) by Rhyne, Teresa J.
You Took My Heart by Elizabeth Hoy
The Reluctant Beauty by Laurie Leclair
A Crossworder's Gift by Nero Blanc
Murder on the Blackboard by Stuart Palmer
The Global War on Morris by Steve Israel