Sequence Types

Sequence Types and Occurrence Indicators

Sequences are flat: (1, (2, 3), ()) simply concatenates, and () is the empty sequence, XPath's equivalent of SQL's NULL. A sequence type is an item type plus an occurrence indicator: none (exactly one), ? (zero or one), * (zero or more) or + (one or more). Item types range from item() through element(book) to xs:integer. instance of tests a value, treat as asserts a type and fails at run time if it is wrong, and cast as converts (Casting and Constructors):

Flattened sequences, occurrence indicators and instance of
xp '(1, (2, 3), ())' '() instance of xs:integer?' '//book instance of element(book)*' \
   '//book instance of element(book)' '"39.50" instance of xs:decimal' \
   '//pages treat as element(pages)'
Output
(1, (2, 3), ())                        => 1 2 3
() instance of xs:integer?             => true()
//book instance of element(book)*      => true()
//book instance of element(book)       => false()
"39.50" instance of xs:decimal         => false()
//pages treat as element(pages)        => error XPDY0050

Six books are not "exactly one book", so the fourth test is false and treat as fails, and a string that looks like a number is still a string. These types guard function signatures in XQuery and XSLT, such as declare function local:price($b as element(book)) as xs:decimal, and they catch the commonest bug in XML pipelines: a path that returns zero or several items where the code assumed one.