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
10.63Mb size Format: txt, pdf, ePub

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:

Other books

Getting Hotter by Elle Kennedy
Voodoo Eyes by Nick Stone
Sweet Harmony by Luann McLane
Deadly Honeymoon by Block, Lawrence
Protector by Catherine Mann
London Falling by Emma Carr
The Witches of Chiswick by Robert Rankin
Dark Victory by Brenda Joyce