DISCLAIMER: This is not a W3C Working Draft, but a "diff" version made available to the public for convenience. The presentation of the original W3C Working Draft has been augmented to identify changes from its previous version. Three kinds of changes are highlighted: new, added text, changed text, and deleted text.
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(unordered and
elementidiv),
names ratherand
than on structural subsumption.(assert,
Theprecedes, sort
byfollows expression has been eliminated , and in=>). itsIt place a new
orderdeclarations by
clauseinto has been added to the FLWR
expression (and publicxmlspace feedback ondefault thiscollation. change is invited). Several
smalldescribes changes have been made to the grammar in order to eliminate the need for
reserved keywords. More detailed material
has beencast includedexpressions, on error handlingconstructors, and optimization. A complete list
of changesas can
be foundsummarized in H 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 XPathXQuery
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.9 FLWOR
Expressions
3.9.1 For and Let Clauses
3.9.2 Wherein Clause
3.9.3 Order ByExpressions and Return Clauses
3.9.4 Example
3.10 Unordered
Expressions
3.11 Conditional
Expressions
3.12 Quantified
Expressions
3.13 Expressions on SequenceTypes
3.13.1 Instance Of
3.13.2 Typeswitch
3.13.3 Cast and Treat
3.13.4 Castable
3.13.5 Constructor Functions
3.13.6 Treat
3.14 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
NamesWords
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
G XPath 2.0 and XQuery 1.0 Issues (Non-Normative)
H Revision Log (Non-Normative)
H.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),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:
| [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 arewill be 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.13.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], 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. 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, or 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 fn:position(). When an expression
E1/E2, or
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, or 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. 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 ofthree 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 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
documentdocument. 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 serializationTransformation of a Data Model instance in the form ofinto an XML document remainis currently 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 anchildren. 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.14
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: 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 Languages that are based on XPath 2.0 may handle type exceptions with either a strict or a flexible policy, as described in . as described in . XQuery has a strict type exception policy, which means that all type exceptions are treated as errors. Like XML Schema, 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 errorname. For example, named types may be detected andassociated with values reported during of the analysisfollowing ways: A literal value has a named type; for example, phase or during the evaluation value 47 is xs:integer.The phase, as described in 2.4.1 Type Checking 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 either 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 error is raised.
It is possible for static 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.
During the analysis phase,If it may be desirable
for an implementation to issue a warning if theby
static type assigned to an expression otherwill necessarily
than ()a is empty,error indicating that the expression can never return a
nonempty value. This can
catch cases in whichfrom a query references an element or
attributestring that is not present, possibly due to a misspelling or misunderstanding. We suggest a warning rather
than requiring anthis error because there are
some situations in which a correct
expressionduring may have the type empty.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.
| [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, whichElemOrAttrType,which places further
constraints on the node (see below).
attribute matches an attribute node. Optionally,
attribute may be followed by ElemOrAttrType, whichElemOrAttrType,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 equalthe same to the requirednamed nametype 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 and if the given element or attribute hasmust 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 beencity 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 aan optional atomic value sequence of atomic values is required.applied to a given The resultvalue, of atomization is either a sequencesingle atomic value, of atomic values or a type error. Atomization of a sequence is defined as follows:
If everythe value is a single atomic value or an item in the input sequence is eithervalue. an atomic value or a node single node, whose typed value of the node is a sequence of atomic values, thenif the resulttyped value is a sequence of atomization is theone item, concatenated sequence of these atomic values.raised.
Otherwise,In any other case, atomization raises a type error. exception.
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 invokingfollows: If the fn:booleansequence function on the
sequence, as defined in [XQuery 1.0
and XPath 2.0 Functions and Operators]false.
If The semantics
of fn:booleana are repeated here for
convenience. fn:boolean,
returns falsevalue if its operand is
any of the following:
AnIf the sequence contains at least one empty sequence.
Theits
effective boolean value is
false.
An empty string ("").
Acase, numeric value that is equal toIn zero.
TheXQuery, doublea
or floatexception value
NaN.
Otherwise,raises fn:booleana
returns true.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 fn:not function
The where clause of a FLWOR expression
Conditional expressions (if)
Quantified expressions (some, every)
Ed. Note: ThisThe action taken when a type sectionexception is raised depends on the still under review by the working group.
Certainexpression kindsis being of expressions
introduce named variables and bind them tostrict values. For example,flexible the following expression binds the variablepolicy is
$i, a type
exception is treated as a dynamic successively
to the valuespolicy is 1, 2,the language environment must handle type exceptions by
applying a fixed set of rules and
3,fallback andconversions. uses each of thesefallback conversions bindings to evaluateprovide backward
compatibility with the nested expression
$iXPath
* 2:
for $i in (1, 2, 3) return $i * 2
1.0.
In If
the required type is anything other than an atomic type or a single node, a
dynamic error is raised. If the required type is boolean, XQuery, the kindsgiven value is of expressionsempty
sequence, that can bind variables are FLWOR
expressions (3.9 FLWOR Expressions),false. If quantified expressions (3.12
Quantified Expressions),type and typeswitch, and the
given value is a sequence containing at least one node, the given value is
converted to expressions (3.13.2
Typeswitch).
true.
Expressions that bind variables can be nested, and an inner expression can containthe sequence references to variables bound in an outer expression. More formally, the rules for binding variablesa node, and forthe first item in the sequence referring to bound variables in XQuerydynamic are as follows:
TheOtherwise if the given value is a sequence containing more than one item, only the first item is retained. If this item is a node, its innermosttyped value expression that contains the defining occurrence of the node is a variablesequence of more than one atomic value, only the first of these atomic values is retained. The resulting (supplied or extracted) atomic name is calledconverted to the required type according to the rules in the containingfollowing table: boolean type string type number type other atomic type boolean value N/A Boolean false value is converted expressionto for that variable.false. The expressionboolean true value is that establishes the string true. Boolean true is converted to 1; boolean false is converted to 0. Dynamic error string value 'true' or '1' goes to true, 'false' or '0' goes to whichfalse. Otherwise, if a variable is boundempty, return false; otherwise, return is called N/A Use the bindingnumeric expressionconstructor for thatthe specific number type, passing in the string value. Use the appropriate string constructor for variable. Aspecific type variable is in scopethe document. number value 0, +0, -0, (and may thus be referenced) within anyfalse, anything subexpression of its containing expression, withtrue. Use the followingstring value of the exceptions:
Itsatomic binding expression
Anyas expression thatin the textually precedesmodel. N/A Attempt its binding expression
Variablesthe that share the samegiven atomic type, containingusing the expression must have different. names.
If twocasting fails, raise a dynamic error. other or morevalue Attempt variables with the samevalue to a boolean, using name aretables defined in scope. If casting fails, raise a dynamic error. Attempt to within the samevalue to a expression, any variable referencetables defined with that. name is interpreted as a referencedynamic error. Attempt to cast the variablevalue to a that has the smallesttables defined in . containing expression.
Thecasting name of a variable is a Attempt QName, and variable names match if their expanded-QNames are using the same--thattables defined in . If casting fails, raise a dynamic error. The entries in this is, if they have the samecasts in . If namespace and thedisagreement, same local name.
precedence.
This section has been approved by the XML Query Working Group but is still being discussed by the XSLT Working Group. Some changes in XPath syntax and/or semantics may result from these discussions.
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. are Typestatic type errors, reported by the analysis phasewhich occur when the static type of an expression is not correct for for the context in which it appears. The term Static errors arealso includes non-type-related errors such as syntax errors. The means by which static errors are reported during the analysis phase is implementation-defined.
The result of the evaluation phase is either a result value,value or a type error,. Some or aerrors are dynamic error. Typetype errors, are raised during the evaluation phase when the dynamic type of an expression is not correct for the context in which it appears. The term Dynamic errors are also includes non-type-related dynamic errors such as numeric overflow. If evaluation of an implementation expression yieldsreturns a value (that is, itvalue, does not raise an error), the value must be the value specified by to 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 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 during the analysiserrors. phase. If an expression contains one or more static errorserrors, including or 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 type errors during the analysiserrors, 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, which is
defined in .
| [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 offor expressions that can bind
variables are FLWOR expressions (3.9 FLWOR Expressions), and quantified
expressions (3.12 Quantified Expressions),, and typeswitchby
expressions (3.13.2 Typeswitch).calls, Function callswhich
also bind values to the formal parameters of
functions before executing the function body.body. XPath also
Variables can also be bound in the externalhost language
environment, outside the scope of a query.
environment.
| [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.