Types

XQuery is a strongly typed language, meaning that each function and operator expects its arguments or operands to be of a particular type. This section provides some basic information about types that is useful to any query author. More detailed coverage of types in XQuery can be found in Chapter 11.

The XQuery type system is based on that of XML Schema. XML Schema has built-in simple types representing common datatypes such as xs:integer, xs:string, and xs:date. The xs: prefix is used to indicate that these types are defined in the XML Schema specification. Types are assigned to items in the input document during schema validation, which is optional. If no schema is used, the items are untyped.

The type system of XQuery is not as rigid as it may sound, since there are a number of type conversions that happen automatically. Most notably, items that are untyped are automatically cast to the type required by a particular operation. Casting involves converting a value from one type to another following specified rules. For example, the function call:

doc("order.xml")/order/substring(@num, 1, 4)

does not require that the num attribute be declared to be of type xs:string. If it is untyped, it is cast to xs:string. In fact, if you do not plan to use a schema, you can in most cases use XQuery without any regard for types. However, if you do use a schema and the num attribute is declared to be of type xs:integer, you cannot use the preceding substring example without explicitly converting ...

Get XQuery now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.