Read XSLT 2.0 and XPath 2.0 Programmer's Reference, 4th Edition Online
Authors: Michael Kay
The
instance of
Operator
The
instance of
operator is used to test whether a given value conforms to a particular type. Unlike Java, the two words must be separated by whitespace.
Expression | Syntax |
InstanceOfExpr | TreatExpr ( instance of SequenceType ) ? |
As usual, the fact that the first operand is listed as a
TreatExpr
is simply a way of indicating the operator priorities; these are summarized in Appendix A.
The
instance
of
expression always returns a boolean result. The first operand is evaluated, and if it conforms to the specified sequence type (as defined by the rules in the previous section) the answer is
true
; otherwise, it is
false
.
It's important to remember, whether you are testing atomic values or nodes, that the
instance
of
operator is testing whether the value has a label that identifies it as a member of the specified type. It isn't testing whether the value would be a valid member of that type if the label were changed. For example:
5 instance of xs:positiveInteger
returns
false
(surprisingly), because although
5
satisfies all the conditions for a positive integer, it is not labeled as such: the type label for a numeric literal of this kind is simply
xs:integer
. Similarly, given an element
as the context item, the expression:
price instance of element(*, xs:decimal)
will return
false
unless the element has actually been validated and given a type annotation of
xs:decimal
, or some type derived from
xs:decimal
. The fact that validation against this type would succeed is not enough; the validation must actually have been done, so that the required type annotation is present on the node.
The
instance of
operator does not atomize its operand, so an expression such as
@code instance of xs:decimal
is always going to return
false
. You need either to atomize the value explicitly, by writing
data(@code) instance of xs:decimal
, or to test the type annotation of the node, by writing
@code instance of attribute(*, xs:decimal)
.