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 new details about error handling and conformance. It contains a new grammar in which the precedence of operators is explicitly represented. It introduces two new operators (unordered and idiv), and deletes four operators (assert, precedes, follows, and =>). It introduces two new declarations into the Query Prolog, called xmlspace and default collation. It also describes changes to the detailed semantics of cast expressions, element constructors, and other operators, as summarized in F Revision
Log.
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.3 Type Conversions
2.4.3.1 Atomization
2.4.3.2 Effective Boolean Value
2.5 Errors and Conformance
2.5.1 Errors
2.5.2 Conformance
2.5.2.1 Basic XQuery
2.5.2.2 Schema Import Feature
2.5.2.3 Static Typing Feature
2.5.3 Handling Dynamic Errors
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.5 Other Constructors and Comments
3.8 FLWR Expressions
3.9 Order-Related Expressions
3.9.1 Sort Expressions
3.9.2 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 and 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 Words
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 16 Aug 2002
F.2 10 Apr 2002
F.3 20 Dec
2001
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, 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:
| [58] | 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 xf: is considered to be bound to the namespace of XPath/XQuery functions, http://www.w3.org/2002/08/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 will be used without a namespace prefix.
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 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.
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 xf:document function when resolving the relative URI of a document to be loaded, if
no explicit base URI is supplied in the function call.
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, the predicate expression E1[E2], and the ordering expression E1 sort by (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.
[Ed. Note: See issue 216.]
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, E1[E2] or E2 sort by (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 xf:position(). When an expression E1/E2, E1[E2], or E1 sort by (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, E1[E2], or E1 sort by (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.
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 xf:current-date, xf:current-time, and xf: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 three 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 three 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 instance, 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 function, which takes no parameters, returns the input
sequence. For example, the expression
input()//customer returns
all the customer elements that are descendants of
nodes in the input sequence. If no input sequence has been bound,
the input function raises a dynamic error.
The 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
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 document function, when its first argument
is a string containing a single URI that refers to an
XML document, returns the root of that document. The
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.
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]. Transformation of a Data Model instance into an XML document is currently an open issue.
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. 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. 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 complex 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 node kinds
of XML (such as element, attribute, and text nodes), the built-in atomic types of [XML Schema] (such as xs:integer and xs:string), and the following special derived types: xf:dayTimeDuration and xf: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 exception is raised. Languages that are based on XPath 2.0 may handle type exceptions with either a strict or a flexible policy, as described in [XPath 2.0]. XQuery has a strict type exception policy, which means that all type exceptions are treated as errors.
Like XML Schema, XQuery distinguishes named types from anonymous types. The set of named types includes all the built-in types and all user-defined simple or complex types for which the type declaration contains a name. For example, named types may be associated with values in one of the following ways:
A literal value has a named type; for example, the type of the value 47 is xs:integer.
The constructor functions described in [XQuery 1.0 and XPath 2.0 Functions and Operators] return values with named types; for example, xs:date("2002-5-31") returns a value of type xs:date.
When an instance of the Data Model is constructed from a validated document, type names assigned by a schema processor are preserved in the Data Model.
The validate expression invokes schema validation within a query, assigning type
names in the same way that a schema processor would.
The cast expression creates an atomic value with a specific named type.
Some functions, such as data(), extract typed values from the nodes of a document, preserving the named types of these values.
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 static 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 to produce either a value of type T or to raise a dynamic type 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 exception is raised.
It is possible for analysis of an expression to raise a static 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 static 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.
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 a valid decimal value), the implementation is allowed to report this error during the analysis phase (as well as during the evaluation phase).
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.
| [64] | SequenceType | ::= | (ItemType OccurrenceIndicator) | "empty" |
| [65] | ItemType | ::= | (("element" | "attribute") ElemOrAttrType?) |
| [66] | ElemOrAttrType | ::= | (QName (SchemaType | SchemaContext?)) | SchemaType |
| [67] | SchemaType | ::= | <"of" "type"> QName |
| [60] | SchemaContext | ::= | "in" SchemaGlobalContext ("/" SchemaContextStep)* |
| [61] | SchemaGlobalContext | ::= | QName | <"type" QName> |
| [62] | SchemaContextStep | ::= | QName |
| [68] | AtomicType | ::= | QName |
| [69] | 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 given element or attribute has the required name and also conforms to the schema definition for the required name. This can be verified in either of the following ways:
If the schema definition for the required name has a named type, the given element or attribute must have a type annotation that is the same as that named type or is known (in the in-scope schema definitions) to be derived from that named type. For example, suppose that a schema declares the element named location to have the type State. Then the SequenceType element location will match a given element only if its name is location and its type annotation is State or some named type that is derived from State.
If the schema definition for the required name has an anonymous (unnamed) type definition, the actual content of the given element or attribute must structurally comply with this type definition. For example, suppose that a schema declares the element named shippingAddress to have an anonymous complex type consisting of a street element followed by a city element. Then the SequenceType element shippingAddress will match a given element only if its name is shippingAddress and its content is a street element followed by a city element.
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 an optional atomic value is expected. When atomization is applied to a given value, the result is either a single atomic value, an empty sequence, or a type exception. Atomization is defined as follows:
If the value is a single atomic value or an empty sequence, atomization simply returns the value.
If the value is a single node, the typed value of the node is extracted and returned; however, if the typed value is a sequence containing more than one item, a type exception is raised.
In any other case, atomization raises a type exception.
Atomization may be used in processing the following types of expressions:
Arithmetic expressions
Comparison expressions
Function calls and returns
Cast expressions
Sort 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 follows:
If the sequence is empty, its effective boolean value is false.
If the sequence contains a single atomic value of type xs:boolean, this value is the effective boolean value of the sequence.
If the sequence contains at least one node, its effective
boolean value is true.
In any other case, a type exception is raised. In XQuery, a type exception always raises a dynamic error.
The effective boolean value of a sequence may be computed during the processing of the following types of expressions:
Logical expressions (and, or)
The xf:not function
The where clause of a FLWR expression
Conditional expressions (if)
Quantified expressions (some, every)
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 static errors. Some static errors are static type errors, which occur when the static type of an expression is not correct for the context in which it appears. The term static errors also includes non-type-related errors such as syntax errors. The means by which static errors are reported is implementation-defined.
The result of the evaluation phase is either a result value or a dynamic error. Some dynamic errors are dynamic type errors, which occur when the dynamic type of an expression is not correct for the context in which it appears. The term dynamic errors also includes non-type-related dynamic errors such as numeric overflow. If an implementation returns a value, the value must conform to the dynamic rules defined in [XQuery 1.0 Formal Semantics].
[XQuery 1.0 Formal Semantics] defines the set of static and dynamic 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.
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: xf:yearMonthDuration,
xf:dayTimeDuration,
xs:anySimpleType, and xs:anyType.
A mapping from a Post-Schema Validation Infoset (PSVI) to the Query 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 Query 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 static 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 static type errors. If an expression contains one or more static errors, including static type errors, then a Static Typing implementation must raise at least one of these static 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 static errors, 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) + xsd:decimal($z)
both ($x div $y) and xsd: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
xf:error function,
which only raises an error and never returns a value.
The xf: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:
xf:error(xf:concat("Unexpected value ", $v))
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 SortExpr, which is defined in 3.9.1 Sort Expressions.
| [5] | Expr | ::= | SortExpr |
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.
| [39] | PrimaryExpr | ::= | Literal | FunctionCall | ("$" VarName) | ParenthesizedExpr |
| [228] | VarName | ::= | QName |
A literal is a direct syntactic representation of an atomic value. XQuery supports two kinds of literals: string literals and numeric literals.
| [56] | Literal | ::= | NumericLiteral | StringLiteral |
| [55] | NumericLiteral | ::= | IntegerLiteral | DecimalLiteral | DoubleLiteral |
| [194] | IntegerLiteral | ::= | Digits |
| [195] | DecimalLiteral | ::= | ("." Digits) | (Digits "." [0-9]*) |
| [196] | DoubleLiteral | ::= | (("." Digits) | (Digits ("." [0-9]*)?)) ("e" | "E") ("+" | "-")? Digits |
| [215] | StringLiteral | ::= | ('"' (('"' '"') | [^"])* '"') | ("'" (("'" "'") | [^'])* "'") |
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.
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 xf:true() and xf: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.
xf:dayTimeDuration("PT5H") returns an item whose type is xf: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. Variables can be bound by clauses in for expressions and quantified expressions, and by function calls, which bind values to the formal parameters of functions before executing the function body.
| [57] | 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.
| [58] | FunctionCall | ::= | <QName "("> (Expr ("," Expr)*)? ")" |
A function call expression is evaluated as follows:
Each argument expression is evaluated, producing an argument value.
Each argument value is converted to the declared type of the corresponding function parameter, using 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.
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 results in a dynamic error.
The function conversion rules are used to convert an argument value or a return value to its required type; that is, to the declared type of the function parameter or return. The required type is expressed as a SequenceType. The function conversion rules are as follows:
If the required type is an AtomicType:
Atomization is applied to the given value. If the resulting atomic value is
of type xs:anySimpleType, an attempt is made to cast it to the required type; if the cast fails,
the function call raises a dynamic type error. If the atomic value has a type that can be promoted
to the required type using the promotion rules in B.1 Type Promotion,
the promotion is done.
If the required type is a sequence or optional occurrence of AtomicType:
If the given value contains any nodes, these nodes are replaced by their typed values. Each item is converted to the required AtomicType using the conversion rule for AtomicType.
If the required type is any other SequenceType, or if no required type is declared:
No conversion is performed.
If the Static Typing Feature is implemented, and the static type of a (converted) function argument or result, as inferred by the static type inference rules in [XQuery 1.0 Formal Semantics], is not a subtype of the required type, a static type error is raised. If the Static Typing Feature is not implemented, and the dynamic type of a (converted) function argument or result does not match the required type according to the rules for SequenceType Matching, a dynamic type error is raised.
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.
| [94] | ExprComment | ::= | "{--" [^}]* "--}" |
Comments may be used before and after major tokens within expressions 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 currently cause an error, and must be disambiguated with a space between the "{" characters. This should be considered an open issue.
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.
| [23] | PathExpr | ::= | ("/" RelativePathExpr?) | ("//" RelativePathExpr) | RelativePathExpr |
| [24] | 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 xf: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 xf: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.
| [40] | ForwardAxis | ::= | <"child" "::"> |
| [41] | 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.
| [42] | NodeTest | ::= | KindTest | NameTest |
| [43] | NameTest | ::= | QName | Wildcard |
| [44] | Wildcard | ::= | "*" | <NCName ":" "*"> | <"*" ":" NCName> |
| [45] | KindTest | ::= | ProcessingInstructionTest
|
| [46] | ProcessingInstructionTest | ::= | <"processing-instruction" "("> StringLiteral? ")" |
| [47] | CommentTest | ::= | <"comment" "("> ")" |
| [48] | TextTest | ::= | <"text" "("> ")" |
| [49] | 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 the namespace axis, the principal node kind is namespace.
For all other axes, the principal node kind is element.
A node test that is a QName is true if and only if the
kind of the node is the principal
node kind and the expanded-name of the node is equal to the expanded-name
specified by the QName. 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 node test is expanded into an expanded-name using the in-scope namespaces in the expression context. An unprefixed QName used as a nametest 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 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-name 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.
| [54] | 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 empty sequence, the
predicate truth value is false.
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.
If the value of the predicate expression is an atomic value of type Boolean, the predicate truth value is equal to the value of the predicate expression.
If the value of the predicate expression is a sequence that contains
at least one node, the predicate truth value is true. The predicate truth value in this case does not depend on
the content of the node(s).
In any other case, a type exception is raised.
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 an list parent and that are in the same document as the context node
child::para[xf:position() = 1] selects the first para child of the context node
child::para[xf:position() = xf:last()] selects the last para child of the context node
child::para[xf:position() = xf:last()-1] selects the last but one para child of the context node
child::para[xf:position() > 1] selects all the para children of the context node other than the first para child of the context node
/descendant::figure[xf:position() = 42] selects the forty-second figure element in the document
/child::doc/child::chapter[xf:position() = 5]/child::section[xf: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'][xf:position() = 5]selects the fifth para child of the context node that has a type attribute with value warning
child::para[xf: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][xf:position() = xf:last()] selects the
last chapter or appendix child of the context node
| [52] | AbbreviatedForwardStep | ::= | "." | ("@" NameTest) | NodeTest |
| [53] | AbbreviatedReverseStep | ::= | ".." |
The abbreviated syntax permits the following abbreviations:
The most important abbreviation is that child:: can be omitted from a step. In effect, child is the default axis. For example, a path expression section/para is short for child::section/child::para.
There is also an abbreviation for
attributes: attribute:: can be
abbreviated by @. For example, a path expression para[@type="warning"] is short
for child::para[attribute::type="warning"] and
so selects para children with a type attribute with value
equal to warning.
// is short
for /descendant-or-self::node()/. For example, //para is short for /descendant-or-self::node()/child::para and so will select any para element in the document (even a para element that is a document element will be selected
by //para since
the document element node is a child of the root node); div1//para is
short for div1/descendant-or-self::node()/child::para and so will select all para descendants of div1 children.
Note that the path expression //para[1] does not mean the same as the path
expression /descendant::para[1]. The latter selects the first descendant para element; the former
selects all descendant para elements that are the first para children of their parents.
A step consisting
of . returns the context item. This is particularly useful in conjunction with //. For example, the path
expression .//para returns all para descendant elements of the context node.
A step consisting
of .. is short
for parent::node(). For example, ../title is short for parent::node()/child::title and so will select the title children of the parent of the context node.
Here are some examples of path expressions that use the abbreviated syntax:
para selects the para element children of the context node
* selects all element children of the context node
text() selects all text node children of the context node
@name selects
the name attribute of the context node
@* selects all the attributes of the context node
para[1] selects the first para child of the context node
para[xf:last()] selects the last para child of the context node
*/para selects
all para grandchildren of the context node
/doc/chapter[5]/section[2] selects the second section of the fifth chapter of the doc
chapter//para selects the para element descendants of the chapter element children of the context node
//para selects all
the para descendants of the document root and thus selects all para elements in the same document as the context node
//list/member selects all the member elements in the same document as the context node that have an list parent
. selects the context node
.//para selects
the para element descendants of the context node
.. selects the parent of the context node
../@lang selects
the lang attribute of the parent of the context node
para[@type="warning"] selects all para children of the context node that have a type attribute with value warning
para[@type="warning"][5] selects the fifth para child of the context node that has a typeattribute with value warning
para[5][@type="warning"] selects the fifth para child of the context node if that child has a type attribute with value warning
chapter[title="Introduction"] selects the chapter children of the context node that have one
or more title children with string-value equal to Introduction
chapter[title] selects the chapter children of the context node that have one or more title children
employee[@secretary and @assistant] selects all
the employee children of the context node that have both a secretary attribute and
an assistant attribute
book/(chapter|appendix)/section selects
every section element that has a parent that is either a chapter or an appendix element, that in turn is a child of a book element that is a child of the context node.
book/xf:id(publisher)/name returns the same result as xf:id(book/publisher)/name.
XQuery supports operators to construct and combine sequences. A sequence is an ordered collection of zero or more items. An item may be an atomic value or a node. An item is identical to a sequence of length one 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).
| [4] | ExprSequence | ::= | Expr ("," Expr)* |