Copyright © 2002 W3C® (MIT, INRIA, Keio), All Rights Reserved. W3C liability, trademark, document use, and software licensing rules apply.
XML is a versatile markup language, capable of labeling the information content of diverse data sources including structured and semi-structured documents, relational databases, and object repositories. A query language that uses the structure of XML intelligently can express queries across all these kinds of data, whether physically stored in XML or viewed as XML via middleware. This specification describes a query language called XQuery, which is designed to be broadly applicable across many types of XML data sources.
This is a public W3C Working Draft for review by W3C Members and other interested parties. This section describes the status of this document at the time of its publication. It is a draft document and may be updated, replaced, or made obsolete by other documents at any time. It is inappropriate to use W3C Working Drafts as reference material or to cite them as other than "work in progress." A list of current public W3C technical reports can be found at http://www.w3.org/TR/.
Much of this document is the result of joint work by the XML Query and XSL Working Groups, which are jointly responsible for XPath 2.0, a language derived from both XPath 1.0 and XQuery. The XPath 2.0 and XQuery 1.0 Working Drafts are generated from a common source. These languages are closely related, sharing much of the same expression syntax and semantics, and much of the text found in the two Working Drafts is identical.
This version of the document contains a new approach to backward compatibility with XPath Version 1.0, and new, more liberal rules for casting values to target types. Rules for matching values to types are now based strictly on type and element names rather than on structural subsumption. The sort by expression has been eliminated and in its place a new order by clause has been added to the FLWR expression (and public feedback on this change is invited). Several small changes have been made to the grammar in order to eliminate the need for reserved keywords. More detailed material has been included on error handling and optimization. A complete list of changes can be found in F Revision
Log. Public feedback is invited on the open issues listed in this document, in particular on Issues 327 and 335.
Under consideration for a future version of this document is a proposal for XQuery to support default validation of element constructors. It is also proposed that users should be able to specify, for any expression, whether all occurrences of validation (either explicit or implicit) within that expression should be interpreted as referring to lax, strict, or skip validation.
This document is a work in progress. It contains many open issues, and should not be considered to be fully stable. Vendors who wish to create preview implementations based on this document do so at their own risk. While this document reflects the general consensus of the working groups, there are still controversial areas that may be subject to change.
Public comments on this document and its open issues are welcome. Comments should be sent to the W3C XPath/XQuery mailing list, public-qt-comments@w3.org (archived at http://lists.w3.org/Archives/Public/public-qt-comments/).
XQuery 1.0 has been defined jointly by the XML Query Working Group (part of the XML Activity) and the XSL Working Group (part of the Style Activity).
Patent disclosures relevant to this specification may be found on the XML Query Working Group's patent disclosure page at http://www.w3.org/2002/08/xmlquery-IPR-statements and the XSL Working Group's patent disclosure page at http://www.w3.org/Style/XSL/Disclosures.
1 Introduction
2 Basics
2.1 Expression Context
2.1.1 Static Context
2.1.2 Evaluation Context
2.2 Input Functions
2.3 Expression Processing
2.3.1 Document Order
2.3.2 Typed Value and String Value
2.4 Types
2.4.1 Type Checking
2.4.2 SequenceType
2.4.2.1 SequenceType Matching
2.4.3 Type Conversions
2.4.3.1 Atomization
2.4.3.2 Effective Boolean Value
2.5 Variable Bindings
2.6 Errors and Conformance
2.6.1 Errors
2.6.2 Conformance
2.6.2.1 Basic XQuery
2.6.2.2 Schema Import Feature
2.6.2.3 Static Typing Feature
2.6.3 Handling Dynamic Errors
2.6.4 Errors and Optimization
3 Expressions
3.1 Primary Expressions
3.1.1 Literals
3.1.2 Variables
3.1.3 Parenthesized Expressions
3.1.4 Function Calls
3.1.5 Comments
3.2 Path Expressions
3.2.1 Steps
3.2.1.1 Axes
3.2.1.2 Node Tests
3.2.2 Predicates
3.2.3 Unabbreviated Syntax
3.2.4 Abbreviated Syntax
3.3 Sequence Expressions
3.3.1 Constructing Sequences
3.3.2 Combining Sequences
3.4 Arithmetic Expressions
3.5 Comparison Expressions
3.5.1 Value Comparisons
3.5.2 General Comparisons
3.5.3 Node Comparisons
3.5.4 Order Comparisons
3.6 Logical Expressions
3.7 Constructors
3.7.1 Element Constructors
3.7.2 Computed Constructors
3.7.3 Whitespace in Constructors
3.7.4 Data Model Representation
3.7.4.1 Constructed Element Nodes
3.7.4.2 Constructed Attribute Nodes
3.7.4.3 Constructed Document Nodes
3.7.4.4 Constructed Text Nodes
3.7.5 Other Constructors and Comments
3.8 FLWOR Expressions
3.8.1 For and Let Clauses
3.8.2 Where Clause
3.8.3 Order By and Return Clauses
3.8.4 Example
3.9 Unordered Expressions
3.10 Conditional Expressions
3.11 Quantified Expressions
3.12 Expressions on SequenceTypes
3.12.1 Instance Of
3.12.2 Typeswitch
3.12.3 Cast
3.12.4 Castable
3.12.5 Constructor Functions
3.12.6 Treat
3.13 Validate Expressions
4 The Query Prolog
4.1 Namespace Declarations
4.2 Schema Imports
4.3 Xmlspace Declaration
4.4 Default Collation
4.5 Function Definitions
5 Example Applications
5.1 Joins
5.2 Grouping
5.3 Queries on Sequence
5.4 Recursive Transformations
A Grammar
A.1 Lexical structure
A.1.1 Syntactic Constructs
A.1.2 Lexical Rules
A.2 BNF
A.3 Reserved Function Names
A.4 Precedence Order
B Type Promotion and Operator Mapping
B.1 Type Promotion
B.2 Operator Mapping
C References
C.1 Normative References
C.2 Non-normative References
C.3 Background References
C.4 Informative Material
D Glossary
E XPath 2.0 and XQuery 1.0
Issues (Non-Normative)
F Revision
Log (Non-Normative)
F.1 15 Nov 2002
As increasing amounts of information are stored, exchanged, and presented using XML, the ability to intelligently query XML data sources becomes increasingly important. One of the great strengths of XML is its flexibility in representing many different kinds of information from diverse sources. To exploit this flexibility, an XML query language must provide features for retrieving and interpreting information from these diverse sources.
XQuery is designed to meet the requirements identified by the W3C XML Query Working Group [XML Query 1.0 Requirements] and the use cases in [XML Query Use Cases]. It is designed to be a language in which queries are concise and easily understood. It is also flexible enough to query a broad spectrum of XML information sources, including both databases and documents. The Query Working Group has identified a requirement for both a human-readable query syntax and an XML-based query syntax. XQuery is designed to meet the first of these requirements. XQuery is derived from an XML query language called Quilt [Quilt], which in turn borrowed features from several other languages, including XPath 1.0 [XPath 1.0], XQL [XQL], XML-QL [XML-QL], SQL [SQL], and OQL [ODMG].
XQuery Version 1.0 is an extension of XPath Version 2.0. Any expression that is syntactically valid and executes successfully in both XPath 2.0 and XQuery 1.0 will return the same result in both languages. Since these languages are so closely related, their grammars and language descriptions are generated from a common source to ensure consistency, and the editors of these specifications work together closely.
XQuery also depends on and is closely related to the following specifications:
The XQuery data model defines the information in an XML document that is available to an XQuery processor. The data model is defined in [XQuery 1.0 and XPath 2.0 Data Model].
The static and dynamic semantics of XQuery are formally defined in [XQuery 1.0 Formal Semantics]. This is done by mapping the full XQuery language into a "core" subset for which the semantics is defined. This document is useful for implementors and others who require a rigorous definition of XQuery.
XQuery's type system is based on [XML Schema]. Work is in progress to ensure that the type systems of XQuery, the XQuery Core, and XML Schema are completely aligned.
The library of functions and operators supported by XQuery is defined in [XQuery 1.0 and XPath 2.0 Functions and Operators].
One requirement in [XML Query 1.0 Requirements] is that an XML query language have both a human-readable syntax and an XML-based syntax. The XML-based syntax for XQuery is described in [XQueryX 1.0]. [Ed. Note: The current edition of [XQueryX 1.0] has not incorporated recent language changes; it will be made consistent with this document in its next edition.]
This document specifies a grammar for XQuery, using the same Basic EBNF notation used in [XML], except that grammar symbols always have initial capital letters. Unless otherwise noted (see A.1 Lexical structure), whitespace is not significant in the grammar. Grammar productions are introduced together with the features that they describe, and a complete grammar is also presented in the appendix [A Grammar].
In the grammar productions in this document, nonterminal symbols are underlined and literal text is enclosed in double quotes. Angle brackets are used to enclose tokens that must be recognized by using lexical look-ahead, as described in A.1 Lexical structure. For example, the following production describes the syntax of a function call:
| [81] | FunctionCall | ::= | <QName "("> (Expr ("," Expr)*)? ")" |
The production should be read as follows: A function call consists of a QName followed by an open-parenthesis (these tokens must be recognized together using lexical lookahead.) The open-parenthesis is followed by an optional argument list. The argument list (if present) consists of one or more expressions, separated by commas. The optional argument list is followed by a close-parenthesis.
[Ed. Note: A future version of this document will include links between terms (in bold font) and their definitions.]
The basic building block of XQuery is the expression. The language provides several kinds of expressions which may be constructed from keywords, symbols, and operands. In general, the operands of an expression are other expressions. XQuery is a functional language which allows various kinds of expressions to be nested with full generality. It is also a strongly-typed language in which the operands of various expressions, operators, and functions must conform to designated types.
Like XML, XQuery is a case-sensitive language. All keywords in XQuery use lower-case characters.
The value of an expression is always a sequence, which is an ordered collection of zero or more items. An
item is either an atomic value or a node. An atomic
value is a value in the value space of an XML Schema atomic
type, as defined in [XML Schema] (that is, a simple type that is
not a list type or a union type). A node conforms to one of the
seven node kinds described in [XQuery 1.0 and XPath 2.0 Data Model]. Each node has a unique node identity. Some
kinds of nodes have typed values, string values, and names, which can be
extracted from the node. The typed value of a node is a sequence
of zero or more atomic values. The string value of a node is a
value of type xs:string. The name of a node is a value of type xs:QName.
A sequence containing exactly one item is called a singleton sequence. An item is identical to a singleton sequence containing that item. Sequences are never nested--for example, combining the values 1, (2, 3), and ( ) into a single sequence results in the sequence (1, 2, 3). A sequence containing zero items is called an empty sequence.
In this document, the namespace prefixes xs: and xsi: are considered to be bound to the XML Schema namespaces http://www.w3.org/2001/XMLSchema and http://www.w3.org/2001/XMLSchema-instance, respectively (as described in [XML Schema]), and the prefix fn: is considered to be bound to the namespace of XPath/XQuery functions, http://www.w3.org/2002/11/xquery-functions (described in [XQuery 1.0 and XPath 2.0 Functions and Operators]). In some cases, where the meaning is clear and namespaces are not important to the discussion, built-in XML Schema typenames such as integer and string are used without a namespace prefix. Also, this document assumes that the default function namespace (see 4.1 Namespace Declarations) is set to the namespace of XPath/XQuery functions, so function names appearing without a namespace prefix can be assumed to be in this namespace.
The expression context for a given expression consists of all the information that can affect the result of the expression. This information is organized into two categories called the static context and the evaluation context.
This section describes the context information used by XQuery expressions, including the functions in the core function library. Other functions, outside the core function library, may require additional context information.
The static context of an expression is the information that is available during static analysis of the expression, prior to its evaluation. This information can be used to decide whether the expression contains a static error.
In XQuery, the information in the static context is provided by declarations in the Query Prolog (except as noted below). Static context consists of the following components:
In-scope namespaces. This is a set of (prefix, URI) pairs. The in-scope namespaces are used for resolving prefixes used in QNames within the expression.
Default namespace for element and type names. This is a namespace URI. This namespace is used for any unprefixed QName appearing in a position where an element or type name is expected.
Default namespace for function names. This is a namespace URI. This namespace is used for any unprefixed QName appearing as the function name in a function call.
In-scope schema definitions. This is a set of (QName, type definition) pairs. It defines the set of types that are available for reference within the expression. It includes the built-in schema types and all globally-declared types in imported schemas. It may also include types declared in schemas associated with documents retrieved by input functions, as described in 2.2 Input Functions.
Ed. Note: The importing of type definitions from input documents is still under discussion. The idea that the static context should be affected by run-time functions in an implementation-defined way remains controversial (see Issue 307.)
In-scope variables. This is a set of (QName, type) pairs. It defines the set of variables that have been declared and are available for reference within the expression. The QName represents the name of the variable, and the type represents its static data type.
Unlike the other parts of the static context, variable types are not declared in the Query Prolog. Instead, they are derived from static analysis of the expressions in which the variables are bound. In-scope variable definitions may also be provided by the environment external to a query. (See Issue 307.)
In-scope functions. This part of the static context defines the set of functions that are available to be called from within an expression. Each function is uniquely identified by its QName and its arity (number of parameters). The static context maps QName and arity into a function signature, which specifies the static types of the function parameters and function result.
For each atomic type in the in-scope schema definitions, there is a constructor function in the in-scope functions. Constructor functions are discussed in 3.12.5 Constructor Functions.
In-scope collations. This is a set of (URI, collation) pairs. It defines the names of the collations that are available for use in function calls that take a collation name as an argument. A collation may be regarded as an object that supports two functions: a function that given a set of strings, returns a sequence containing those strings in sorted order; and a function that given two strings, returns true if they are considered equal, and false if not.
Default collation. This is a collation. This collation is used by string comparison functions when no explicit collation is specified.
Base URI. This is an absolute URI, used by the fn:document function when resolving the relative URI of a document to be loaded, if
no explicit base URI is supplied in the function call.
XQuery Version 1.0 includes XPath Version 2.0 as a subset. In addition to the static context items listed above, XPath 2.0 requires a static context item named XPath 1.0 compatibility mode. Since XQuery does not support this mode, it always sets this context item to false when evaluating an XPath expression.
The evaluation context of an expression is defined as information that is available at the time the expression is evaluated. The evaluation context consists of all the components of the static context, and the additional components listed below.
The first three components of the dynamic context (context item, context position, and context size) are called the focus of the expression. The focus enables the processor to keep track of which nodes are being processed by the expression.
The focus for the outermost expression is supplied by the
environment in which the expression is evaluated. Certain language constructs,
notably the path expression E1/E2 and the predicate expression E1[E2], create a new focus for the evaluation of a sub-expression. In these constructs, E2 is evaluated once for each item in the sequence that results from
evaluating E1. Each time E2 is evaluated, it is evaluated with a different focus. The focus for
evaluating E2 is referred to below as the inner focus, while the focus
for evaluating E1 is referred to as the outer focus. The inner focus exists
only while E2 is being evaluated. When this evaluation is complete, evaluation of the
containing expression continues with its original focus unchanged.
The context item is the item currently being
processed. An item is either an atomic value or a node. When the context item
is a node, it can also be referred to as the context node. The
context item is returned by the expression ".". When an expression E1/E2 or E1[E2] is evaluated, each item in the sequence obtained by evaluating E1 becomes the context item in the inner focus for an evaluation of E2.
The context position is the position of the context
item within the sequence of items currently being processed. It changes
whenever the context item changes. Its value is always an integer greater than
zero. The context position is returned by the expression fn:position(). When an expression E1/E2 or E1[E2] is evaluated, the context position in the inner focus for an
evaluation of E2 is the position of the context item in the sequence obtained by
evaluating E1. The position of the first item in a sequence is always 1 (one). The
context position is always less than or equal to the context size.
The context size is the number of items in the
sequence of items currently being processed. Its value is always an integer
greater than zero. The context size is returned by the expression last(). When an expression E1/E2 or E1[E2] is evaluated, the context size in the inner focus for an
evaluation of E2 is the number of items in the sequence obtained by evaluating E1.
Dynamic variables. This is a set of (QName, type, value) triples. It contains the same QNames as the in-scope variables in the static context for the expression. Each QName is associated with the dynamic type and value of the corresponding variable. The dynamic type associated with the value of a variable may be more specific than the static type associated with the same variable. The value of a variable is, in general, a sequence.
The dynamic types and values of variables are provided by execution of the XQuery expressions in which the variables are bound. Variable types and values may also be provided by the environment external to the query. (See Issue 307.)
Current date and time. This information represents
an implementation-defined point in time during processing of a query or transformation. It can be retrieved by the fn:current-date, fn:current-time, and fn:current-dateTime functions. If invoked multiple times during the execution of a query or transformation,
these functions always returns a consistent result.
Implicit timezone. This is the timezone to be used when a date, time, or dateTime value that does not have a timezone is used in a comparison or in any other operation. This value is an instance of dayTimeDuration that is implementation-defined. See [ISO 8601] for the range of legal values of a timezone.
Input sequence. The input sequence is sequence of nodes that can be accessed by the input function. It might be thought of as an "implicit input". The content of the input sequence is determined in an implementation-defined way.
XQuery has a set of functions that provide access to input data. These functions are of particular importance because they provide a way in which an expression can reference a document or a collection of documents. The input functions are described informally here, and in more detail in [XQuery 1.0 and XPath 2.0 Functions and Operators].
The input sequence is a part of the evaluation context for an expression. The way in which nodes are assigned to the input sequence is implementation-defined. For example, one implementation might provide a fixed mapping from a directory system to the input sequence, another implementation might provide a graphical user interface that allows users to choose a data source for the input sequence, and a third implementation might support UNIX-style pipes, allowing the output of one query to become the input sequence for another query.
The input functions supported by XQuery are as follows:
The fn:input function, which takes no parameters, returns the input
sequence. For example, the expression
fn:input()//customer returns
all the customer elements that are descendants of
nodes in the input sequence. If no input sequence has been bound,
the fn:input function raises a dynamic error.
The fn:collection function returns the nodes
found in a collection. A collection may be any sequence of nodes. A collection is identified by a
string, which must be a valid URI. For example, the expression
fn:collection("http://example.org")//customer
identifies all the customer elements that are
descendants of nodes found in the collection whose URI is
http://example.org.
The fn:document function, when its first argument
is a string containing a single URI that refers to an
XML document, converts that document to a Data Model representation and returns its document node. The
fn:document function can also be used to address
multiple documents or document fragments; see
[XQuery 1.0 and XPath 2.0 Functions and Operators] for details.
If a given input function is invoked repeatedly with the same arguments during the scope of a single query or transformation, each invocation returns the same result.
The input functions described in this section provide access to input documents or document fragments. If these documents or document fragments are associated with schemas, the type definitions contained in these schemas may be added to the in-scope schema definitions, in an implementation-defined way.
Ed. Note: The importing of type definitions from input documents is still under discussion. The idea that the static context should be affected by run-time functions in an implementation-defined way remains controversial (see Issue 307).
XQuery is defined in terms of the [XQuery 1.0 and XPath 2.0 Data Model] (referred to in this document simply as the Data Model), which represents information in the form of nodes and atomic values. Before an XQuery expression can be processed, the input documents to be operated on by the expression must be represented in the Data Model. For example, an XML document can be converted to the Data Model by the following steps:
The document can be parsed using an XML parser.
The parsed document can be validated against one or more schemas. This process, which is described in [XML Schema], results in an abstract information structure called the Post-Schema Validation Infoset (PSVI). If a document has no associated schema, it can be validated against a permissive default schema that accepts any well-formed document.
The PSVI can be transformed into the Data Model by a process described in [XQuery 1.0 and XPath 2.0 Data Model].
The above steps provide an example of how a Data Model instance might be constructed. A Data Model instance might also be synthesized directly from a relational database, or constructed in some other way. XQuery is defined in terms of operations on the Data Model, but it does not place any constraints on how the input Data Model instance is constructed.
Each element or attribute node in the Data Model has an annotation that indicates its dynamic type. If the Data Model was derived from an input XML document, the dynamic types of the elements and attributes are derived from schema validation. A newly constructed element node has the dynamic type xs:anyType, and a newly constructed attribute node has the dynamic type xs:anySimpleType. Constructed element and attribute nodes may be given a more specific type annotation by a validate expression. The dynamic type of an element or attribute indicates its range of values--for example, an attribute named version might have the dynamic type xs:decimal, indicating that it contains a decimal value.
The value of an attribute is represented directly within the attribute node. An attribute node whose type is unknown (such as might occur in a schemaless document) is annotated with the dynamic type xs:anySimpleType.
The value of an element is represented by the children of the element node, which may include text nodes and other element nodes. The dynamic type of an element node indicates how the values in its child text nodes are to be interpreted. An element whose type is unknown (such as might occur in a schemaless document) is annotated with the type xs:anyType.
Atomic values in the Data Model also carry dynamic type annotations. An atomic value of unknown type is annotated with the type xs:anySimpleType. Under certain circumstances (such as during processing of an arithmetic operator), an atomic value of xs:anySimpleType may be cast into a more specific type (such as xs:double).
This document provides a description of how each kind of expression is processed. For each expression, the operands and result are instances of the Data Model. The details of transforming XML documents into the Data Model are described in [XQuery 1.0 and XPath 2.0 Data Model]. Rules for serialization of a Data Model instance in the form of an XML document remain to be specified.
The terms document order, typed value, and string value are described here because they are of particular importance for the processing of expressions.
Document order defines a total ordering among all the nodes seen by the language processor. Informally, document order corresponds to a depth-first, left-to-right traversal of the nodes in the Data Model.
Within a given document, the document node is the first node, followed by element nodes, text nodes, comment nodes, and processing instruction nodes in the order of their representation in the XML form of the document (after expansion of entities). Element nodes occur before their children, and the children of an element node occur before its following siblings. The namespace nodes of an element immediately follow the element node, in implementation-defined order. The attribute nodes of an element immediately follow its namespace nodes, and are also in implementation-defined order.
The relative order of nodes in distinct documents is implementation-defined but stable within a given query or transformation. In other words, given two distinct documents A and B, if a node in document A is before a node in document B, then every node in document A is before every node in document B. The relative order among free-floating nodes (those not in a document) is implementation-defined.
Element, attribute, and text nodes have a typed value and a string value that can be extracted by calling the data function and the string function, respectively. The typed value of a node is a sequence of atomic values, and the string value of a node is a string. Element and attribute nodes also have a type annotation, which is a QName that is defined in the in-scope schema definitions. The type annotation of a node is assigned when the node is constructed, and can be changed by validating the node (see 3.13 Validate Expressions).
The typed value and string value for each kind of node are defined by the dm:typed-value and dm:string-value accessors in [XQuery 1.0 and XPath 2.0 Data Model]. Specifically:
The typed value of a text node is the same as its string value, as an instance of xs:anySimpleType.
If the type annotation of an attribute node is xs:anySimpleType, its typed value is equal to its string value, as an instance of xs:anySimpleType. Otherwise, its typed value is derived from its string value and type annotation in a way that is consistent with schema validation, as described in [XQuery 1.0 and XPath 2.0 Data Model].
Example: A1 is an unvalidated attribute whose content is defined by the expression {2 + 2}. The type annotation of A1 is xs:anySimpleType. The string value of A1 is "4". The typed value of A1 is "4" as an instance of xs:anySimpleType. If A1 is later validated and found to have the type hatsize, its string value is still "4", but its typed value is 4 as an instance of hatsize.
Example: A2 is a validated attribute with type annotation IDREFS, which is a list type derived from IDREF. Its string value is "bar baz faz". The typed value of A2 is a sequence of three atomic values ("bar", "baz", "faz"), each of type IDREF.
If the type annotation of an element node is xs:anyType, its typed value is equal to its string value, as an instance of xs:anySimpleType. Otherwise, its typed value is derived from its string value and type annotation in a way that is consistent with schema validation, as described in [XQuery 1.0 and XPath 2.0 Data Model]. If the type annotation of an element denotes a type with complex content (i.e., a type that permits subelements), its typed value is undefined, and the data function raises an error when applied to such an element.
Example: E1 is an unvalidated element node whose content is defined by the expression {1, 2, 3}. The type annotation of E1 is xs:anyType. The string value of E1 is the string "1 2 3". The typed value of E1 is "1 2 3" as an instance of xs:anySimpleType.
Example: E2 is a validated element node with the type annotation hatsizelist, which is a type whose content is defined as a sequence of items of type hatsize, which in turn is derived from xs:integer. The string value of E2 is "7 8 9". The typed value of E2 is a sequence of three values (7, 8, 9), each of type hatsize.
Example: E3 is a validated element node with the type annotation weather, which is a complex type that permits subelements. The string value of E3 is "hot". Even though E3 does not happen to contain any subelements, its typed value is undefined because its type permits subelements.
XQuery is a strongly typed language with a type system based on
[XML Schema]. The built-in types of XQuery include the built-in atomic types of [XML Schema] (such as xs:integer and xs:string), and the following special derived types: fn:dayTimeDuration and fn:yearMonthDuration (described in [XQuery 1.0 and XPath 2.0 Functions and Operators]). Additional types may be defined in schemas and imported into a query by means of a schema import, as discussed in
4.2 Schema Imports.
When the type of a value is not appropriate for the context in which it is used, a type error is raised. A type error may be detected and reported during the analysis phase or during the evaluation phase, as described in 2.4.1 Type Checking.
The XQuery type system is formally defined in [XQuery 1.0 Formal Semantics]. This section presents a summary of types from a user's perspective.
XQuery defines two phases of processing called the analysis phase and the evaluation phase.
The analysis phase depends on the query expression itself and on the static context. The analysis phase does not depend on any input data. The purpose of type-checking during the analysis phase is to provide early detection of type errors and to compute the type of a query result.
During the analysis phase, each expression is assigned a static type. In some cases, the static type is derived from the lexical form of the expression; for example, the static type of the literal 5 is xs:integer. In other cases, the static type of an expression is inferred according to rules based on the static types of its operands; for example, the static type of the expression size < 5 is xs:boolean. The static type of an expression may be either a named type or a structural description--for example, xs:boolean? denotes an optional occurrence of the xs:boolean type. The rules for inferring the static types of various expressions are described in [XQuery 1.0 Formal Semantics]. During the analysis phase, if an operand of an expression is found to have a static type that is not appropriate for that operand, a type error is raised. If static type checking raises no errors and assigns a static type T to an expression, then execution of the expression on valid input data is guaranteed either to produce a value of type T or to raise a dynamic error.
The evaluation phase is performed only after successful completion of the analysis phase. The evaluation phase depends on input data, on the expression being evaluated, and on the evaluation context. During the evaluation phase, a dynamic type is associated with each value as it is computed. The dynamic type of a value may be either a structural type (such as "sequence of integers") or a named type. The dynamic type of a value may be more specific than the static type of the expression that computed it (for example, the static type of an expression might be "zero or more integers or strings," but at run time its value may have the dynamic type "integer.") If an operand of an expression is found to have a dynamic type that is not appropriate for that operand, a type error is raised.
It is possible for static analysis of an expression to raise a type error, even though the expression might evaluate successfully on some valid input data. For example, an expression might contain a function that requires an element as its parameter, and the analysis phase might infer the static type of the function parameter to be an optional element. In this case, a type error would result, even though the function call would be successful for input data in which the optional element is present.
It is also possible for an expression to raise a dynamic error, even though analysis of the expression raised no static error. For example, an expression may contain a cast of a string into an integer, which is statically valid. However, if the actual value of the string at run time cannot be cast into an integer, a dynamic error will result. Similarly, an expression may apply an arithmetic operator to a value extracted from a schemaless document. This is not a static error, but at run time, if the value cannot be successfully cast to a numeric type, a dynamic error will be raised.
During the analysis phase, it may be desirable for an implementation to issue a warning if the static type assigned to an expression other than () is empty, indicating that the expression can never return a nonempty value. This can catch cases in which a query references an element or attribute that is not present, possibly due to a misspelling or misunderstanding. We suggest a warning rather than requiring an error because there are some situations in which a correct expression may have the type empty.
When it is necessary to refer to a type in an XQuery expression, the syntax shown below is used. This syntax production is called "SequenceType", since it describes the type of an XQuery value, which is a sequence.
| [88] | SequenceType | ::= | (ItemType OccurrenceIndicator) | "empty" |
| [89] | ItemType | ::= | (("element" | "attribute") ElemOrAttrType?) |
| [90] | ElemOrAttrType | ::= | (QName (SchemaType | SchemaContext?)) | SchemaType |
| [91] | SchemaType | ::= | <"of" "type"> QName |
| [83] | SchemaContext | ::= | "context" SchemaGlobalContext ("/" SchemaContextStep)* |
| [84] | SchemaGlobalContext | ::= | QName | <"type" QName> |
| [85] | SchemaContextStep | ::= | QName |
| [92] | AtomicType | ::= | QName |
| [93] | OccurrenceIndicator | ::= | ("*" | "+" | "?")? |
Here are some examples of SequenceTypes that might be used in XQuery expressions or function parameters:
xs:date refers to the built-in Schema type date
attribute? refers to an optional attribute
element refers to any element
element office:letter refers to an element that has a specific name and that has been validated as conforming to the schema definition for that name
element of type
po:address+ refers to one or more elements that have been validated as conforming to the schema definition of the given type
node* refers to a sequence of zero or more nodes of any type
item* refers to a sequence of zero or more nodes or atomic values
During processing of a query, it is sometimes necessary to determine whether a given value matches a type that was declared using the SequenceType syntax. This process is known as SequenceType matching. For example, an instance of expression returns true if a given value matches a given type, or false if
it does not.
SequenceType matching between a given value and a given SequenceType is performed as follows:
If the SequenceType is empty, the match succeeds only if the value is an empty sequence. If the
SequenceType is an ItemType with no OccurrenceIndicator, the match succeeds only if the value contains precisely one item and that item matches the ItemType (see below).
If the SequenceType contains an ItemType and an OccurrenceIndicator, the match succeeds only if the number of items in the value matches the OccurrenceIndicator and each
of these items matches the ItemType. As a consequence of these rules, a value that is an empty sequence matches any SequenceType whose occurrence indicator is * or ?.
An OccurrenceIndicator indicates the number of items in a sequence, as follows:
? indicates zero or one items
* indicates zero or more items
+ indicates one or more items
The process of matching a given item against a given ItemType is performed as follows (remember that an item may be a node or an atomic value):
The ItemType item matches any item. For example, item matches the atomic value 1 or the element <a/>.
The following ItemTypes match atomic values:
atomic value matches any atomic value.
A named atomic type matches a value if the dynamic type of the value is the same as the named atomic type or is derived from the named atomic type by restriction. For example, the ItemType xs:decimal matches the value 12.34 (a decimal literal); it also matches a value whose dynamic type is shoesize, if shoesize is an atomic type derived from xs:decimal.
untyped matches an atomic value whose
most specific type is xs:anySimpleType.
The following ItemTypes match nodes:
node matches any node.
text matches any text node.
processing-instruction matches any processing instruction node.
comment matches any comment node.
document matches any document node.
element matches an element node. Optionally, element may be followed by ElemOrAttrType, which places further constraints on the node (see below).
attribute matches an attribute node. Optionally, attribute may be followed by ElemOrAttrType, which places further constraints on the node (see below).
An ElemOrAttrType may be used to place a constraint on the name or type of an element or attribute, as follows:
One form of ElemOrAttrType, denoted by the phrase "of type", specifies the required type of the element or attribute node. The required type must be the QName of a simple or complex type that is found in the in-scope schema definitions. The match is successful only if the given element or attribute has a type annotation that is the same as the required type or is known (in the in-scope schema definitions) to be derived from the required type. For example, element of type Employee matches an element node that has been validated and has received the type annotation Employee. Similarly, attribute of type xs:integer matches an attribute node that has been validated and has received the type annotation xs:integer.
Another form of ElemOrAttrType is simply a QName, which is interpreted as the required name of the element or attribute. The QName must be an element or attribute name that is found in the in-scope schema definitions. The match is successful only if the name of the given element or attribute is equal to the required name or is known (in the in-scope schema definitions) to be derived from the required name, and if the element or attribute has been validated.
The constraint that an element must have a required name is considered to be satisfied if the element has been validated and found to be a member of a substitution group whose head element has the required name. Substitution groups are described in [XML Schema].
The above two forms of ElemOrAttrType may be combined to specify both the required name and the required type of an element or attribute node, as in element person of type Employee or attribute color of type xs:integer. This form might be used, for example, to specify a required type that is more specific than the schema type associated with the required name.
In some cases, the required name of an element or attribute node may be locally declared (that is, declared inside a complex type in some schema.) In this case, the ElemOrAttrType may specify the SchemaContext in which the required name is to be interpreted. For example, element shippingAddress in invoice/customer matches an element node that conforms to the schema definition of the element name shippingAddress, as it would be interpreted inside a customer element that is inside an invoice element. The first QName in the SchemaContext must be found in the in-scope schema definitions.
Some expressions do not require their operands to exactly match the expected type. For example, function parameters and returns expect a value of a particular type, but automatically perform certain type conversions, such as extraction of atomic values from nodes, promotion of numeric values, and implicit casting of untyped values. The conversion rules for function parameters and returns are discussed in 3.1.4 Function Calls. Other operators that provide special conversion rules include arithmetic operators, which are discussed in 3.4 Arithmetic Expressions, and value comparisons, which are discussed in 3.5.1 Value Comparisons.
Type conversions sometimes depend on a process called atomization, which is used when a sequence of atomic values is required. The result of atomization is either a sequence of atomic values or a type error. Atomization of a sequence is defined as follows:
If every item in the input sequence is either an atomic value or a node whose typed value is a sequence of atomic values, then the result of atomization is the concatenated sequence of these atomic values.
Otherwise, atomization raises a type error.
Atomization may be used in processing the following types of expressions:
Arithmetic expressions
Comparison expressions
Function calls and returns
Cast expressions
If a sequence of items is encountered where a boolean value is expected, it is necessary to find its effective boolean value. The effective boolean value of a sequence is defined as the result of invoking the fn:boolean function on the sequence, as defined in [XQuery 1.0 and XPath 2.0 Functions and Operators].
The semantics of fn:boolean are repeated here for convenience. fn:boolean returns false if its operand is any of the following:
An empty sequence.
The boolean value false.
An empty string ("").
A numeric value that is equal to zero.
The double or float value NaN.
Otherwise, fn:boolean returns true.
The effective boolean value of a sequence may be computed during processing of the following types of expressions:
Logical expressions (and, or)
The fn:not function
The where clause of a FLWOR expression
Conditional expressions (if)
Quantified expressions (some, every)
Ed. Note: This section is still under review by the working group.
Certain kinds of expressions introduce named variables and bind them to values. For example, the following expression binds the variable $i successively to the values 1, 2, and 3, and uses each of these bindings to evaluate the nested expression $i * 2:
for $i in (1, 2, 3) return $i * 2
In XQuery, the kinds of expressions that can bind variables are FLWOR expressions (3.8 FLWOR Expressions), quantified expressions (3.11 Quantified Expressions), and typeswitch expressions (3.12.2 Typeswitch).
Expressions that bind variables can be nested, and an inner expression can contain references to variables bound in an outer expression. More formally, the rules for binding variables and for referring to bound variables in XQuery are as follows:
The innermost expression that contains the defining occurrence of a variable name is called the containing expression for that variable. The expression that establishes the value to which a variable is bound is called the binding expression for that variable. A variable is in scope (and may thus be referenced) within any subexpression of its containing expression, with the following exceptions:
Its binding expression
Any expression that textually precedes its binding expression
Variables that share the same containing expression must have different names.
If two or more variables with the same name are in scope within the same expression, any variable reference with that name is interpreted as a reference to the variable that has the smallest containing expression.
The name of a variable is a QName, and variable names match if their expanded-QNames are the same--that is, if they have the same namespace and the same local name.
As described in 2.4.1 Type Checking, XQuery defines an analysis phase, which does not depend on input data, and an evaluation phase, which does depend on input data.
The result of the analysis phase is either success or one or more type errors and/or static errors. Type errors reported by the analysis phase occur when the static type of an expression is not correct for the context in which it appears. Static errors are non-type-related errors such as syntax errors. The means by which errors are reported during the analysis phase is implementation-defined.
The result of the evaluation phase is either a result value, a type error, or a dynamic error. Type errors are raised during the evaluation phase when the dynamic type of an expression is not correct for the context in which it appears. Dynamic errors are non-type-related errors such as numeric overflow. If evaluation of an expression yields a value (that is, it does not raise an error), the value must be the value specified by the dynamic semantics defined in [XQuery 1.0 Formal Semantics].
If an implementation can determine by static analysis that an expression will necessarily raise a dynamic error (for example, because it attempts to construct a decimal value from a constrant string that is not in the lexical space of xs:decimal), the implementation is allowed to report this error during the analysis phase (as well as during the evaluation phase).
[XQuery 1.0 Formal Semantics] defines the set of static, dynamic, and type errors. In addition to these errors, an XQuery implementation may raise implementation-defined warnings, either during the analysis phase or the evaluation phase. The way in which warnings are raised and handled is implementation-defined.
In addition to the errors defined in this specification, an implementation may specify a list of resource-related limitations, such as maximum numbers or sizes of various objects. These limitations, and the consequences of exceeding them, are implementation-defined.
XQuery defines a basic conformance level named Basic XQuery, and two optional features called the Schema Import Feature and the Static Typing Feature. A conforming implementation must satisfy the requirements of Basic XQuery, and may also provide either or both of the optional features.
A conforming Basic XQuery implementation must implement the full XQuery language, subject to the following limitations:
If a QueryProlog contains a SchemaImport, a Basic XQuery implementation raises a static error.
In a Basic XQuery
implementation, the in-scope schema
definitions consist of a fixed set of 48 predefined type definitions. These
include the 44 built-in datatypes defined in [XML Schema], plus four
additional types: fn:yearMonthDuration,
fn:dayTimeDuration,
xs:anySimpleType, and xs:anyType.
A mapping from a Post-Schema Validation Infoset (PSVI) to the Data Model is specified in [XQuery 1.0 and XPath 2.0 Data Model]. In a Basic XQuery implementation, this mapping maps each datatype that is not one of the 48 predefined types listed above into its nearest supertype that belongs to this list. As a result of this mapping, all complex types are mapped into xs:anyType. (Of course, mapping from a PSVI is only one way in which a Data Model instance might be constructed--other ways are also possible.)
If any SequenceType contains an AtomicType that is not one of the 48 predefined types listed above, a Basic XQuery implementation raises a static error.
If any SequenceType contains an ElemOrAttrType, a Basic XQuery implementation raises a static error.
If the processing of an expression depends on the type of some value, and that type is not one of the 48 predefined types listed above, a Basic XQuery implementation raises a dynamic error.
A Basic XQuery implementation is not required to raise type errors during the analysis phase. If an expression contains one or more non-type-related static errors, then a Basic XQuery implementation must raise at least one of these static errors during the analysis phase. If the analysis phase is successful but one or more dynamic errors are encountered during the evaluation phase, then a Basic XQuery implementation must raise at least one of these dynamic errors.
The Schema Import Feature removes the limitations specified by Rules 1 through 6 of Basic XQuery.
During the analysis phase, in-scope schema definitions are derived from schemas named in Schema Import clauses. If more than one schema is imported, the definitions contained in these schemas are collected into a single pool of definitions. This pool of definitions must satisfy the conditions for schema validity set out in Sections 3 and 5 of [XML Schema] Part 1. In brief, the definitions must be valid, they must be complete and they must be unique--that is, the pool of definitions must not contain two or more schema components with the same name and target namespace. If any of these conditions is violated, a static error must be raised.
The Static Typing Feature removes the limitation specified by Rule 7 of Basic XQuery. An implementation that includes this feature is required to detect type errors during the analysis phase. If an expression contains one or more static errors or type errors, then a Static Typing implementation must raise at least one of these errors during the analysis phase.
Ed. Note: The Working Group is currently discussing the relationships among the various XQuery features (for example, if an expression executes successfully on an implementation with Feature A, will it also execute successfully on an implementation with Feature B?). The Working Group is also discussing the issue of "type soundness" (that is, if the Static Typing Feature is implemented and a given expression raises no type errors during the analysis phase, what guarantees can be made about its behavior during the evaluation phase?). The editors expect to include more material on these issues in a future version of this document. (See Issue 308.)
Except as noted in this document, if any operand of an expression
raises a dynamic error, the expression also raises a dynamic error.
If an expression can validly return a value or raise a dynamic
error, the implementation may choose to return the value or raise
the dynamic error. For example, the logical expression
expr1 and expr2 may return the value false
if either operand returns false,
or may raise a dynamic error if either operand raises a dynamic
error.
If more than one operand of an expression may raise an error, the implementation may choose which error is raised by the expression. For example, in this expression:
($x div $y) + xs:decimal($z)
both ($x div $y) and xs:decimal($z) may
raise an error. The
implementation may choose which error is raised by the "+"
expression. Once one operand raises an error, the implementation is
not required, but is permitted, to evaluate any other operands.
A dynamic error carries an error value, which may be a single item or an empty sequence. For example, an error value might be an integer, a string, a QName, or an element. An implementation may provide a mechanism whereby an application-defined error handler can process error values and produce diagnostics; in the absence of such an error handler, the string-value of the error value may be used directly as an error message.
A dynamic error may be raised by a built-in
function or operator. For example,
the input function raises an error if the input
sequence is not
defined in the evaluation context.
An error can be raised explicitly by calling the
fn:error function,
which only raises an error and never returns a value.
The fn:error function takes an optional item as its parameter, which is used as the error value. For example, the following function call raises a dynamic error
whose error value is a string:
fn:error(fn:concat("Unexpected value ", $v))
Because different implementations may choose to evaluate or optimize an expression in different ways, the detection and reporting of dynamic errors is implementation dependent.
When an implementation is able to evaluate an expression without evaluating some subexpression, the implementation is never required to evaluate that subexpression solely to determine whether it raises a dynamic error. For example, if a function parameter is never used in the body of the function, an implementation may choose whether to evaluate the expression bound to that parameter in a function call.
In some cases, an optimizer may be able to achieve substantial performance improvements by rearranging an expression so that the underlying operations such as projection, restriction, and sorting are performed in a different order than that specified in [XQuery 1.0 Formal Semantics]. In such cases, dynamic errors may occur that could not have occurred if the expression were evaluated as written. For example, consider the following expression:
$N[@x castable as xs:date]
[xs:date(@x) gt xs:date("2000-01-01")]
This expression cannot fail with a casting error if it is evaluated exactly as written. An implementation is permitted, however, to reorder the predicates to achieve better performance (for example, by taking advantage of an index). This reordering could cause the above expression to fail. However, an expression must not be rearranged in a way that causes it to return a non-error result that is different from the result defined by [XQuery 1.0 Formal Semantics].
To avoid unexpected errors caused by reordering of expressions, tests that are designed to prevent dynamic errors should be expressed using conditional expressions, as in the following example:
$N[if (@x castable as xs:date)
then xs:date(@x) gt xs:date("2000-01-01")
else false()]
In the case of a conditional expression, the implementation is required not to evaluate the then branch if the condition is false, and not to evaluate the else branch if the condition is true. Conditional and typeswitch expressions are the only kinds of expressions that provide guaranteed conditions under which a particular subexpression will not be evaluated.
This section introduces each of the basic kinds of XQuery expression. Each kind of expression has a name such as PathExpr, which is introduced on the left side of the grammar production that defines the expression. Since XQuery is a composable language, each kind of expression is defined in terms of other expressions whose operators have a higher precedence. In this way, the precedence of operators is represented explicitly in the grammar.
The simplest kinds of expressions are introduced first, followed by more complex expressions. This order of presentation does not conform to the order of operator precedence. The complete grammar is presented in the appendix [A Grammar].
The highest-level kind of expression (that is, the kind of expression whose operators have lowest precedence) is OrExpr.
| [25] | Expr | ::= | OrExpr |
Primary expressions are the basic primitives of the language. They include literals, variables, function calls, and the use of parentheses to control precedence of operators.
| [62] | PrimaryExpr | ::= | Literal | FunctionCall | ("$" VarName) | ParenthesizedExpr |
| [13] | VarName | ::= | QName |
A literal is a direct syntactic representation of an atomic value. XQuery supports two kinds of literals: string literals and numeric literals.
| [79] | Literal | ::= | NumericLiteral | StringLiteral |
| [78] | NumericLiteral | ::= | IntegerLiteral | DecimalLiteral | DoubleLiteral |
| [1] | IntegerLiteral | ::= | Digits |
| [2] | DecimalLiteral | ::= | ("." Digits) | (Digits "." [0-9]*) |
| [3] | DoubleLiteral | ::= | (("." Digits) | (Digits ("." [0-9]*)?)) ("e" | "E") ("+" | "-")? Digits |
| [4] | StringLiteral
(ws: significant) | ::= | ('"' (('"' '"') | [^"])* '"') | ("'" (("'" "'") | [^'])* "'") |
| [5] | URLLiteral
(ws: significant) | ::= | ('"' (('"' '"') | [^"])* '"') | ("'" (("'" "'") | [^'])* "'") |
The value of a string literal is a singleton sequence
containing an item whose primitive type is xs:string and whose value is the string denoted by the characters between the
delimiting quotation marks. If the literal is delimited by single quotes, two adjacent single quote characters within the literal are interpreted as one single quote character. Similarly, if the literal is delimited by double quotes, two adjacent double quote characters within the literal are interpreted as one double quote character.
A URL Literal is defined equivalently to a string literal.
The value of a numeric literal containing no "." and no e or E character is a singleton sequence containing an item whose type is xs:integer and whose value is obtained by parsing the numeric literal according to
the rules of the xs:integer datatype. The value of a numeric literal containing "." but no e or E character is a singleton sequence containing an item whose primitive
type is xs:decimal and whose value is obtained by parsing the numeric literal according to
the rules of the xs:decimal datatype. The value of a numeric literal containing an e or E character is a singleton sequence containing an item whose primitive
type is xs:double and whose value is obtained by parsing the numeric literal according to
the rules of the xs:double datatype.
Here are some examples of literal expressions:
"12.5" denotes the string containing the characters '1', '2', '.', and
'5'.
12 denotes the integer value twelve.
12.5 denotes the decimal value twelve and one half.
125E2 denotes the double value twelve thousand, five hundred.
The boolean values true and false can be represented by calls to the built-in functions fn:true() and fn:false(), respectively.
Values of other XML Schema built-in types can be constructed by calling the constructor for the given type. The constructors for XML Schema built-in types are defined in [XQuery 1.0 and XPath 2.0 Functions and Operators]. In general, the name of a constructor function for a given type is the same as the name of the type (including its namespace). For example:
xs:integer("12") returns the integer value twelve.
xs:date("2001-08-25") returns an item whose type is xs:date and whose value represents the date 25th August 2001.
fn:dayTimeDuration("PT5H") returns an item whose type is fn:dayTimeDuration and whose value represents a duration of five hours.
It is also possible to construct values of various types by using a cast expression. For example:
cast as
hatsize(9) returns an item whose primitive value is the integer 9 and
whose type is the user-defined type hatsize, derived from xs:integer.
A variable evaluates to the value to which its name is bound in the evaluation context. An expression containing an unbound variable raises a static error.
In XQuery, the kinds of expressions that can bind variables are FLWOR expressions (3.8 FLWOR Expressions), quantified expressions (3.11 Quantified Expressions), and typeswitch expressions (3.12.2 Typeswitch). Function calls also bind values to the formal parameters of functions before executing the function body. Variables can also be bound in the external environment, outside the scope of a query.
| [80] | ParenthesizedExpr | ::= | "(" ExprSequence? ")" |
Parentheses may be used to enforce a particular evaluation order in
expressions that contain multiple operators. For example, the expression (2 + 4)
* 5 evaluates to thirty, since the parenthesized expression (2 + 4) is evaluated first and its result is multiplied by five. Without
parentheses, the expression 2 + 4 * 5 evaluates to twenty-two, because the multiplication operator has higher
precedence than the addition operator.
Empty parentheses are used to denote an empty sequence, as described in 3.3.1 Constructing Sequences.
A function call consists of a QName followed by a parenthesized list of zero or more expressions, called arguments. The QName and number of arguments must match the name and arity of an in-scope function in the static context (see 2.1 Expression Context); otherwise, a static error is raised.
| [81] | FunctionCall | ::= | <QName "("> (Expr ("," Expr)*)? ")" |
A function call is evaluated as follows:
Each argument expression is evaluated, producing an argument value.
Each argument value is converted by applying the function conversion rules listed below.
If the function is a built-in function, it is executed using the converted argument values. The result is a value of the function's declared return type.
If the function is a user-defined function, the converted argument values are bound to the formal parameters of the function, and the function body is evaluated. The value returned by the function body is then converted to the declared return type of the function by applying the function conversion rules.
When a converted argument value is bound to a function parameter, the argument value retains its most specific type, even though this may be a subtype of the type of the formal parameter. For example, a function with a parameter $p of type xs:decimal can be invoked with an argument of type xs:integer, which is derived from xs:decimal. During the processing of this function invocation, the dynamic type of $p inside the body of the function is considered to be xs:integer.
A function does not inherit a focus (context item, context position, and context size) from the environment of the function call. During evaluation of a function body, the focus is undefined, except where it is defined by the action of some expression inside the function body. Use of an expression that depends on the focus when the focus is undefined raises a static error.
The function conversion rules are used to convert an argument value or a return value to its expected type; that is, to the declared type of the function parameter or return. The expected type is expressed as a SequenceType. The function conversion rules are applied to a given value as follows:
If the expected type is a sequence of an atomic type (possibly with an occurrence indicator *, +, or ?), the following conversions are applied:
Atomization is applied to the given value, resulting in a sequence of atomic values.
Each item in the atomic sequence that is of type xs:anySimpleType is cast to the required atomic type.
For each numeric item in the atomic sequence that can be promoted to the expected atomic type using the promotion rules in B.1 Type Promotion, the promotion is done.
If, after the above conversions, the resulting value does not match the expected type according to the rules for SequenceType Matching, a type error is raised. Note that the rules for SequenceType Matching permit a value of a derived type to be substituted for a value of its base type.
A core library of functions is defined in [XQuery 1.0 and XPath 2.0 Functions and Operators]. Functions in this library may be invoked without a namespace prefix by assigning the default function namespace to the namespace of the function library.
The comma operator in XQuery serves two purposes: it separates the arguments in a function call, and it separates items in an expression that constructs a sequence (see 3.3.1 Constructing Sequences). To distinguish these two uses, parentheses can be used to delimit the individual arguments of a function call. Here are some illustrative examples of function calls:
three-argument-function(1,
2, 3) denotes a function call with three arguments.
two-argument-function((1,
2), 3) denotes a function call with two arguments, the first of which is a
sequence of two values.
two-argument-function(1,
()) denotes a function call with two arguments, the second of which is an
empty sequence.
one-argument-function((1, 2,
3)) denotes a function call with one argument that is a sequence of three
values.
one-argument-function(( )) denotes a function call with one argument that is an empty sequence.
zero-argument-function( ) denotes a function call with zero arguments.
XQuery comments can be used to provide informative annotation. These comments are lexical constructs only, and do not affect the processing of an expression.
| [6] | ExprComment | ::= | "{--" [^}]* "--}" |
Comments may be used anywhere that ignorable whitespace is allowed, and within element content. See A.1 Lexical structure for the exact lexical states where comments are recognized.
The following is an example of a comment:
{-- Houston, we have a problem --}
Ed. Note: The EBNF should disallow "--}" within the comment, rather than "}". Also, within an enclosed expression, a comment immediately after the opening "{" will cause the "{{" to be mistaken for an escaped "{". Thus,
<a>{{--comment--}foo}</a>will be processed as element content.
A path expression can be used to locate nodes within a tree. Because the XQuery grammar is organized around the precedence of operators, the syntax for PathExpr also includes PrimaryExpr. In common usage, the term path expression denotes a PathExpr that is not simply a PrimaryExpr.
| [42] | PathExpr | ::= | ("/" RelativePathExpr?) | ("//" RelativePathExpr) | RelativePathExpr |
| [43] | RelativePathExpr | ::= | StepExpr (("/" | "//") StepExpr)* |
A path expression consists of a series of one or more steps, separated by "/", and optionally beginning with "/" or "//". An initial "/" or "//" is an abbreviation for one or more initial steps that are implicitly added to the beginning of the path expression, as described below.
A path expression consisting of a single step is evaluated as described in 3.2.1 Steps.
In a path expression consisting of two or more steps, each occurrence of // is expanded as described in 3.2.4 Abbreviated Syntax, leaving a sequence of steps separated by /. This sequence of steps is then evaluated from left to right. Each operation E1/E2 is evaluated as follows: Expression E1 is evaluated, and if the result is not a sequence of nodes, a dynamic error is raised. The resulting sequence of nodes is sorted in document order, and duplicates are eliminated based on node identity. Each node resulting from the evaluation of E1 then serves in turn to provide an inner focus for an evaluation of E2, as described in 2.1.2 Evaluation Context. Each evaluation of E2 must result in a sequence of nodes; otherwise, a dynamic error is raised. The sequences of nodes resulting from all the evaluations of E2 are merged, eliminating duplicate nodes based on node identity and sorting the results in document
order.
As an example of a path expression, child::div1/child::para selects the para element children of the div1 element children of the context node, or, in other words, the para element grandchildren of the context node that have div1 parents.
A "/" at the beginning of a path expression is an abbreviation for the initial step fn:root(self::node()). The effect of this initial step is to begin the path at the root node that contains the context node. If the context item is not a node, a dynamic error is raised.
A "//" at the beginning of a path expression is an abbreviation for the initial steps fn:root(self::node())/descendant-or-self::node(). The effect of these initial steps is to establish an initial node sequence that contains all nodes in the same hierarchy as the context node. This node sequence is then filtered by subsequent steps in the path expression. If the context item is not a node, a dynamic error is raised.
A step generates a sequence of items and then filters the sequence by zero or more predicates. The value of the step consists of those items that satisfy the predicates. Predicates are described in 3.2.2 Predicates.
A step may consist of a primary expression (described in 3.1 Primary Expressions), a forward step, or a reverse step. A forward or reverse step always returns a sequence of nodes. A forward or reverse step might be thought of as beginning at the context node and navigating to those nodes that are reachable from the context node via a specified axis. Such a step has two parts: an axis, which defines the "direction of movement" for the step, and a node test, which specifies the node kind and/or name of the nodes to be selected by the step.
In the abbreviated syntax for a step, the axis can be omitted and other shorthand notations can be used as described in 3.2.4 Abbreviated Syntax.
The unabbreviated syntax for a forward or reverse step consists of the axis name
and node test separated by a double colon. The result of the step consists of the nodes
reachable from the context node via the specified axis that have the node kind
and/or name specified by the node test. For example, the
step child::para selects the para element children of the context node: child is the name of the axis, and para is the name of the element nodes to be selected on this axis. The available axes are described in 3.2.1.1 Axes. The
available node tests are described in 3.2.1.2 Node Tests. Examples of
steps are provided in 3.2.3 Unabbreviated Syntax and 3.2.4 Abbreviated Syntax.
| [63] | ForwardAxis | ::= | <"child" "::"> |
| [64] | ReverseAxis | ::= | <"parent" "::"> |
XQuery supports the following axes:
the child axis contains the children of the context node
the descendant axis contains the descendants of the context node; a descendant is a
child or a child of a child and so on; thus the descendant axis never contains
attribute or namespace nodes
the parent axis contains the parent of the context node, if there is one
the attribute axis contains the attributes of the context node; the axis will be
empty unless the context node is an element
the self axis contains just the context node itself
the descendant-or-self axis contains the context node and the descendants of the context
node
Axes can be categorized as forward axes and reverse axes. An axis that only ever contains the context node or nodes that are after the context node in document order is a forward axis. An axis that only ever contains the context node or nodes that are before the context node in document order is a reverse axis.
In XQuery, the parent axis is a reverse axis; all other axes are forward axes. Since the self axis always contains at most one node, it makes no difference whether
it is a forward or reverse axis.
A node test is a condition that must be true for each node selected by a step. The condition may be based on the kind of the node (element, attribute, text, document, comment, processing instruction, or namespace) or on the name of the node.
| [65] | NodeTest | ::= | KindTest | NameTest |
| [66] | NameTest | ::= | QName | Wildcard |
| [67] | Wildcard | ::= | "*" | <NCName ":" "*"> | <"*" ":" NCName> |
| [68] | KindTest | ::= | ProcessingInstructionTest
|
| [69] | ProcessingInstructionTest | ::= | <"processing-instruction" "("> StringLiteral? ")" |
| [70] | CommentTest | ::= | <"comment" "("> ")" |
| [71] | TextTest | ::= | <"text" "("> ")" |
| [72] | AnyKindTest | ::= | <"node" "("> ")" |
Every axis has a principal node kind. If an axis can contain elements, then the principal node kind is element; otherwise, it is the kind of nodes that the axis can contain. Thus:
For the attribute axis, the principal node kind is attribute.
For all other axes, the principal node kind is element.
A node test that consists of a QName is called a name test. A name test is true if and only if the
kind of the node is the principal
node kind and the expanded-QName of the node is equal to the expanded-QName
specified by the name test. For example, child::para selects the para element children of the context node; if the context node has no para children, it selects an empty set of nodes. attribute::abc:href selects the attribute of the context node with the QName abc:href; if the context node has no such attribute, it selects an empty set of nodes.
A QName in a name test is expanded into an expanded-QName using the in-scope namespaces in the expression context. An unprefixed QName used as a name test has the namespaceURI associated with the default element namespace in the expression context. It is a static error if the QName has a prefix that does not correspond to any in-scope namespace.
A name test is not satisfied by an element node whose name does not match the QName of the name test, even if it is in a substitution group whose head is the named element.
A node test * is true for any node of the principal node kind. For example, child::* will select all element children of the context node, and attribute::* will select all attributes of the context node.
A node test can have the form NCName:*. In this case, the prefix is expanded in the same way as with a QName,
using the context namespace declarations. It is a static error if there is no
namespace declaration for the prefix in the expression context. The node test
will be true for any node of the principal node kind whose expanded-QName has the
namespace URI to which the prefix expands, regardless of the local part of the
name.
A node test can also have the form *:NCName. In this case, the node test is true for any node of the principal node
kind whose local name matches the given NCName, regardless of its
namespace.
The node test text() is true for any text node. For example, child::text() will select the text node children of the context node. Similarly, the
node test comment() is true for any comment node, and the node test processing-instruction() is true for any processing instruction. The processing-instruction() test may have an argument that is a StringLiteral; in this
case, it is true for any processing instruction whose target application is equal to the
value of the StringLiteral.
A node test node() is true for any node whatsoever.
Note:
In order to be consistent with QName in XML, whitespace is not allowed in the Wildcard production. For instance "prefix:*" is allowed, but "prefix : *" is not allowed.
| [77] | Predicates | ::= | ("[" Expr "]")* |
A predicate consists of an expression, called a predicate
expression, enclosed in square brackets. A predicate serves to filter a sequence, retaining some items and discarding others. For each item in the sequence to be filtered, the predicate expression is evaluated using an
inner focus derived from that item, as described in
2.1.2 Evaluation Context. The result of the predicate expression is
coerced to a Boolean value, called the predicate truth value, as
described below. Those items for which the predicate truth value is true are retained, and those for which the predicate truth value is false are discarded.
The predicate truth value is derived by applying the following rules, in order:
If the value of the predicate expression is an atomic value of a
numeric type, the predicate truth value is true if and only if the value of the predicate expression is equal to the context position.
Otherwise, the predicate truth value is the Effective Boolean Value of the predicate expression.
Here are some examples of steps that contain predicates:
This example selects the second chapter element that is a child
of the context node:
child::chapter[2]
This example selects all the descendants of the context node whose
name is "toy" and whose color attribute has the value "red":
descendant::toy[attribute::color = "red"]
This example selects all the employee children of the context node
that have a secretary subelement:
child::employee[secretary]
A predicate can also be used with a primary expression that is not a forward or reverse step, as illustrated in the following example:
List all the integers from 1 to 100 that are divisible by 5. (See 3.3.1 Constructing Sequences for an explanation of the to operator.)
(1 to 100)[. mod 5 eq 0]
This section provides a number of examples of path expressions in which the axis is explicitly specified in each step. The syntax used in these examples is called the unabbreviated syntax. In many common cases, it is possible to write path expressions more concisely using an abbreviated syntax, as explained in 3.2.4 Abbreviated Syntax.
child::para selects
the para element children of the context node
child::* selects all element children of the context node
child::text() selects all text node children of the context node
child::node() selects all the children of the context node, whatever their node
type
attribute::name selects the name attribute of the context node
attribute::* selects all the attributes of the context node
descendant::para selects the para element descendants of the context node
descendant-or-self::para selects the para element descendants of the context node and, if the context node is a para element, the context node as well
self::para selects the context node if it is a para element, and otherwise selects nothing
child::chapter/descendant::para selects the para element
descendants of the chapter element children of the context node
child::*/child::para selects all para grandchildren of the context node
/ selects the root of the node hierarchy that contains the context node
/descendant::para selects all the para elements in the same document as the context node
/descendant::list/child::member selects all
the member elements that have a list parent and that are in the same document as the context node
child::para[fn:position() = 1] selects the first para child of the context node
child::para[fn:position() = fn:last()] selects the last para child of the context node
child::para[fn:position() = fn:last()-1] selects the last but one para child of the context node
child::para[fn:position() > 1] selects all the para children of the context node other than the first para child of the context node
/descendant::figure[fn:position() = 42] selects the forty-second figure element in the document
/child::doc/child::chapter[fn:position() = 5]/child::section[fn:position() = 2]selects the
second section of the fifth chapter of the doc document element
child::para[attribute::type="warning"]selects
all para children of the context node that have a type attribute with value warning
child::para[attribute::type='warning'][fn:position() = 5]selects the fifth para child of the context node that has a type attribute with value warning
child::para[fn:position() = 5][attribute::type="warning"]selects the fifth para child of the context node if that child has a type attribute with value warning
child::chapter[child::title='Introduction']selects the chapter children of the context node that have one or more title children with string-value equal to Introduction
child::chapter[child::title] selects the chapter children of the context node that have one or more title children
child::*[self::chapter or self::appendix]
selects the chapter and appendix children of the context node
child::*[self::chapter or
self::appendix][fn:position() = fn:last()] selects the
last chapter or appendix child of the context node