This document is governed by the
W3C publishes a
This document was developed by the W3C
This document will be
considered ready for transition to Proposed Recommendation
when there are two independent implementations of Minimal Conformance
(see
Once the entrance criteria for Proposed Recommendation have been achieved,
the Director will be requested to advance this document to
This Candidate Recommendation specifies XQuery
version 3.1, a fully compatible extension of
No implementation report currently exists.
However, a Test Suite for this document is under development.
Implementors are encouraged to run this test suite and report their results.
The Test Suite can be found at
This document incorporates changes made against the previous publication
of the Working Draft.
Changes to this document since the previous publication of the Working Draft
are detailed in
Please report errors in this document using W3C's
Publication as a Candidate Recommendation does not imply endorsement by the W3C Membership. This is a draft document and may be updated, replaced or obsoleted by other documents at any time. It is inappropriate to cite this document as other than work in progress.
This document was produced by a group operating under the
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.
XQuery 3.1 is an extended version of the XQuery 3.0
Recommendation published on 2014-04-08. A list of changes made
since XQuery 3.0 can be found in
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
XQuery Version 3.0 is an extension of XPath Version 3.0. In general, any expression that is
syntactically valid and executes successfully in both XPath 3.0 and XQuery 3.0 will return
the same result in both languages. There are a few exceptions to this rule: Because XQuery expands If XPath 1.0 compatibility mode is enabled, XPath behaves differently from
XQuery in a number of ways,
"&"
is &
in XQuery,
and &
in XPath. (XPath is often embedded in other
languages, which may expand predefined entity references or character references
before the XPath expression is evaluated.)
Because 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 3.1 also depends on and is closely related to the following specifications:
The type system of XQuery 3.1 is based on XML Schema. It is implementation-defined
whether the type system is based on
The built-in function library and the operators supported by XQuery 3.1 are defined
in
XQuery also has an XML-based syntax, which is described in
This document specifies a grammar for XQuery 3.1, using the same basic EBNF notation used in
In the grammar productions in this document, named symbols are underlined and literal text is enclosed in double quotes. For example, the following productions describe the syntax of a static function call:
The productions should be read as follows: A static function call consists of an
This document normatively defines the static and dynamic semantics of XQuery 3.1. In this document, examples and material labeled as "Note" are provided for explanatory purposes and are not normative.
Certain aspects of language processing are described in this specification as
The basic building block of XQuery 3.1 is the
This specification contains no
assumptions or requirements regarding the character set encoding of strings
of
Like XML, XQuery 3.1 is a case-sensitive language. Keywords in
XQuery 3.1 use lower-case characters and are not reserved—that is, names in XQuery 3.1 expressions are allowed to be the same as language keywords, except for certain unprefixed function-names listed in
xs:string
. The xs:QName
.
In the XQuery 3.1 grammar, most names are specified using the
Names in XQuery 3.1 can be bound to namespaces, and are
based on the syntax and semantics defined in
The xs:anyURI
type in http://www.w3.org/2000/xmlns/
.
Here are some examples of
pi
is a
math:pi
is a
Q{http://www.w3.org/2005/xpath-functions/math}pi
specifies the namespace URI using a
Certain namespace prefixes are predeclared by XQuery and bound to fixed namespace URIs. These namespace prefixes are as follows:
xml = http://www.w3.org/XML/1998/namespace
xs = http://www.w3.org/2001/XMLSchema
xsi = http://www.w3.org/2001/XMLSchema-instance
fn = http://www.w3.org/2005/xpath-functions
local = http://www.w3.org/2005/xquery-local-functions
(see
In addition to the prefixes in the above list, this document uses the prefix err
to represent the namespace URI http://www.w3.org/2005/xqt-errors
(see http://www.w3.org/2012/xquery
for which no prefix is used in this document, which is reserved for use in this specification. It is currently used for annotations and option declarations that are defined by the XML Query Working Group.
Element nodes have a property called
In
However, where other specifications such as $e
In most contexts, processors are not required to raise errors if a URI is not lexically valid according to
This information is organized into two categories
called the
The individual components of the
false
.
xs:anyURI
type in
Some namespaces are predefined; additional namespaces can be added to the statically known namespaces by
xs:anyURI
type in
xs:anyURI
type in
The static type of a variable may either be declared in a query or
inferred by static type inference as discussed in
The
xs:string
and xs:anyURI
(and types derived from them) when no
explicit collation is
specified.
preserve
, the type of a constructed element node is xs:anyType
, and all attribute and element nodes copied during node construction retain their original types. If construction mode is strip
, the type of a constructed element node is xs:untyped
; all element nodes copied during node construction receive the type xs:untyped
, and all attribute nodes copied during node construction receive the type xs:untypedAtomic
.
ordered
or unordered
, affects the ordering of the result sequence returned by certain expressions, as discussed in
NaN
values as ordering keys in an order by
clause in a FLWOR expression, as described in greatest
or least
.
preserve
or strip
.
preserve
or no-preserve
, and inherit
or no-inherit
.
fn:static-base-uri
function, and is used implicitly during dynamic
evaluation by functions such as fn:doc
. Relative URI references are
resolved as described in
If the value of the Static Base URI is based on the location of the
query module (in the terminology of import module
declarations as when retrieving source
documents using the fn:doc
function. If an implementation uses different
values for the Static Base URI during static analysis and during dynamic
evaluation, then it is implementation-defined which of the two values is
used for particular operations that rely on the Static Base URI; for
example, it is implementation-defined which value is used for resolving
collation URIs.
fn:doc
function. The type is the fn:doc
with the given URI as its
literal argument. fn:doc
is a
string literal that is not present in fn:doc
is document-node()?
.
The purpose of the fn:doc
.
fn:collection
function. The type is the type of the
sequence of nodes that would result from calling the
fn:collection
function with this URI as its
argument.fn:collection
is a string literal that is not present in
fn:collection
is node()*
.
The purpose of the fn:collection
.
fn:collection
function with no arguments.node()*
.
fn:format-number()
.
Each decimal format contains three sets of properties, which control the interpretation of characters
in the picture string supplied to the fn:format-number
function, and also specify characters that may appear in the result
of formatting the number.
The following attributes specify characters used to format the number per se:
The following attributes control the interpretation of characters in the picture string supplied to the format-number function. In each case the value must be a single character.
The following attributes specify characters or strings that may appear in the result of formatting the number:
The individual
components of the
The
Certain language constructs, notably the E1/E2
, the E1[E2]
, create a new focus
for the evaluation of a sub-expression. In these constructs, E2
is evaluated once for each item in the
sequence that results from evaluating E1
. Each time E2
is evaluated, it is evaluated with a
different focus. The focus for evaluating E2
is referred to below as the E1
is referred to as the E2
is being evaluated. When this evaluation
is complete, evaluation of the containing expression continues with
its original focus unchanged.
.
). When an expression E1/E2
or E1[E2]
is evaluated, each item in the
sequence obtained by evaluating E1
becomes the context item in the inner focus for an evaluation of E2
.
fn:position()
. When an expression E1/E2
or E1[E2]
is evaluated, the context position in
the inner focus for an evaluation of E2
is the position of the context item in the sequence obtained by
evaluating E1
. The position of the
first item in a sequence is always 1 (one). The context position is
always less than or equal to the context size.
fn:last()
. When an expression
E1/E2
or E1[E2]
is evaluated, the context size in the
inner focus for an evaluation of E2
is
the number of items in the sequence obtained by evaluating E1
.
fn:current-dateTime
function. If invoked multiple times during the execution of
xs:dayTimeDuration
. See
fn:format-date
and fn:format-integer
)
if no other language is requested.
The value is a language code as defined by the type xs:language
.
fn:format-date
and fn:format-dateTime
)
if no other calendar is requested.
The value is a string.
fn:format-date
and fn:format-dateTime
,
if no other place is specified. It is used when translating timezone offsets to civil timezone names,
and when using calendars where the translation from ISO dates/times to a local representation is dependent
on geographical location. Possible representations of this information are an ISO country code or an
Olson timezone name, but implementations are free to use other representations from which the above
information can be derived.
fn:doc
function when applied to that URI.
If there are one or more
URIs in D
, then the document-uri property of D
must either be absent, or must
be one of these URIs.
This means that given a document node $N
, the result of
fn:doc(fn:document-uri($N)) is $N
will always be true
, unless
fn:document-uri($N)
is an empty sequence.
fn:unparsed-text
function when applied to that
URI.
fn:collection
function when that URI is supplied as the
argument.
For every document node D
that is in the target of a mapping in D
must either be absent, or must be a
URI U
such that U
to D
.
This means that for any document node $N
retrieved using the
fn:collection
function, either directly or by navigating to the root of a
node that was returned, the result of fn:doc(fn:document-uri($N)) is $N
will always be true
, unless fn:document-uri($N)
is an empty sequence. This
implies a requirement for the fn:doc
and fn:collection
functions to be
consistent in their effect. If the implementation uses catalogs or
user-supplied URI resolvers to dereference URIs supplied to the fn:doc
function, the implementation of the fn:collection
function must take these
mechanisms into account. For example, an implementation might achieve this
by mapping the collection URI to a set of document URIs, which are then
resolved using the same catalog or URI resolver that is used by the fn:doc
function.
fn:collection
function
with no arguments.
fn:uri-collection
function when that URI is supplied as the
argument.
An implementation fn:uri-collection(X)!fn:doc(.)
is the same as the result of fn:collection(X)
.
However, this is not required. The fn:uri-collection
function is more
general than fn:collection
in that it allows access to resources other
than XML documents; at the same time, fn:collection
allows access to
nodes that might lack individual URIs, for example nodes corresponding
to XML fragments stored in the rows of a relational database.
fn:uri-collection
function
with no arguments.
A possible implementation is to provide the set of POSIX environment variables (or their equivalent on other
operating systems) appropriate to the process in which the
XQuery 3.1 is defined in terms
of the
Figure 1: Processing Model Overview
Figure 1 provides a schematic overview of the processing steps that
are discussed in detail below. Some of these steps are completely
outside the domain of XQuery 3.1; in Figure 1, these are depicted
outside the line that represents the boundaries of the language, an
area labeled
Before
A document may be parsed using an XML parser that
generates an
The Information Set or PSVI may be
transformed into an
The above steps provide an example of how an
type-name
of a node is the name of the type referenced by its
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 given the xs:untypedAtomic
.
The value of an element is represented by the children of the
element node, which may include text nodes and other element
nodes. The xs:untyped
. An element that has been validated and found to be partially valid is annotated with the schema type xs:anyType
. If an element node is annotated as xs:untyped
, all its descendant element nodes are also annotated as xs:untyped
. However, if an element node is annotated as xs:anyType
, some of its descendant element nodes may have a more specific
The
XQuery 3.1 defines two phases of processing called
the
Within each phase, an implementation is free to use any strategy or algorithm whose result conforms to the specifications in this document.
During the static analysis phase, the
The
During the
Examples of inferred static types might be:
For the expression concat(a,b)
the inferred static type is xs:string
For the expression $a = $v
the inferred static type is xs:boolean
For the expression $s[exp]
the inferred static
type has the same item type as the static type of $s
,
but a cardinality that allows the empty sequence even if the
static type of $s
does not allow an empty
sequence.
The inferred static type of the expression data($x)
(whether written
explicitly or inserted into the operation tree in places where atomization
is implicit) depends on the inferred static type of $x
: for example, if $x
has type element(*, xs:integer)
then data($x)
has static type xs:integer
.
In XQuery 1.0 and XPath 2.0, rules for static type inferencing were published
normatively in
Every kind of expression also imposes requirements on the type of its
operands. For example, with the expression substring($a, $b, $c)
, $a
must be
of type xs:string
(or something that can be converted to xs:string
by the
function calling rules), while $b
and $c
must be of type xs:double
.
If the Static Typing Feature is in effect, a processor must raise a
type error during static analysis if the inferred static type of an
expression is not subsumed by the required type of the context where the
expression is used. For example, the call of substring above would cause a
type error if the inferred static type of $a
is xs:integer
; equally, a type
error would be reported during static analysis if the inferred static type
is xs:anyAtomicType
.
If the Static Typing Feature is not in effect, a processor may raise a type
error during static analysis only if the inferred static type of an
expression has no overlap (intersection) with the required type: so for the
first argument of substring, the processor may raise an error if the
inferred type is xs:integer
, but not if it is xs:anyAtomicType
.
Alternatively, if the Static Typing Feature is not in effect, the processor
may defer all type checking until the dynamic evaluation phase.
The dynamic evaluation phase can occur only if no errors were detected during the
The dynamic evaluation phase depends on the
xs:integer*
, denoting a sequence of zero or more integers, but at evaluation time its value may have the dynamic type xs:integer
, denoting exactly one integer.)
If an operand of an expression is found
to have a
Even though static typing can catch many xs:untypedAtomic
. This is not a
When the
This definition of serialization is the definition
used in this specification. Any form of serialization that is
not based on
An XQuery implementation is not required to provide a
serialization interface. For example, an implementation may
provide only a DOM interface (see
parameter-document
, each option corresponds to a serialization parameter element defined in use-character-maps
, it can be set only by means of a parameter document.
When the application requests serialization of the output, the
processor may use these parameters to control the way in which the
serialization takes place. Processors may also allow external
mechanisms for specifying serialization parameters, which may or may
not override serialization parameters specified in the query prolog.
The following example illustrates the use of declaration options.
An http://www.w3.org/2010/xslt-xquery-serialization
namespace is not one of the
serialization parameter names listed in parameter-document
,
or if the name of an output declaration is use-character-maps
.
The default value for the method
parameter is "xml"
. An
implementation may define additional
If the local name of an output declaration in the
http://www.w3.org/2010/xslt-xquery-serialization
namespace is
parameter-document
, the value of the output declaration is treated as a
URI literal. The value is a location hint, and identifies an XDM instance
in an implementation-defined way. If a processor is performing
serialization, it is a static error output:parameter-document
declaration to produce an XDM instance.
If a processor is performing serialization, the XDM instance identified by
an output:parameter-document
output declaration specifies the values of
serialization parameters in the manner defined by
http://www.w3.org/2010/xslt-xquery-serialization
namespace with the local name
parameter-document declaration.
A serialization parameter that is not applicable to the chosen output method must be ignored, except that if its value is not a valid value for that parameter, an error may be raised.
A processor that is performing serialization must raise a serialization error if the values of any serialization parameters that it supports (other than any that are ignored under the previous paragraph) are incorrect.
A processor that is not performing serialization may report errors if any serialization parameters are incorrect, or may ignore such parameters.
Specifying serialization parameters in a query does not by itself demand that the output be serialized. It merely defines the desired form of the serialized output for use in situations where the processor has been asked to perform serialization.
The
In order for XQuery 3.1 to
be well defined, the input
For every node that has a type annotation, if that type annotation is found in the
Every element name, attribute name, or schema type name referenced in
Any reference to a global element, attribute, or type name in
the
For each mapping of a string to a
document node in
For each mapping of a string to a sequence of nodes in
The sequence of nodes in the
The value of the
For each (variable, type) pair in
For each variable declared as external, if the variable declaration does
not include a
For each variable declared as external for which the external environment
provides a value: If the variable declaration includes a declared type,
the value provided by the external environment must match the
declared type, using the matching rules in
For each function declared as external: the function's
For a given query, define a
In the xml
must not be bound to any namespace URI other than http://www.w3.org/XML/1998/namespace
, and no prefix other than xml
may be bound to this namespace URI.
The prefix xmlns
must not be bound to any namespace URI, and no prefix may be bound to the namespace URI http://www.w3.org/2000/xmlns/
.
For each
(expanded QName, arity) -> FunctionTest
entry in
(expanded QName, arity) -> function
entry in
FunctionTest
.
As described in
The outcome of the
If more than one error is present, or if an error condition comes within the scope of more than one error defined in this specification, then any non-empty subset of these errors may be reported.
During the ()
or data(())
is empty-sequence()
, a
Independently of whether the
An implementation can raise a
The following example contains a type error, which can be reported statically even if the implementation can not prove that the expression will actually be evaluated.
In addition to the errors defined in this
specification, an implementation may raise a Any limits on primitives defined by the XML and XSD specifications that differ from what these specifications state are
The errors defined in this specification are identified by QNames that have the form err:XXYYnnnn
, where:
err
denotes the namespace for XPath and XQuery errors, http://www.w3.org/2005/xqt-errors
. This binding of the namespace prefix err
is used for convenience in this document, and is not normative.
XX
denotes the language in which the error is defined, using the following encoding:
XP
denotes an error defined by XPath. Such an error may also occur XQuery since XQuery includes XPath as a subset.
XQ
denotes an error defined by XQuery (or an error originally defined by XQuery and later added to XPath).
YY
denotes the error category, using the following encoding:
ST
denotes a static error.
DY
denotes a dynamic error.
TY
denotes a type error.
nnnn
is a unique numeric code.
The namespace URI for XPath and XQuery errors is not expected to
change from one version of
The method by which an XQuery 3.1 processor reports error information to the external environment is
An error can be represented by a URI reference that is derived from the error QName as follows: an error with namespace URI NS
LP
NS
#
LP
err:XPST0017
could be represented as http://www.w3.org/2005/xqt-errors#XPST0017
.
Along with a code identifying an error, implementations may wish to return additional information, such
as the location of the error or the processing phase in which it was detected. If an implementation chooses to do so, then the mechanism that
it uses to return this information is
Except as noted in this document, if any operand of an expression
raises a 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 raises an error, the implementation may choose which error is raised by the expression. For example, in this expression:
both the sub-expressions ($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 may be raised by a div
operator raises an error if its operands are xs:decimal
values and its second operand
is equal to zero. Errors raised by built-in functions and operators are defined in
A dynamic error can also be raised explicitly by calling the
fn:error
function, which always raises a dynamic error and never
returns a value. This function is defined in app
is bound to a namespace containing application-defined error codes):
Because different implementations may
choose to evaluate or optimize an expression in different ways,
certain aspects of raising
An implementation is always free to evaluate the operands of an operator in any order.
In some cases, a processor can determine the result of an expression without accessing all the data that would be implied by the formal expression semantics. For example, the formal description of $s[1]
should be evaluated by examining all the items in sequence $s
, and selecting all those that satisfy the predicate position()=1
. In practice, many implementations will recognize that they can evaluate this expression by taking the first item in the sequence and then exiting. If $s
is defined by an expression such as //book[author eq 'Berners-Lee']
, then this strategy may avoid a complete scan of a large document and may therefore greatly improve performance. However, a consequence of this strategy is that a dynamic error or type error that would be detected if the expression semantics were followed literally might not be detected at all if the evaluation exits early. In this example, such an error might occur if there is a book
element in the input data with more than one author
subelement.
The extent to which a processor may optimize its access to data, at the cost of not raising errors, is defined by the following rules.
Consider an expression
There is an exception to this rule: If a processor evaluates an operand $e eq 0
results in a type error if the value of $e
contains two or more items. A processor is not allowed to decide, after evaluating the first item in the value of $e
and finding it equal to zero, that the only possible outcomes are the value true
or a type error caused by the cardinality violation. It must establish that the value of $e
contains no more than one item.
These rules apply to all the operands of an expression considered in combination: thus if an expression has two operands
The rules cascade: if
The effect of these rules is that the processor is free to stop examining further items in a sequence as soon as it can establish that further items would not affect the result except possibly by causing an error. For example, the processor may return true
as the result of the expression S1 = S2
as soon as it finds a pair of equal values from the two sequences.
Another consequence of these rules is that where none of the items in a sequence contributes to the result of an expression, the processor is not obliged to evaluate any part of the sequence. Again, however, the processor cannot dispense with a required cardinality check: if an empty sequence is not permitted in the relevant context, then the processor must ensure that the operand is not an empty sequence.
Examples:
If an implementation can find (for example, by using an index) that at
least one item returned by $expr1
in the following example has the value 47
, it is allowed to
return true
as the result of the some
expression, without searching for
another item returned by $expr1
that would raise an error if it were evaluated.
In the following example, if an implementation can find (for example, by using an index) the
product
element-nodes that have an id
child with the value 47
, it is allowed to return these nodes as the
result of the product
node that
would raise an error because it has an id
child whose value is not an integer.
For a variety of reasons, including optimization, implementations may rewrite expressions into a different form. There are a number of rules that limit the extent of this freedom:
Other than the raising or not raising of errors, the result of evaluating a rewritten expression must conform to the semantics defined in this specification for the original expression.
This allows an implementation to return a result in cases where the original expression would have raised an error, or to raise an error in cases where the original expression would have returned a result. The main cases where this is likely to arise in practice are (a) where a rewrite changes the order of evaluation, such that a subexpression causing an error is evaluated when the expression is written one way and is not evaluated when the expression is written a different way, and (b) where intermediate results of the evaluation cause overflow or other out-of-range conditions.
This rule does not mean that the result of the expression will always
be the same in non-error cases as if it had not been rewritten, because there
are many cases where the result of an expression is to some degree
Conditional and typeswitch expressions
must not raise a dynamic error in
respect of subexpressions occurring in a branch that is not selected,
and must not
return the value delivered by a branch unless that branch is selected.
Thus, the following example must not raise a
dynamic error if the document abc.xml
does not exist:
As stated earlier, an expression
must not be rewritten to dispense with a
required cardinality check: for example, string-length(//title)
must raise an
error if the document contains more than one title element.
Expressions must not be rewritten in such a way as to create or remove static errors. The static errors in this specification are defined for the original expression, and must be preserved if the expression is rewritten.
Expression rewrite is illustrated by the following examples.
Consider the expression Parts that have exactly one color that is Red are returned. If some part has color Red together with some other color, an error is
raised. The existence of some part that has no color Red but has multiple non-Red
colors does not trigger an error.//part[color eq "Red"]
. An implementation might
choose to rewrite this expression as //part[color = "Red"][color eq
"Red"]
. The implementation might then process the expression as follows:
First process the "=
" predicate by probing an index on parts by color to
quickly find all the parts that have a Red color; then process the "eq
"
predicate by checking each of these parts to make sure it has only a
single color. The result would be as follows:
The expression in the following example cannot raise a casting error if it is evaluated exactly as written (i.e., left to right). Since neither predicate depends on the context position, an implementation might choose to reorder the predicates to achieve better performance (for example, by taking advantage of an index). This reordering could cause the expression to raise an error.
To avoid unexpected errors caused by expression rewrite,
tests that are designed to prevent dynamic errors should be expressed
using conditional typeswitch
This section explains some concepts that are important to the processing of XQuery 3.1 expressions.
An ordering called
Within a tree, document order satisfies the following constraints:
The root node is the first node.
Every node occurs before all of its children and descendants.
Attribute nodes immediately follow the element node with which they are associated. The relative order of
attribute nodes is stable but
The relative order of siblings is the order in which they occur
in the children
property of their parent node.
Children and descendants occur before following siblings.
The relative order of nodes in distinct trees is stable but
The semantics of some
XQuery 3.1 operators depend on a process called fn:data
function
on the sequence, as defined in
The semantics of
fn:data
are repeated here for convenience. The result of
fn:data
is the sequence of atomic values produced by
applying the following rules to each item in the input
sequence:
If the item is an atomic value, it is returned.
If the item is a node,
its
If the item is a
If the item is an array $a
, atomization is defined as seq($a) ! fn:data(.)
$a?* ! fn:data(.)
, which is equivalent to atomizing the members of the array.
This definition recursively atomizes members that are arrays. Hence, the result of atomizing the array [ [1, 2, 3], [4, 5, 6] ]
is the sequence (1, 2, 3, 4, 5, 6)
.
Atomization is used in processing the following types of expressions:
Arithmetic expressions
Comparison expressions
Function calls and returns
Cast expressions
Constructor expressions for various kinds of nodes
order by
clauses in FLWOR expressions
group by
clauses in FLWOR expressions
Switch expressions
Under certain circumstances (listed below), it is necessary to find
the fn:boolean
function to the value, as
defined in
The dynamic semantics of fn:boolean
are repeated here for convenience:
If its operand is an empty sequence, fn:boolean
returns false
.
If its operand is a sequence whose first item is a node, fn:boolean
returns true
.
If its operand is a xs:boolean
or derived from xs:boolean
, fn:boolean
returns the value of its operand unchanged.
If its operand is a xs:string
, xs:anyURI
, xs:untypedAtomic
, or a type derived from one of these, fn:boolean
returns false
if the operand value has zero length; otherwise it returns true
.
If its operand is a fn:boolean
returns false
if the operand value is NaN
or is numerically equal to zero; otherwise it returns true
.
In all other cases, fn:boolean
raises a type error [err:FORG0006].
For instance, fn:boolean
raises a type error if the operand is a function, a map, or an array.
The unordered
.
The
Logical expressions (and
, or
)
The fn:not
function
The where
clause of a FLWOR expression
Certain types of a[b]
Conditional expressions (if
)
Quantified expressions (some
, every
)
window
clauses.
The definition of xs:boolean
, for example in a cast
expression or when passing a value to a function whose expected
parameter is of type xs:boolean
.
XQuery 3.1 has a set of functions that provide access to
input data. These functions are of particular importance because they provide a way in which an expression can reference a document or a collection of documents. The input functions are described informally here; they are defined in
An expression can access input data either by calling one
of the input functions or by referencing some part of the
The input functions supported by XQuery 3.1 are as follows:
The fn:doc
function takes a string containing a URI. If that URI is associated with a document in fn:doc
returns a document node whose content is the
The fn:unparsed-text
function takes a string containing a URI, which must identify a resource that can be read as text; otherwise it raises a
The fn:environment-variable
and fn:available-environment-variables
identify environment variables that are available in the dynamic context.
The fn:collection
function with one argument takes a string containing a URI.
If that URI is associated with a collection in fn:collection
returns the data model representation of that collection; otherwise it raises a 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:collection
function with zero arguments returns the
The fn:uri-collection
function returns a sequence of xs:anyURI
values representing the URIs in a resource collection.
The fn:uri-collection
function with zero arguments returns the URIs in the
These input functions are all specified in
XQuery 3.1 requires a statically known, valid URI in
As in a string literal, any &
), •
), or ""
)
is replaced by its appropriate expansion. Certain characters,
notably the ampersand, can only be represented using a
The xs:anyURI
type is designed to anticipate the introduction of
Internationalized Resource Identifiers (IRI's) as defined in
Whitespace is normalized using the whitespace normalization rules
of fn:normalize-space
. If the result of whitespace
normalization contains only whitespace, the corresponding URI
consists of the empty string. 

does
not prevent its being normalized to a space
character.
A Braced URI Literal or URI Literal is not
subjected to percent-encoding
or decoding as defined in
$rel
against a
base URI $base
is to expand it to an absolute URI,
as if by calling the function fn:resolve-uri($rel,
$base)
.
Any process that attempts to
The type system of XQuery 3.1 is based on
xs:NOTATION
or xs:anyAtomicType
, in which case its derived
types can be so used). Every schema type is either a
{variety}
is union
, (2) the {facets}
property is empty, (3) no type in the transitive membership of the union type has {variety}
list
, and (4) no type in the transitive membership of the union type is a type with {variety}
union
having a non-empty {facets}
property
The definition of
The current (second) edition of XML Schema 1.0 contains an error in respect of the substitutability of a union type by one of its members: it fails to recognize that this is unsafe if the union is derived by restriction from another union.
This problem is fixed in XSD 1.1, but the effect of the resolution is that an atomic value labeled with an atomic type cannot be treated as being substitutable for a union type without explicit validation. This specification therefore allows union types to be used as item types only if they are defined directly as the union of a number of atomic types.
xs:integer
or my:hatsize
, is both a
The schema types defined in
The http://www.w3.org/2001/XMLSchema
,
which has the predefined namespace prefix
xs
. The schema types in this namespace are defined in xs
namespace are
not implicitly included in the static context. The schema types defined in
xs:untyped
is used as the skip
mode.xs:untyped
.
xs:untypedAtomic
is an atomic type that is used to denote untyped atomic data, such as text that has not been assigned a more specific type.skip
mode is represented in the xs:untypedAtomic
. No predefined schema types are derived from xs:untypedAtomic
.
xs:dayTimeDuration
is derived by restriction from xs:duration
. The lexical representation of xs:dayTimeDuration
is restricted to contain only day, hour, minute, and second
components.
xs:yearMonthDuration
is derived by restriction from xs:duration
. The lexical representation of xs:yearMonthDuration
is
restricted to contain only year and month
components.
xs:anyAtomicType
is an atomic type that includes all atomic values (and no values that
are not atomic). Its base type is
xs:anySimpleType
from which all simple types, including atomic,
list, and union types, are derived. All primitive atomic types, such as
xs:decimal
and xs:string
, have xs:anyAtomicType
as their base type.
xs:anyAtomicType
will not appear as the type of an actual value in an
xs:error
is a simple type with no value space, defined in
The relationships among the schema types in the xs
namespace are illustrated in Figure 2. A more complete description of the XQuery 3.1 type hierarchy can be found in
Figure 2: Hierarchy of Schema Types used in XQuery 3.1.
xs:QName
, xs:NOTATION
, types
derived by restriction from xs:QName
or
xs:NOTATION
, list types that have a namespace-sensitive
item type, and union types with a namespace-sensitive type in their
transitive membership.
It is not possible to preserve the type of a [err:FONS0004]
if the namespace bindings for the result cannot be determined.
Every node has a fn:data
function to
the node.fn:string
function to the node.fn:data
and fn:string
can be found in
An implementation may store both the xs:integer
value 30
, its string value might be "30
" or "0030
".
The
If the node was created by mapping from an Infoset or PSVI, see rules in
If the node was created by an XQuery node constructor, see rules in
If the node was created by a validate
expression, see rules in
As a convenience to the reader, the relationship between
For text and document nodes, the typed value of the node is the same as its
string value, as an instance of the type xs:untypedAtomic
. The
string value of a document node is formed by concatenating the string
values of all its descendant text nodes, in
The typed value of a comment or processing instruction node is the same as its string value. It is an instance of the type xs:string
.
The typed value of an attribute node with
the xs:anySimpleType
or xs:untypedAtomic
is the same as its
string value, as an instance of xs:untypedAtomic
. The
typed value of an attribute node with any other type annotation is
derived from its string value and type annotation using the lexical-to-value-space mapping defined in
Example: A1 is an attribute
having string value "3.14E-2"
and type annotation
xs:double
. The typed value of A1 is the
xs:double
value whose lexical representation is
3.14E-2
.
Example: A2 is an attribute with type
annotation xs:IDREFS
, which is a list datatype whose item type is the atomic datatype xs: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 xs:IDREF
. The typed
value of a node is never treated as an instance of a named list
type. Instead, if the type annotation of a node is a list type (such
as xs:IDREFS
), its typed value is treated as a sequence
of the xs:IDREF
).
For an element node, the
relationship between typed value and string value depends on the
node's
If the type annotation is xs:untyped
or xs:anySimpleType
or
denotes a complex type with mixed content (including xs:anyType
), then the typed value of the
node is equal to its string value, as an instance of
xs:untypedAtomic
. However, if the nilled
property of the node is true
, then its typed value is the empty sequence.
Example: E1 is an element node
having type annotation xs:untyped
and string value
"1999-05-31
". The typed value of E1 is
"1999-05-31
", as an instance of
xs:untypedAtomic
.
Example: E2 is an element node
with the type annotation formula
, which is a complex type
with mixed content. The content of E2 consists of the character
"H
", a child element named subscript
with
string value "2
", and the character "O
". The
typed value of E2 is "H2O
" as an instance of
xs:untypedAtomic
.
If the type
annotation denotes a simple type or a complex type with simple
content, then the typed value of the node is derived from its string
value and its type annotation in a way that is consistent with schema
validation. However, if the nilled
property of the node is true
, then its typed value is the empty sequence.
Example: E3 is an element node with the type
annotation cost
, which is a complex type that has several
attributes and a simple content type of xs:decimal
. The
string value of E3 is "74.95
". The typed value of E3 is
74.95
, as an instance of
xs:decimal
.
Example: E4 is an element node with the
type annotation hatsizelist
, which is a simple type
derived from the atomic type hatsize
, which in turn is
derived from xs:integer
. The string value of E4 is
"7 8 9
". The typed value of E4 is a sequence of three
values (7
, 8
, 9
), each of type
hatsize
.
Example: E5 is an element node with the type annotation my:integer-or-string
which is a union type with member types xs:integer
and xs:string
. The string value of E5 is "47
". The typed value of E5 is 47
as an xs:integer
, since xs:integer
is the member type that validated the content of E5. In general, when the type annotation of a node is a union type, the typed value of the node will be an instance of one of the member types of the union.
If an implementation stores only the string value of a node, and the type annotation of the node is a union type, the implementation must be able to deliver the typed value of the node as an instance of the appropriate member type.
If the type annotation denotes a complex type with empty content, then the typed value of the node is the empty sequence and its string value is the zero-length string.
If the type annotation
denotes a complex type with element-only content, then the typed value
of the node is fn:data
function raises a
[err:FOTY0012]
when applied to such a node. The string value of such a node is equal to the concatenated string values of all its text node descendants, in document order.
Example: E6 is an
element node with the type annotation weather
, which is a
complex type whose content type specifies
element-only
. E6 has two child elements named
temperature
and precipitation
. The typed
value of E6 is fn:data
function
applied to E6 raises an error.
Whenever it is necessary to refer to a type in an XQuery 3.1 expression, the
With the exception of the special type
empty-sequence()
, a item()
,
which permits any kind of item, item types divide into element()
), xs:integer
) and function types
(such as function() as item()*).
eq
operator.
Item types representing element
and attribute nodes may specify the required element(*, us:address)
denotes any element node whose type annotation is (or is derived from)
the schema type named us:address
.
The occurrence indicators '+', '*', and '?' bind to the last
Here are some examples of
xs:date
refers to the built-in atomic schema type named xs:date
attribute()?
refers to an optional attribute node
element()
refers to any element node
element(po:shipto, po:address)
refers to an element node that has the name po:shipto
and has the type annotation po:address
(or a schema type derived from po:address
)
element(*, po:address)
refers to an element node of any name that has the type annotation po:address
(or a type derived from po:address
)
element(customer)
refers to an element node named customer
with any type annotation
schema-element(customer)
refers to an element node whose name is customer
(or is in the substitution group headed by customer
) and whose type annotation matches the schema type declared for a customer
element in the
node()*
refers to a sequence of zero or more nodes of any kind
item()+
refers to a sequence of one or more
function(*)
refers to any
function(node()) as xs:string*
refers to a
(function(node()) as xs:string)*
refers to a sequence of zero or more
instance of
expression returns true
if the false
if it does not.
An XQuery 3.1 implementation must be able to determine relationships among the types in type annotations in an
xs:integer
value is used where an
xs:decimal
value is expected, the value retains its type
as xs:integer
.
The definition of derives-from(
)
, which takes an actual simple or complex
schema type
derives-from(
)
raises a type error
There is a type derives-from(
)
returns true
if any of the following conditions applies:
derives-from(
)
and derives-from(
)
Otherwise, derives-from(
)
returns false
The rules for
The empty-sequence()
matches a value that is the empty sequence.
An
An
An
?
matches zero or one items
*
matches zero or more items
+
matches one or more items
As a consequence of these rules, any *
or ?
matches a
value that is an empty sequence.
An derives-from(
)
is true
.
The name of an
Example: The xs:decimal
matches any value of type
xs:decimal
. It also matches any value of type
shoesize
, if shoesize
is an atomic type
derived by restriction from xs:decimal
.
Example: Suppose dress-size
is a union type that allows
either xs:decimal
values for numeric sizes (e.g. 4, 6, 10, 12),
or one of an enumerated set of xs:strings
(e.g. "small", "medium", "large"). The dress-size
matches any of these values.
The names of non-atomic
types such as xs:IDREFS
are not accepted in this context,
but can often be replaced by a xs:IDREF+
.
item()
matches
any single
Example: item()
matches the atomic
value 1
, the element <a/>
, or the function fn:concat#3
.
node()
matches any node.
text()
matches any
text node.
processing-instruction()
matches any processing-instruction
node.
processing-instruction(
)
matches any processing-instruction node whose PITarget is equal to fn:normalize-space(N)
. If fn:normalize-space(N)
is not in the lexical space of NCName, a type error is raised
Example:
processing-instruction(xml-stylesheet)
matches any
processing instruction whose PITarget is
xml-stylesheet
.
For backward compatibility with
XPath 1.0, the PITarget of a
processing instruction may also be expressed as a
string literal, as in this example:
processing-instruction("xml-stylesheet")
.
If the specified PITarget is not a syntactically valid NCName, a type error is raised
comment()
matches any comment node.
namespace-node()
matches any
namespace node.
document-node()
matches any document
node.
document-node(
)
matches any document node that contains exactly one element node, optionally accompanied by one or more comment and processing instruction nodes, if
Example:
document-node(element(book))
matches a document node
containing
exactly one element node that is matched by the ElementTest
element(book)
.
A
An
The ItemType
map(K, V)
matches an item M if (a) M is a
K
and an associated value that matches V
. For example,
map(xs:integer, element(employee))
matches a map if all the keys in the map are integers, and all the associated
values are employee
elements. Note that a map (like a sequence) carries no intrinsic type information separate
from the types of its entries, and the type of existing entries in a map does not constrain the type of new entries that can be
added to the map.
In consequence, map(K, V)
matches an empty map,
whatever the types K and V might be.
The ItemType
map(*)
matches
any map regardless of its contents. It is equivalent to map(xs:anyAtomicType, item()*)
.
The ItemType
array(T)
matches any array in which the type of every entry is T
.
The ItemType
array(*)
matches any array regardless of its contents.
An
The
An
element()
and
element(*)
match any
single element node, regardless of its name or
type annotation.
element(
)
matches any element node whose name is nilled
property.
Example: element(person)
matches any element node whose name is person
.
element(
,
)
matches an element node whose name is derives-from(
)
is true
, where nilled
property of the node is false
.
Example: element(person, surgeon)
matches a
non-nilled element node whose name is person
and whose
type annotation is surgeon
(or is derived from surgeon
).
element(
?)
matches an element node whose name is derives-from(
)
is true
, where nilled
property of the node may be either true
or false
.
Example: element(person, surgeon?)
matches a nilled or non-nilled element node whose name is person
and whose type
annotation is surgeon
(or is derived from surgeon
).
element(*,
)
matches an element
node regardless of its name, if
derives-from(
)
is
true
, where nilled
property of the node is false
.
Example: element(*, surgeon)
matches any non-nilled element node whose type annotation is
surgeon
(or is derived from surgeon
), regardless of its name.
element(*,
?)
matches an element
node regardless of its name, if
derives-from(
)
is
true
, where nilled
property of the node may be either true
or false
.
Example: element(*, surgeon?)
matches any nilled or non-nilled element node whose type annotation is
surgeon
(or is derived from surgeon
), regardless of its name.
A
The
A
Either:
The name
The name
The term "actual substitution group" is defined in
The schema element declaration named
derives-from( AT, ET )
is true, where
If the schema element declaration named
Example: The customer is a top-level element declaration in the in-scope element declarations; the name of the candidate node is customer; the element declaration of customer is not abstract; the type annotation of the candidate node is the same as or derived from the schema type declared in the customer element declaration; and either the candidate node is not nilled, or customer is declared to be nillable. customer is a top-level element declaration in the in-scope element declarations; the name of the candidate node is client; client is an actual (non-abstract and non-blocked) member of the substitution group of customer; the type annotation of the candidate node is the same as or derived from the schema type declared for the client element; and either the candidate node is not nilled, or client is declared to be nillable.schema-element(customer)
matches a candidate element node
in the following two situations:
An
The
An
attribute()
and attribute(*)
match any single attribute node,
regardless of its name or type annotation.
attribute(
)
matches any attribute node whose name is
Example: attribute(price)
matches any attribute node whose name is price
.
attribute(
)
matches an attribute node whose name is derives-from(
)
is true
, where
Example: attribute(price, currency)
matches an
attribute node whose name is price
and whose type
annotation is
currency
(or is derived from currency
).
attribute(*,
)
matches an attribute
node regardless of its name, if
derives-from(
)
is
true
, where
Example:
attribute(*, currency)
matches any attribute node whose
type annotation is currency
(or is derived from currency
), regardless of its
name.
A
The
A
The name of the candidate node matches the specified
derives-from(
)
is true
, where
Example: The schema-attribute(color)
matches a candidate attribute node if color
is a top-level attribute declaration in the color
, and the type annotation of the candidate node is the same as or derived from the schema type declared for the color
attribute.
A
Here are some examples of
function(*)
matches any
%assertion function(*)
matches any %assertion
is satisfied.
function(int, int) as int
matches any function(int, int) as int
.
%assertion function(int, int) as int
matches any function(int, int) as int
if the implementation-defined function assertion %assertion
is satisfied.
function(*)
matches any
function(xs:anyAtomicType) as item()*
matches any map.
function(xs:integer) as item()*
matches any array.
Implementations are free to define their own function assertions, whose behavior is completely implementation-defined. Implementations may also provide a way for users to create their own function assertions.
An implementation may raise implementation-defined errors or warnings for function assertions, e.g. if the parameters are not correct for a given assertion. If a function assertion is not recognized by an implementation, it is ignored, and has no effect on the semantics of the function test.
An implementation is free to raise warnings for function assertions that it does not recognize.
Although function assertions use the same syntax as
annotations, they are not directly related to annotations. If an
implementation defines the annotation blue
and uses it in
function declarations, there is no guarantee that it will also
define a function assertion blue
, or that a function
assertion named blue
matches a function declared with
the annotation blue
. Of course, an implementation
that does so may be more intuitive to users.
Implementations must not define function assertions in the
following reserved namespaces; it is an error for users to create
function assertions in the following reserved namespaces
http://www.w3.org/XML/1998/namespace
http://www.w3.org/2001/XMLSchema
http://www.w3.org/2001/XMLSchema-instance
http://www.w3.org/2005/xpath-functions
http://www.w3.org/2005/xpath-functions/math
http://www.w3.org/2012/xquery
The Map Test map(*)
matches any map. The Map Test
map(X, Y)
matches any map where the type of every key
is an instance of X
and the type of every value is an
instance of Y
.
Examples:
Given a map $M
whose keys are integers and whose
results are strings, such as map{0:"no", 1:"yes"}
,
consider the results of the following expressions:
$M instance of map(*)
returns true()
$M instance of map(xs:integer, xs:string)
returns true()
$M instance of map(xs:decimal, xs:anyAtomicType)
returns true()
not($M instance of map(xs:int, xs:string))
returns true()
not($M instance of map(xs:integer, xs:token))
returns true()
Because of the rules for subtyping of function types according to their signature, it follows that the item type
function(A) as item()*
, where A is an atomic type, also matches any map, regardless of the type of the keys actually
found in the map. For example, a map whose keys are all strings can be supplied where the required type is
function(xs:integer) as item()*
; a call on the map that treats it as a function with an integer argument will always succeed,
and will always return an empty sequence.
The function signature of the map, treated as a function, is always function(xs:anyAtomicType) as item()*
,
regardless of the actual types of the keys and values in the map. This means that a function item type with a more specific return type,
such as function(xs:anyAtomicType) as xs:integer
, does not match a map in the sense required to satisfy the instance of
operator. However, the rules for function coercion mean that any map can be supplied as a value in a context where such a type is the required
type, and a type error will only occur if an actual call on the map (treated as a function) returns a value that is not an instance of the
required return type.
Examples:
$M instance of function(*)
returns true()
$M instance of function(xs:anyAtomicType) as item()*
returns true()
$M instance of function(xs:integer) as item()*
returns true()
$M instance of function(xs:int) as item()*
returns true()
$M instance of function(xs:string) as item()*
returns true()
not($M instance of function(xs:integer) as xs:string)
returns true()
The last case might seem surprising; however, function coercion ensures that $M
can be used successfully
anywhere that the required type is function(xs:integer) as xs:string
.
The Wildcard Array Test array(*)
matches any
array. The Typed Array Test array(X)
matches any array
X
.
Examples:
[ 1, 2 ] instance array(*)
returns true()
[] instance of array(xs:string)
returns true()
[ "foo" ] instance of array(xs:string)
returns true()
[ "foo" ] instance of array(xs:integer)
returns false()
An array also matches certain other ItemTypes, including:
item()
function(*)
function(xs:integer) as item()*
Given two A
is a B
if the judgement subtype(A, B)
is true.subtype(A, B)
is true, it is always the case that for any value V
, (V instance of A)
implies (V instance of B)
.
subtype(A, B)
The judgement subtype(A, B)
determines if the A
is a B
.
A
can either be empty-sequence()
, xs:error
, or an Ai
, possibly followed by an occurrence indicator. Similarly
B
can either be empty-sequence()
, xs:error
, or an Bi
, possibly followed by an occurrence indicator.
The result of the subtype(A, B)
judgement can be determined from the table below, which makes use of the auxiliary judgement subtype-itemtype(Ai, Bi)
defined
in
B
| |||||||
---|---|---|---|---|---|---|---|
empty-sequence()
|
Bi?
|
Bi*
|
Bi
|
Bi+
| xs:error | ||
A
|
empty-sequence()
| true | true | true | false | false | false |
Ai?
| false |
subtype-itemtype(Ai, Bi)
|
subtype-itemtype(Ai, Bi)
| false | false | false | |
Ai*
| false | false |
subtype-itemtype(Ai, Bi)
| false | false | false | |
Ai
| false |
subtype-itemtype(Ai, Bi)
|
subtype-itemtype(Ai, Bi)
|
subtype-itemtype(Ai, Bi)
|
subtype-itemtype(Ai, Bi)
| false | |
Ai+
| false | false |
subtype-itemtype(Ai, Bi)
| false |
subtype-itemtype(Ai, Bi)
| false | |
xs:error
| true | true | true | true | true | true |
xs:error+
is treated the same way as xs:error
in the above table. xs:error?
and xs:error*
are treated the same way as empty-sequence()
.
subtype-itemtype(Ai, Bi)
The judgement subtype-itemtype(Ai, Bi)
determines if the Ai
is a Bi
. Ai
is a subtype of Bi
if and only if at least one of the following conditions applies:
Ai
and Bi
are derives-from(Ai, Bi)
returns true
.
Ai
is a pure union type,
and every type t
in the transitive membership of Ai
satisfies subtype-itemType(t, Bi)
.
Ai
is xs:error
and Bi
is a
Bi
is item()
.
Bi
is node()
, and Ai
is a
Bi
is text()
and Ai
is also text()
.
Bi
is comment()
and Ai
is also comment()
.
Bi
is namespace-node()
and Ai
is also namespace-node()
.
Bi
is processing-instruction()
and Ai
is either processing-instruction()
or
processing-instruction(N)
for any name N.
Bi
is processing-instruction(Bn)
, and Ai
is also processing-instruction(Bn)
.
Bi
is document-node()
and Ai
is either document-node()
or
document-node(E)
for any
Bi
is document-node(Be)
and Ai
is document-node(Ae)
, and subtype-itemtype(Ae, Be)
.
Bi
is either element()
or element(*)
, and Ai
is an
Bi
is either element(Bn)
or element(Bn, xs:anyType?)
,
the An
equals the Bn
,
and Ai
is either element(An)
element(An, T)
element(An, T?)
for any type T.
Bi
is element(Bn, Bt)
,
the An
equals the Bn
,
Ai
is element(An, At)
, and derives-from(At, Bt)
returns true
.
Bi
is element(Bn, Bt?)
,
the An
equals the Bn
,
Ai
is either element(An, At)
or element(An, At?)
,
and derives-from(At, Bt)
returns true
.
Bi
is element(*, Bt)
, Ai
is either element(*, At)
or element(N, At)
for any name N, and derives-from(At, Bt)
returns true
.
Bi
is element(*, Bt?)
, Ai
is either element(*, At)
, element(*, At?)
, element(N, At)
, or element(N, At?)
for any name N, and derives-from(At, Bt)
returns true
.
The fact that Bi
is schema-element(Bn)
,
Ai
is schema-element(An)
,
and every element declaration that is an actual member of the substitution group of An
is also an actual member of the substitution group of Bn
.
P
is a member of the substitution group of Q
does not mean that every element declaration in the substitution group of P
is also in the substitution group of Q
. For example, Q
might block substitution of elements whose type is derived by extension, while P
does not.
Bi
is either attribute()
or attribute(*)
, and Ai
is an
Bi
is either attribute(Bn)
or attribute(Bn, xs:anyType)
,
the An
equals the Bn
,
and Ai
is either attribute(An)
, or attribute(An, T)
for any type T.
Bi
is attribute(Bn, Bt)
,
the An
equals the Bn
,
Ai
is attribute(An, At)
,
and derives-from(At, Bt)
returns true
.
Bi
is attribute(*, Bt)
, Ai
is either attribute(*, At)
, or attribute(N, At)
for any name N, and derives-from(At, Bt)
returns true
.
Bi
is schema-attribute(Bn)
,
the An
equals the Bn
,
and Ai
is schema-attribute(An)
.
Bi
is
Ai
is a [AnnotationsA]
, and subtype-assertions(AnnotationsA, AnnotationsB)
, where [AnnotationsB]
and [AnnotationsA]
are optional lists of one or more annotations
Bi
is
,
Ai
is
,
where
[AnnotationsB]
and [AnnotationsA]
are optional lists of one or more annotationsN
(arity of Bi) equals M
(arity of Ai);
subtype(Ar, Br)
;
for values of I
between 1 and N
, subtype(Ba_I, Aa_I)
subtype-assertions(AnnotationsA, AnnotationsB)
Function return types are covariant because this rule invokes subtype(Ar, Br) for return types. Function arguments are contravariant because this rule invokes subtype(Ba_I, Aa_I) for arguments.
Ai
is map(K, V)
,
for any K
and V
and Bi
is map(*)
.
Ai
is map(Ka, Va)
and Bi
is map(Kb, Vb)
,
where subtype-itemtype(Ka, Kb)
and subtype(Va, Vb)
.
Ai
is map(*)
(or, because of the transitivity rules, any other map type),
and Bi
is function(*)
.
Ai
is map(*)
(or, because of the transitivity rules, any other map type),
and Bi
is
function(xs:anyAtomicType) as item()*
.
Ai
is array(X)
and Bi
is array(*)
.
Ai
is array(X)
and Bi
is function(Y)
, and X
is a subtype of Y
.
Ai
is array(*)
(or, because of the transitivity rules, any other array type) and Bi
is function(*)
.
Ai
is array(*)
(or, because of the transitivity rules, any other array type) and Bi
is function(xs:integer) as item()*
.
subtype-assertions(AnnotationsA, AnnotationsB)
The judgement subtype-assertions(AnnotationsA, AnnotationsB)
determines if AnnotationsA
is a subtype of AnnotationsB
,
where AnnotationsA
and AnnotationsB
are annotation lists from two FunctionTests.
It is defined to ignore function assertions in namespaces not understood by the XQuery
implementation. For assertions that are understood, their effect on the result
of subtype-assertions()
is implementation defined.
The following examples are some possible ways to define subtype-assertions()
for some
implementation defined assertions in the local
namespace. These examples assume that some implementation uses annotations to label functions as deterministic or nondeterministic, and treats deterministic functions as a subset of nondeterministic functions. In this implementation, nondeterministic functions are not a subset of deterministic functions.
AnnotationsA is
subtype-assertions()
.
AnnotationsA is
subtype-assertions()
is true.
AnnotationsA contains
%local:nondeterministic
annotation only match deterministic functions,
subtype-assertions()
must be false.
The type xs:error
has an empty value space; it never appears as a dynamic type or as the content type of a dynamic element or attribute type.
xs:error
offers an alternative way of raising errors, in addition to fn:error.
A cast to xs:error
raises an error or returns the empty sequence. Promotion to xs:error
is not possible.
Neither xs:error
nor xs:error+
can ever match a value. xs:error
is a subtype of all simple types, and a supertype only of itself.
xs:error?
and xs:error*
are identical to empty-sequence(). A variable binding with a type declaration xs:error always raises a type error.
Comments may be used to provide information relevant to programmers who read
Comments are strings, delimited by the symbols (:
and :)
. Comments may be nested.
A comment may be used anywhere
The following is an example of a comment:
This section discusses each of the basic kinds of 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 3.1 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 order in which expressions are discussed in this document does not reflect the order of operator precedence. In general, this document introduces the simplest kinds of expressions first, followed by more complex expressions. For the complete grammar, see Appendix [
The XQuery 3.1 operator that has lowest precedence is the
The symbol
After the comma, the expressions that have next lowest precedence are
The value of a .
" and no e
or E
character is an atomic value of type xs:integer
. The value of a numeric literal containing ".
" but no e
or E
character is an atomic value of type xs:decimal
. The value of a numeric literal containing an e
or E
character is an atomic value of type xs:double
. The value of the numeric literal is determined by casting it to the
appropriate type according to the rules for casting from xs:untypedAtomic
to a numeric type as specified in
The value of a xs:string
and whose value is the string denoted by the characters between the
delimiting apostrophes or quotation marks. If the literal is delimited by apostrophes, two adjacent apostrophes within the literal are interpreted as a single apostrophe. Similarly, if the literal is delimited by quotation marks, two adjacent quotation marks within the literal are interpreted as one quotation mark.
A string literal may contain a
Entity Reference | Character Represented |
<
|
<
|
>
|
>
|
&
|
&
|
"
|
"
|
'
|
'
|
A string literal may also contain a €
. Character references are normatively defined in Section 4.1 of the XML specification (it is
Here are some examples of literal expressions:
"12.5"
denotes the string containing the characters '1', '2', '.', and
'5'.
12
denotes the xs:integer
value twelve.
12.5
denotes the xs:decimal
value twelve and one half.
125E2
denotes the xs:double
value twelve thousand, five hundred.
"He said, ""I don't like it."""
denotes a string containing two quotation marks and one apostrophe.
"Ben & Jerry's"
denotes the xs:string
value "Ben & Jerry's
".
"€99.50"
denotes the xs:string
value "€99.50
".
The xs:boolean
values true
and false
can be constructed by calls to the
fn:true()
and fn:false()
, respectively.
Values of other atomic types can be constructed by
calling the
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.
xs:dayTimeDuration("PT5H")
returns an item whose type is xs:dayTimeDuration
and whose value represents a duration of five hours.
Constructor functions can also be used to create special values that have no literal representation, as in the following examples:
xs:float("NaN")
returns the special floating-point value, "Not a Number."xs:double("INF")
returns the special double-precision value, "positive infinity."
Constructor functions are available for all my:dt
is a user-defined union
type whose member types are xs:date
, xs:time
, and xs:dateTime
, then
the expression my:dt("2011-01-10")
creates an atomic value of type
xs:date
. The rules follow XML Schema validation rules for union types:
the effect is to choose the first member type that accepts the given
string in its lexical space.
It is also possible to construct values of various types by using a cast
expression. For example:
9 cast as
hatsize
returns the atomic value 9
whose type is hatsize
.
eq
operator). The scope of a variable binding is defined separately for each kind of
expression that can bind variables.
Every variable reference must match a name in the
Every variable binding has a static scope. The scope defines where
references to the variable can validly occur.
It is a
A reference to a variable that was declared external
, but was not bound to a value by the external environment, raises a
At evaluation time, the value of a variable reference is the value to which the relevant variable is bound.
Parentheses may be used to override the precedence rules.
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
A fn:doc("bib.xml")/books/book[fn:count(./author)>1]
),
or an atomic value or function (as in the expression (1 to
100)[. mod 5 eq 0]
).
If the
If the
Evaluation of
function calls is described in
Since the arguments of a function call are separated by commas, any
my:three-argument-function(1,
2, 3)
denotes a static function call with three arguments.
my:two-argument-function((1,
2), 3)
denotes a static function call with two arguments, the first of which is a
sequence of two values.
my:two-argument-function(1,
())
denotes a static function call with two arguments, the second of which is an
empty sequence.
my:one-argument-function((1, 2,
3))
denotes a static function call with one argument that is a sequence of three
values.
my:one-argument-function(( ))
denotes a static function call with one argument that is an empty sequence.
my:zero-argument-function( )
denotes a static function call with zero arguments.
When a static or dynamic function call FC is evaluated with respect to a static context SC and a dynamic context DC, the result is obtained as follows:
Argument
s
in an ArgumentList
is its
The function to be called or partially applied (call it F) is obtained as follows:
If FC is a static function call:
Using
the expanded QName corresponding to FC's EQName
,
and
the arity of FC's ArgumentList
,
the corresponding function
is looked up
in the
If FC is a dynamic function call:
FC's base expression is evaluated with respect to SC and DC.
If this yields a sequence consisting of a single function
with the same arity as the arity of the ArgumentList
,
let F denote that function.
Otherwise, a type error is raised
Each argument value is converted
to the corresponding parameter type in F's signature
by applying the
The remainder depends on whether or not FC
is a
If FC is a partial function application:
ArgumentList
has an argument expression
(as opposed to an ArgumentPlaceholder
).
A new function returned
(as the value of FC),
with the following properties
(as defined in
If FC is not a partial function application:
If F's implementation is
F's implementation is invoked with the converted argument values using the contexts it is associated with in F. If these contexts are absent in F, it is associated with SC and DC.
The result is either an instance of F's return type or a dynamic error. This result is then the result of evaluating FC.
Errors raised by built-in functions are defined in
Errors raised by external functions are
If F's implementation is a FunctionBody
:
The FunctionBody
is evaluated.
The dynamic context for this evaluation is obtained
by taking the dynamic context of the FunctionBody
, and
making the following changes:
The
In the
When
this is done,
the converted argument value retains
its most specific
$p
of type xs:decimal
can be invoked with an argument of type xs:integer
,
which is derived from xs:decimal
.
During the processing of this function
call,
the $p
inside the body of the function
is considered to be xs:integer
.
F's nonlocal variable bindings
are also added to the
The value returned by evaluating the function body
is then converted to the declared return type of F
by applying the
As with argument values,
the value returned by a function
retains its most specific type,
which may be derived from the declared return type of F.
For example, a function that has
a declared return type of xs:decimal
may in fact return a value of dynamic type xs:integer
.
If the expected type is a sequence of a *
, +
, or ?
), the following conversions are applied:
Atomization converts arrays to sequences (see
Each item in the atomic
sequence that is of type
xs:untypedAtomic
is cast to the expected generalized
atomic type. For xs:untypedAtomic
are cast to xs:double
. If the item is of type xs:untypedAtomic
and the expected type is
For each
For each item of type xs:anyURI
in the atomic sequence that can be
If the
expected type is a *
,
+
, or ?
),
If, after the
above conversions, the resulting value does not match
the expected type according to the rules for
Function coercion is a transformation applied to
Function coercion
is only defined to operate on
Annotations
is set to the annotations of F. TypedFunctionTest
is set to the expected type.
FunctionBody
that calls F,
passing it the parameters of this new function,
in order.
If the result of invoking the new function would necessarily result in a type error, that error may be raised during function coercion. It is implementation dependent whether this happens or not.
These rules have the following consequences:
SequenceType matching of the function's arguments and result are delayed until that function is invoked.
The function conversion rules applied to the function's arguments and result are defined by the SequenceType
it has most recently been coerced to. Additional function conversion rules could apply when the wrapped function
is invoked.
If an implementation has static type information about a function, that can be used to type check the
function's argument and return types during static analysis.
The function
The function conversion rules result in applying function coercion to
$p is matched against the SequenceType of
When $p is invoked inside the predicate, function conversion and SequenceType matching rules are applied to the context item argument,
resulting in an
$f is invoked with the
$p applies function conversion rules to the result sequence from $f, which already matches its declared return type of
The $f
has a static type of function(item()*) as item()*
. When the local:filter()
function
is called, the following occurs to the function:
$f
,
wrapping $f in a new function ($p)
with the signature function(xs:string) as xs:boolean
.
function(xs:string) as xs:boolean
, and succeeds.
xs:string
value or a type error.
xs:string
, which returns an xs:boolean
.
xs:boolean
.
xs:boolean
is returned as the result of $p.
Although the semantics of function coercion are specified in terms of wrapping the functions, static typing will often be able to reduce the number of places where this is actually necessary.
If the EQName is a
If the
The value of a NamedFunctionRef
is the function obtained by looking up
the expanded QName and arity
in the
Furthermore, if the function referenced by a
NamedFunctionRef
has an implementation-dependent
implementation, then the implementation of the function
returned by the NamedFunctionRef
is associated with the
static context of this NamedFunctionRef
expression and to
the dynamic context in which it is currently being
evaluated.
Certain functions in the
The above way of modeling polymorphic functions is semantically backwards compatible with
The following are examples of named function references:
fn:abs#1
references the fn:abs function which takes a single argument.
fn:concat#5
references the fn:concat function which takes 5 arguments.
local:myfunc#2
references a function named local:myfunc which takes 2 arguments.
If a function parameter is declared using a name but no type, its default type is item()*. If the result type is omitted from an inline function expression, its default result type is item()*.
The parameters of an inline function expression are considered to be variables whose scope is the function body. It is a static error
An inline function
expression may have
annotations. XQuery 3.1 does not define annotations that
apply to inline function
expressions, in particular it is a %public
or %private
. An
implementation can define annotations, in its own namespace,
to support functionality beyond the scope of this
specification.
The static context for the function body is inherited from the location of the inline function expression, with the exception of the
static type of the context item which is initially
The variables in scope for the function body include all variables representing the function parameters, as well as all variables that
are in scope for the inline function expression.
Function parameter names can mask variables that would otherwise be in scope for the function body.
The result of an inline function expression is a single function with the following properties (as defined in
InlineFunctionExpr
's
ParamList
.
FunctionTest
constructed from the
Annotation
s andSequenceType
s in the InlineFunctionExpr
.
InlineFunctionExpr
's FunctionBody
.
InlineFunctionExpr
.
The following are examples of some inline function expressions:
This example creates a function that takes no arguments and returns a sequence of the first 6 primes:
This example creates a function that takes two xs:double arguments and returns their product:
This example creates a function that returns its item()* argument:
This example creates a sequence of functions each of which returns a
different node from the default collection.
E1[E2]
)
is referred to as a E1
that
satisfy the predicate in E2.
An expression (other than a raw EQName) followed by an argument
list in parentheses (that is, E1(E2, E3, ...)
) is
referred to as a E1
to obtain a function,
and then call that function, with
E2
, E3
, ...
as
arguments. Dynamic function are described in
A filter expression consists of a base expression followed by a predicate, which is an expression written in square brackets. The result of the filter expression consists of the items returned by the base expression, filtered by applying the predicate to each item in turn. The ordering of the items returned by a filter expression is the same as their order in the result of the primary expression.
Where the expression before the square brackets is a
Here are some examples of filter expressions:
Given a sequence of products in a variable, return only those products whose price is greater than 100.
List all the integers from 1 to 100 that are divisible by 5. (See to
operator.)
The result of the following expression is the integer 25:
The following example returns the fifth through ninth items in the sequence bound to variable $orders
.
The following example illustrates the use of a filter expression as a $book
:
For each item in the input sequence, the predicate expression
is evaluated using an
For each item in the input sequence, the result of the
predicate expression is coerced to an xs:boolean
value, called the 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 a true
if the value
of the predicate expression is equal (by the
eq
operator) to the false
otherwise.
In a region of a query where unordered
, the result of a numeric predicate is
Otherwise, the predicate truth value is the
A dynamic function call
is evaluated as described in
The following are examples of some dynamic function calls:
This example invokes the function contained in $f, passing the arguments 2 and 3:
This example fetches the second item from sequence $f, treats it as a function and invokes it, passing an xs:string
argument:
This example invokes the function $f passing no arguments, and filters the result with a positional predicate:
=>
)
$s
is f()
is a function, then $s=>f()
is equivalent to f($s)
, and $s=>f($j)
is equivalent to f($s, $j)
.
This syntax is particularly helpful when conventional function call syntax is unreadable, e.g. when applying multiple functions to an item. For instance, the following expression is difficult to read due to the nesting of parentheses, and invites syntax errors due to unbalanced parentheses:
Many people consider the following expression easier to read, and it is much easier to see that the parentheses are balanced:
/
" or
"//
", and optionally beginning with
"/
" or "//
"./
" 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
A "/
"
at the beginning of a path expression is an abbreviation for
the initial step (fn:root(self::node()) treat as document-node())/
(however, if the
"/
" is the entire path expression, the trailing "/
" is omitted from the expansion.) The effect
of this initial step is to begin the path at the root node of
the tree that contains the context node. If the context item
is not a node, a
A "//
" at the beginning of a path expression
is an abbreviation for the initial steps
(fn:root(self::node()) treat as
document-node())/descendant-or-self::node()/
(however, "//
" by itself is not a valid path expression
The descendants of a node do not include attribute nodes.
Relative path expressions are binary operators on step expressions, which are named E1
and E2
in this section.
Each non-initial occurrence of "//
" in a path expression is
expanded as described in /
". This sequence
of steps is then evaluated from left to right. Each item produced by the evaluation of E1
is used as the E2
; the sequences resulting from all the evaluations of E2
are combined to produce a result.
The following example illustrates the use of relative path expressions.
child::div1/child::para
Selects the
para
element children of the div1
element children of the context node; that is, the
para
element grandchildren of the context node
that have div1
parents.
Since each step in a path provides context nodes for the following step, in effect, only the last step in a path is allowed to return a sequence of non-nodes.
The "/
" character
can be used either as a complete path expression or as the
beginning of a longer path expression such as
"/*
". Also, "*
"
is both the multiply operator and a wildcard in path
expressions. This can cause parsing difficulties when
"/
" appears on the left-hand side of
"*
". This is resolved using the /*
" and "/
*
" are valid path expressions containing wildcards,
but "/*5
" and "/ * 5
" raise syntax
errors. Parentheses must be used when "/
" is
used on the left-hand side of an operator, as in "(/) * 5
". Similarly, "4 + / *
5
" raises a syntax error, but "4 + (/) * 5
" is a valid expression.
The expression "4 + /
" is also
valid, because /
does not occur on the left-hand
side of the operator.
Similarly, in the expression /
union /*
, "union" is interpreted as an element name
rather than an operator. For it to be parsed as an operator,
the expression should be written (/)
union /*
.
/
)The path operator "/" is used to build expressions for locating nodes within trees. Its left-hand side expression must return a sequence of nodes. The operator returns either a sequence of nodes, in which case it additionally performs document ordering and duplicate elimination, or a sequence of non-nodes.
Each operation E1/E2
is evaluated as follows: Expression E1
is evaluated, and if the result is not a (possibly empty) sequence S
of nodes, a S
then serves in turn to provide an inner focus (the node as the context item, its position in S
as the context position, the length of S
as the context size) for an evaluation of E2
, as described in E2
are combined as follows:
If every evaluation of E2
returns a (possibly empty) sequence of nodes, these sequences are combined, and duplicate nodes are eliminated based on node identity.
If every evaluation of E2
returns a (possibly empty) sequence of non-nodes, these sequences are concatenated and returned. ordered
, the returned sequence preserves the orderings within and among the subsequences generated by the evaluations of E2
; otherwise the order of the returned sequence is
If the multiple evaluations of E2
return at least one node and at least one non-node, a
The semantics of the path operator can also be defined using the simple mapping operator as follows (forming the union with an empty sequence ($R | ())
has the effect of eliminating duplicates and sorting nodes into document order):
ordered
, the resulting node sequence is returned in
In the
The unabbreviated syntax for an axis 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, name,
and/or 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
XQuery supports the following axes:
The child
axis
contains the children of the context
node, which are the nodes returned by
the dm:children
accessor
in
Only document nodes and element nodes have children. If the context node is any other kind of node, or if the context node is an empty document or element node, then the child axis is an empty sequence. The children of a document node or element node may be element, processing instruction, comment, or text nodes. Attribute and document nodes can never appear as children.
the descendant
axis is defined as the transitive closure of
the child axis; it contains the descendants
of the context node (the children, the children of the children, and so on)
the parent
axis contains the sequence
returned by the
dm:parent
accessor in
An attribute node may have an element node as its parent, even though the attribute node is not a child of the element node.
the
ancestor
axis is
defined as the transitive
closure of the parent axis; it
contains the ancestors of the
context node (the parent, the
parent of the parent, and so
on)
The ancestor axis includes the root node of the tree in which the context node is found, unless the context node is the root node.
the following-sibling
axis contains the context node's following
siblings, those children of the context
node's parent that occur after the context
node in following-sibling
axis is
empty
the preceding-sibling
axis contains the context node's preceding
siblings, those children of the context
node's parent that occur before the context
node in preceding-sibling
axis is
empty
the following
axis
contains all nodes that are
descendants of the root of the tree in
which the context node is found, are
not descendants of the context node,
and occur after the context node in
the preceding
axis
contains all nodes that are
descendants of the root of the tree in
which the context node is found, are
not ancestors of the context node, and
occur before the context node in
the attribute
axis
contains the attributes of the context node,
which are the nodes returned by the
dm:attributes
accessor in
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
the ancestor-or-self
axis contains the context node and the ancestors of the context node;
thus, the ancestor-or-self axis will always include the root node
Axes can be categorized as
The parent
, ancestor
, ancestor-or-self
, preceding
, and preceding-sibling
axes are reverse axes; all other axes are forward axes. The ancestor
, descendant
, following
, preceding
and self
axes partition a document (ignoring attribute nodes):
they do not overlap and together they contain all the nodes in the
document.
For the attribute axis, the principal node kind is attribute.
For all other axes, the principal node kind is element.
eq
operator) to the
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.
If the EQName is a
A name test is not satisfied by an element node whose name does not match the
A node test *
is true for any node of the
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
A node test can contain a BracedURILiteral, e.g.
Q{http://example.com/msg}*
Such a node test is true for any node of the principal node kind of the step axis whose expanded QName has the namespace URI specified in the BracedURILiteral, 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
node()
matches any
node.
text()
matches
any text
node.
comment()
matches any comment
node.
namespace-node()
matches any
namespace node.
element()
matches any element
node.
schema-element(person)
matches any element node whose name is
person
(or is in the person
), and whose type
annotation is the same as (or is derived from) the declared type of the person
element in the
element(person)
matches any element node whose name is
person
, regardless of its type annotation.
element(person, surgeon)
matches any non-nilled element node whose name
is person
, and whose type
annotation is
surgeon
or is derived from surgeon
.
element(*,
surgeon)
matches any non-nilled element node whose type
annotation is surgeon
(or is derived from surgeon
), regardless of
its
name.
attribute()
matches any
attribute node.
attribute(price)
matches
any attribute whose name is price
,
regardless of its type annotation.
attribute(*,
xs:decimal)
matches any attribute whose type
annotation is xs:decimal
(or is derived from xs:decimal
), regardless of
its
name.
document-node()
matches any document
node.
document-node(element(book))
matches any document node whose content consists of
a single element node that satisfies the element(book)
, interleaved with zero or more
comments and processing
instructions.
A predicate within a Step has similar syntax and semantics
to a predicate within a
For the purpose of evaluating the context position within a predicate, the input sequence is considered to be sorted as follows: into document order if the predicate is in a forward-axis step, into reverse document order if the predicate is in a reverse-axis step, or in its original order if the predicate is not in a step.
Here are some examples of
This example selects the second chapter
element that is a child
of the context node:
This example selects all the descendants of the
context node that are elements named
"toy"
and whose color
attribute has the value "red"
:
This example selects all the employee
children of the context node
that have both a secretary
child element and an assistant
child element:
When using preceding::foo[1]
returns the first qualifying foo
element in (preceding::foo)[1]
returns the first qualifying foo
element in (preceding::foo)
to be parsed as a ancestor::*[1]
returns the nearest ancestor element, because the ancestor
axis is a
reverse axis, whereas (ancestor::*)[1]
returns the root element (first ancestor in document order).
The fact that a reverse-axis step assigns context positions in reverse
document order for the purpose of evaluating predicates does not alter the
fact that the final result of the step
This section provides a number of examples of path expressions in which the
axis is explicitly specified in each
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. Note that no attribute nodes are returned, because attributes are not children.
attribute::name
selects the name
attribute of the context node
attribute::*
selects all the attributes of the context node
parent::node()
selects the parent of the context node. If the context node is an attribute node, this expression returns the element node (if any) to which the attribute node is attached.
descendant::para
selects the para
element descendants of the context node
ancestor::div
selects all div
ancestors of the context node
ancestor-or-self::div
selects the div
ancestors of the context node and, if the context node is a div
element, the context node as well
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 returns an empty sequence
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 tree that contains the context node, but raises a dynamic error if this root is not a document node
/descendant::para
selects all the para
elements in the same document as the context node
/descendant::list/child::member
selects all
the member
elements that have a list
parent and that are in the same document as the context node
child::para[fn:position() = 1]
selects the first para
child of the context node
child::para[fn:position() = fn:last()]
selects the last para
child of the context node
child::para[fn:position() = fn:last()-1]
selects the last but one para
child of the context node
child::para[fn:position() > 1]
selects all the para
children of the context node other than the first para
child of the context node
following-sibling::chapter[fn:position() = 1]
selects the next chapter
sibling of the context node
preceding-sibling::chapter[fn:position() = 1]
selects the previous chapter
sibling of the context node
/descendant::figure[fn:position() = 42]
selects the forty-second figure
element in the document containing the context node
/child::book/child::chapter[fn:position() = 5]/child::section[fn:position() = 2]
selects the
second section
of the fifth chapter
of the book
whose parent is the document node that contains the context node
child::para[attribute::type eq "warning"]
selects
all para
children of the context node that have a type
attribute with value warning
child::para[attribute::type eq 'warning'][fn:position() = 5]
selects the fifth para
child of the context node that has a type
attribute with value warning
child::para[fn:position() = 5][attribute::type eq "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 whose Introduction
child::chapter[child::title]
selects the chapter
children of the context node that have one or more title
children
child::*[self::chapter or self::appendix]
selects the chapter
and appendix
children of the context node
child::*[self::chapter or
self::appendix][fn:position() = fn:last()]
selects the
last chapter
or appendix
child of the context node
The abbreviated syntax permits the following abbreviations:
The attribute axis 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
.
If the axis name is omitted from an
child
, with two exceptions:
(1) if the attribute
;
(2) if the section/para
is an abbreviation for child::section/child::para
, and the path
expression section/@id
is an
abbreviation for child::section/attribute::id
. Similarly,
section/attribute(id)
is an
abbreviation for child::section/attribute::attribute(id)
. Note
that the latter expression contains both an axis specification and
a
Each non-initial occurrence of //
is effectively replaced by /descendant-or-self::node()/
during processing of a path expression. For example, div1//para
is
short for child::div1/descendant-or-self::node()/child::para
and so will select all para
descendants of div1
children.
The path expression //para[1]
does /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 respective parents.
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.
The expression .
, known as a
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[fn:last()]
selects the last para
child of the context node
*/para
selects
all para
grandchildren of the context node
/book/chapter[5]/section[2]
selects the
second section
of the fifth chapter
of the book
whose parent is the document node that contains the context node
chapter//para
selects the para
element descendants of the chapter
element children of the context node
//para
selects all
the para
descendants of the root document node and thus selects all para
elements in the same document as the context node
//@version
selects all the version
attribute nodes that are 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 a list
parent
.//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 type
attribute 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 whose 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.
If E
is any expression that returns a sequence of nodes, then the expression E/.
returns the same nodes in
XQuery 3.1 supports operators to construct, filter, and combine
1
, (2, 3)
, and ( )
into a single sequence results
in the sequence (1, 2, 3)
.
A sequence may contain duplicate
In places where the grammar calls for
Here are some examples of expressions that construct sequences:
The result of this expression is a sequence of five integers:
This expression combines four sequences of length one, two, zero, and two, respectively, into a single sequence of length five. The result of this expression is the sequence 10, 1, 2, 3, 4
.
The result of this expression is a sequence containing
all salary
children of the context node followed by all bonus
children.
Assuming that $price
is bound to
the value 10.50
, the result of this expression is the sequence 10.50, 10.50
.
A to
operator is
converted as though it was an argument of a function with the expected
parameter type xs:integer?
.
If either operand is an empty sequence, or if the integer derived from the first operand is greater than the integer derived from the second operand, the result of the range expression is an empty sequence. If the two operands convert to the same integer, the result of the range expression is that integer. Otherwise, the result is a sequence containing the two integer operands and
every integer between the two operands, in increasing order.
This example uses a range expression as one operand in constructing a sequence. It evaluates to the sequence 10, 1, 2, 3, 4
.
This example constructs a sequence of length one containing the single integer 10
.
The result of this example is a sequence of length zero.
This example uses the fn:reverse
function to construct a sequence of six integers in decreasing order. It evaluates to the sequence 15, 14, 13, 12, 11, 10
.
XQuery 3.1 provides the following operators for combining sequences of nodes:
The union
and |
operators are equivalent. They take two node sequences as operands and
return a sequence containing all the nodes that occur in either of the
operands.
The intersect
operator takes two node sequences as operands and returns a sequence
containing all the nodes that occur in both operands.
The except
operator takes two node sequences as operands and returns a sequence
containing all the nodes that occur in the first operand but not in the second
operand.
All these operators eliminate duplicate nodes from their result sequences based on node identity. ordered
, the resulting sequence is returned in
If an operand
of union
, intersect
, or except
contains an item that is not a node, a
If an IntersectExceptExpr contains more than two InstanceofExprs, they are grouped from left to right. With a UnionExpr, it makes no difference how operands are grouped, the results are the same.
Here are some examples of expressions that combine sequences. Assume the existence of three element nodes that we will refer to by symbolic names A, B, and C. ordered
.$seq1
, $seq2
and $seq3
are bound to the following sequences of these nodes:
$seq1
is bound to (A, B)
$seq2
is bound to (A, B)
$seq3
is bound to (B, C)
Then:
$seq1 union $seq2
evaluates to the sequence (A, B).
$seq2 union $seq3
evaluates to the sequence (A, B, C).
$seq1 intersect $seq2
evaluates to the sequence (A, B).
$seq2 intersect $seq3
evaluates to the sequence containing B only.
$seq1 except $seq2
evaluates to the empty sequence.
$seq2 except $seq3
evaluates to the sequence containing A only.
In addition to the sequence operators described here,
XQuery 3.1 provides arithmetic operators for addition, subtraction, multiplication, division, and modulus, in their usual binary and unary forms.
A subtraction operator must be preceded by whitespace if
it could otherwise be interpreted as part of the previous token. For
example, a-b
will be interpreted as a
name, but a - b
and a -b
will be interpreted as arithmetic expressions. (See
If an AdditiveExpr contains more than two MultiplicativeExprs,
they are grouped from left to right. So, for instance,
The first step in evaluating an arithmetic expression is to evaluate its operands. The order in which the operands are evaluated is
Atomization converts arrays to sequences (see
If the atomized operand is an empty sequence, the result of the arithmetic expression is an empty sequence, and the implementation need not evaluate the other operand or apply the operator. However, an implementation may choose to evaluate the other operand in order to determine whether it raises an error.
If the atomized operand is a sequence of
length greater than one, a
If the atomized operand is of type xs:untypedAtomic
, it is cast to xs:double
. If
the cast fails, a
After evaluation of the operands, if the types of the operands are a valid combination
for the given arithmetic operator, the operator is applied to the operands,
resulting in an atomic value or a
If the types of the operands, after evaluation, are not a valid combination for the given operator, according to the rules in
XQuery 3.1 supports two division operators named div
and idiv
. Each of these operators accepts two operands of any $arg1 idiv $arg2
is equivalent to ($arg1 div $arg2) cast as xs:integer?
except for error cases.
Here are some examples of arithmetic expressions:
The first expression below returns the xs:decimal
value -1.5
, and the second expression returns the xs:integer
value -1
:
Atomization converts arrays to sequences (see
Subtraction of two date values results in a value of type xs:dayTimeDuration
:
This example illustrates the difference between a subtraction operator and a hyphen:
Unary operators have higher precedence than binary operators, subject of course to the use of parentheses. Therefore, the following two examples have different meanings:
Multiple consecutive unary arithmetic operators are permitted by XQuery 3.1 for compatibility with
String concatenation expressions allow the string representations of values to be concatenated. In XQuery 3.1, $a || $b
is equivalent to fn:concat($a, $b)
. The following expression evaluates to the string concatenate
:
Comparison expressions allow two values to be compared. XQuery 3.1 provides three kinds of comparison expressions, called value comparisons, general comparisons, and node comparisons.
The value comparison operators are eq
, ne
, lt
, le
, gt
, and ge
. Value comparisons are used for comparing single values.
The first step in evaluating a value comparison is to evaluate its operands. The order in which the operands are evaluated is
Atomization converts arrays to sequences (see
If
If
If xs:untypedAtomic
, it is cast to
xs:string
.
The purpose of this rule is to
make value comparisons transitive. Users should be aware that the
general comparison operators have a different rule for casting of
xs:untypedAtomic
operands. Users should also be aware
that transitivity of value comparisons may be compromised by loss of
precision during type conversion (for example, two
xs:integer
values that differ slightly may both be
considered equal to the same xs:float
value because
xs:float
has less precision than
xs:integer
).
Next, if possible, the two operands are converted to their least common
type by a combination of hatsize
(derived from xs:integer
) and
shoesize
(derived from xs:float
), their least common type is xs:float
.
If the two operands are instances of different primitive types (meaning the 19 primitive types defined in If each operand is an instance of one of the types If each operand is an instance of one of the types If each operand is an instance of one of the types Otherwise, a The primitive type of an xs:string
or xs:anyURI
, then both operands are cast to type xs:string
.xs:decimal
or xs:float
, then both operands are cast to type xs:float
.xs:decimal
, xs:float
, or xs:double
, then both operands are cast to type xs:double
.xs:integer
value for this purpose is xs:decimal
.
Finally, if the types of the operands are a valid combination for the given operator, the operator is applied to the operands.
The combinations of atomic types that are accepted by the various
value comparison operators, and their respective result types, are
listed in
Informally, if both atomized operands consist of exactly one atomic
value, then the result of the comparison is true
if the value of the
first operand is (equal, not equal, less than, less than or equal,
greater than, greater than or equal) to the value of the second
operand; otherwise the result of the comparison is false
.
If the types of the operands, after evaluation, are not a valid
combination for the given operator, according to the rules in
Here are some examples of value comparisons:
The following comparison atomizes the node(s) that are returned by the expression $book/author
. The comparison is true only if the result of atomization is the value "Kennedy" as an instance of xs:string
or xs:untypedAtomic
. If the result of atomization is an empty sequence, the result of the comparison is an empty sequence. If the result of atomization is a sequence containing more than one value, a
The following comparison is true
because atomization converts an array to its member sequence:
The following weight
subelement, the value of the predicate is the empty sequence, and the product is not selected. This example assumes that weight
is a validated element with a numeric type.
The following comparisons are true because, in each case, the two constructed nodes have the same value after atomization, even though they have different identities and/or names:
The following comparison is true if my:hatsize
and my:shoesize
are both user-defined types that are derived by restriction from a primitive
The following comparison is true. The eq
operator compares two QNames by performing codepoint-comparisons of their namespace URIs and their local names, ignoring their namespace prefixes.
The general comparison operators are =
, !=
, <
, <=
, >
, and >=
. General comparisons are existentially quantified comparisons that may be applied to operand sequences of any length. The result of a general comparison that does not raise an error is
always true
or false
.
Atomization converts arrays to sequences (see
The result of the comparison is true
if and only if there is a pair of
atomic values, one in the first operand sequence and the other in the second operand sequence, that have the required
false
. The cast
operation called for by these rules is not successful, a
The purpose of these rules is to preserve compatibility with XPath 1.0, in which (for example) x < 17
is a numeric comparison if x
is an untyped value. Users should be aware that the value comparison operators have different rules for casting of xs:untypedAtomic
operands.
If both atomic values are instances of xs:untypedAtomic
,
then the values are cast to the type xs:string
.
If exactly one of the atomic values is an instance of
xs:untypedAtomic
, it is cast to a type depending on
the other value's dynamic type T according to the following rules,
in which V denotes the value to be cast:
If T is a numeric type or is derived from a numeric type,
then V is cast to xs:double
.
If T is xs:dayTimeDuration
or is derived from
xs:dayTimeDuration
,
then V is cast to xs:dayTimeDuration
.
If T is xs:yearMonthDuration
or is derived from
xs:yearMonthDuration
,
then V is cast to xs:yearMonthDuration
.
In all other cases, V is cast to the primitive base type of T.
The special treatment of the duration types is required to avoid
errors that may arise when comparing the primitive type
xs:duration
with any duration type.
After performing the conversions described above, the atomic values are
compared using one of the value comparison operators eq
, ne
, lt
, le
, gt
, or
ge
, depending on whether the general comparison operator was =
, !=
, <
, <=
,
>
, or >=
. The values have the required true
.
When evaluating a general comparison in which either operand is a sequence of items, an implementation may return true
as soon as it finds an item in the first operand and an item in the second operand that have the required
Here are some examples of general comparisons:
The following comparison is true if the author
subelement of $book1
is "Kennedy" as an instance of xs:string
or xs:untypedAtomic
:
The following comparison is true
because atomization converts an array to its member sequence:
The following example contains three general comparisons. The value of the first two comparisons is true
, and the value of the third comparison is false
. This example illustrates the fact that general comparisons are not transitive.
The following example contains two general comparisons, both of which are true
. This example illustrates the fact that the =
and !=
operators are not inverses of each other.
Suppose that $a
, $b
, and $c
are bound to element nodes with type annotation xs:untypedAtomic
, with 1
", "2
", and "2.0
" respectively. Then ($a, $b) = ($c, 3.0)
returns false
, because $b
and $c
are compared as strings. However, ($a, $b) = ($c, 2.0)
returns true
, because $b
and 2.0
are compared as numbers.
Node comparisons are used to compare two nodes, by their identity or by their
The operands of a node comparison are evaluated in
If either operand is an empty sequence, the result of the comparison is an empty sequence, and the implementation need not evaluate the other operand or apply the operator. However, an implementation may choose to evaluate the other operand in order to determine whether it raises an error.
Each operand must be either a single node or an empty sequence; otherwise
a
A comparison with the is
operator is true
if the two operand nodes false
. See
A comparison with the <<
operator returns true
if the left operand node precedes the right operand node in
false
.
A comparison with the >>
operator returns true
if the left operand node follows the right operand node in
false
.
Here are some examples of node comparisons:
The following comparison is true only if the left and right sides each evaluate to exactly the same single node:
The following comparison is false because each constructed node has its own identity:
The following comparison is true only if the node identified by the left side occurs before the node identified by the right side in document order:
A true
or false
.
The first step in evaluating a logical expression is to find the
The value of an and-expression is determined by the effective boolean values (EBV's) of its operands, as shown in the following table:
AND: | EBV2 =
true
| EBV2 = false
| error in EBV2 |
EBV1 =
true
|
true
|
false
| error |
EBV1
= false
|
false
|
false
|
false or
error |
error in EBV1 | error |
false or
error | error |
The value of an or-expression is determined by the effective boolean values (EBV's) of its operands, as shown in the following table:
OR: | EBV2 =
true
| EBV2 = false
| error in EBV2 |
EBV1 =
true
|
true
|
true
|
true or
error |
EBV1 =
false
|
true
|
false
| error |
error in EBV1 |
true or
error | error | error |
true
if the first
expression evaluated is true, and it can raise an error if evaluation
of the first expression raises an error. Similarly, an and-expression
can return false
if the first expression evaluated is
false, and it can raise an error if evaluation of the first expression
raises an error. As a result of these rules, a logical expression is
not deterministic in the presence of errors, as illustrated in the examples
below.
Here are some examples of logical expressions:
The following expressions return
true
:
The following
expression may return either false
or raise a
The
following expression may return either true
or raise a
The
following expression must raise a
In addition to and- and or-expressions, XQuery 3.1 provides a
function named fn:not
that takes a general sequence as
parameter and returns a boolean value. The fn:not
function
is defined in fn:not
function reduces its parameter to an true
if the effective boolean value of its parameter is
false
, and false
if the effective boolean
value of its parameter is true
. If an error is
encountered in finding the effective boolean value of its operand,
fn:not
raises the same error.
XQuery provides constructors that can create XML structures within a query.
Constructors are provided for element, attribute, document, text, comment, and processing instruction nodes. Two kinds of constructors are provided:
This section contains a conceptual description of the semantics of various kinds of constructor expressions. An XQuery implementation is free to use any implementation technique that produces the same result as the processing steps described in this section.
An book
element containing an attribute and some nested elements:
If the element name in a direct element constructor has a namespace prefix, the namespace prefix is resolved to a namespace URI using the node-name
property of the constructed element node.
In a direct element constructor, the name used in the end tag must exactly match the name
used in the corresponding start tag, including its prefix or absence of a prefix
In a direct element constructor, curly braces { } delimit
The above query might generate the following result (whitespace has been added for readability to this result and other result examples in this document):
Since XQuery uses curly braces to denote enclosed expressions, some
convention is needed to denote a curly brace used as an ordinary character. For
this purpose, a pair of identical curly brace characters within the content of an element or attribute are interpreted by XQuery as a single curly brace
character (that is, the pair "{{
" represents the
character "{
" and the pair "}}
" represents
the character "}
".) Alternatively, the {
and }
can be used to denote curly brace characters. A single left curly brace
("{
") is interpreted as the beginning delimiter for an
enclosed expression. A single right curly brace ("}
")
without a matching left curly brace is treated as a
The result of an element constructor is a new element node, with its own node identity. All the attribute and descendant nodes of the new element node are also new nodes with their own identities, even if they are copies of existing nodes.
The start tag of a direct element constructor may contain one or more attributes. As in XML, each attribute is specified by a name and a value. In a direct element constructor, the name of each attribute is specified by a constant
Each attribute in a direct element constructor creates a new attribute node, with its own node identity, whose parent is the constructed element node. However, note that
If an attribute name has a namespace prefix, the prefix is resolved to a namespace URI using the node-name
property of the constructed attribute node.
If the attributes in a direct element constructor do not have distinct node-name
properties, a
Conceptually, an attribute (other than a namespace declaration attribute) in a direct element constructor is processed by the following steps:
Each consecutive sequence of literal characters in the attribute content is processed as a string literal containing those characters, with the following exceptions:
Each occurrence of two consecutive {
characters is replaced by a single {
character.
Each occurrence of two consecutive }
characters is replaced by a single }
character.
Each occurrence of "
character.
Each occurrence of '
character.
Attribute value normalization is then applied to
normalize whitespace and expand
Each enclosed expression is converted to a string as follows:
Atomization converts arrays to sequences (see
If the result of atomization is an empty sequence, the result is the zero-length string. Otherwise, each atomic value in the atomized sequence is cast into a string.
The individual strings resulting from the previous step are merged into a single string by concatenating them with a single space character between each pair.
Adjacent strings resulting from the above steps are concatenated with no intervening blanks. The resulting string becomes the string-value
property of the attribute node. The attribute node is given a xs:untypedAtomic
(this type annotation may change if the parent element is validated). The typed-value
property of the attribute node is the same as its string-value
, as an instance of xs:untypedAtomic
.
The parent
property of the attribute node is set to the element node constructed by the direct element constructor that contains this attribute.
If the attribute name is xml:id
, then xml:id
processing is performed as defined in xs:ID
and that its value is properly normalized. If an error is encountered during xml:id
processing, an implementation may raise a
If the attribute name is xml:id
, the is-id
property of the resulting attribute node is set to true
; otherwise the is-id
property is set to false
. The is-idrefs
property of the attribute node is unconditionally set to false
.
Example:
The string value of the size
attribute is "7
".
Example:
The string value of the size
attribute is "7
".
Example:
The string value of the size
attribute is the zero-length string.
Example:
The string value of the ref
attribute is "[1 5 6 7 9]
".
Example:
The string value of the size
attribute is the
string "As big as
", concatenated with the string value of the
node denoted by the expression
$hat/@size
.
The names of
a constructed element and its attributes may be
xmlns
, or with name
xmlns
and no namespace prefix. All the namespace
declaration attributes of a given element must have distinct names
The value of the namespace declaration attribute (a
If the prefix of the attribute name is xmlns
, then the
local part of the attribute name is interpreted as a namespace prefix.
This prefix and the namespace URI are added to the
If the name of the namespace declaration attribute is xmlns
with no prefix, then the namespace URI specifies the
It is a Bind the prefix Bind a prefix other than Bind the prefix Bind a prefix to the namespace
URI xml
to some namespace URI
other than http://www.w3.org/XML/1998/namespace
.
xml
to the namespace
URI http://www.w3.org/XML/1998/namespace
.
xmlns
to any namespace URI.
http://www.w3.org/2000/xmlns/
.
A namespace declaration attribute does not cause an attribute node to be created.
The following examples illustrate namespace declaration attributes:
In this element constructor, a namespace declaration attribute is used to set the http://example.org/animals
:
In this element constructor, namespace declaration attributes are used to bind the namespace prefixes metric
and english
:
The part of a direct element constructor between the start tag and the end tag is called the
Conceptually, the content of an element constructor is processed as follows:
The content is evaluated to produce a
sequence of nodes called the
If the strip
,
<
and &
, are treated as literal characters rather than as markup characters (except for the sequence ]]>
, which terminates the CDataSection).
Each consecutive sequence of literal characters evaluates to a single text node containing the characters.
Each nested direct constructor is evaluated according to the rules in
The parent
property of the resulting node is then set to the newly constructed element node.
The base-uri
property of the
resulting node, and of each of its descendants, is set to be the same as that
of its new parent, unless it (the child node) has an xml:base
attribute, in
which case its base-uri
property is set to the value of that attribute,
base-uri
property of its new parent
node.
Enclosed expressions are evaluated as follows:
Each array returned by the enclosed expression is flattened by calling the function array:flatten()
before the steps that follow.
If an enclosed expression returns a
For each adjacent sequence of one or more atomic values returned by an enclosed expression, a new text node is constructed, containing the result of casting each atomic value to a string, with a single space character inserted between adjacent values.
The insertion of blank characters between adjacent values applies even if one or both of the values is a zero-length string.
For each node returned by an enclosed expression, a new copy is made of the given node and all nodes that have the given node as an ancestor, collectively referred to as
Each copied node receives a new node identity.
The parent
, children
, and attributes
properties of the copied nodes are set so as to preserve their inter-node relationships. For the topmost node (the node directly returned by the enclosed expression), the parent
property is set to the node constructed by this constructor.
If strip
:
If the copied node is an element node, its xs:untyped
. Its nilled
, is-id
, and is-idrefs
properties are set to false
.
If the copied node is an attribute node, its type-name
property is set to xs:untypedAtomic
. Its is-idrefs
property is set to false
. Its is-id
property is set to true
if the qualified name of the attribute node is xml:id
; otherwise it is set to false
.
The Implementations that store only the string-value
of each copied element and attribute node remains unchanged, and its typed-value
becomes equal to its string-value
as an instance of xs:untypedAtomic
.
On the other hand, if preserve
, the type-name
, nilled
, string-value
, typed-value
, is-id
, and is-idrefs
properties of the copied nodes are preserved.
The in-scope-namespaces
property of a copied element node is
determined by the following rules. In applying these rules, the default
namespace or absence of a default namespace is treated like any other
namespace binding:
If preserve
, all in-scope-namespaces of the original element are
retained in the new copy.
If no-preserve
, the new copy retains only those in-scope namespaces of the original element that are used in the names of the element and its
attributes.
If inherit
, the copied node inherits all the in-scope namespaces of the constructed node, augmented and overridden by the in-scope namespaces of the original element that were preserved by the preceding rule. If no-inherit
, the copied node does not inherit any in-scope namespaces from the constructed node.
An enclosed expression in the content of an element constructor may cause one or more existing nodes to be copied. Type error
An element node is copied, and the
preserve
, and
no-preserve
.
An attribute node is copied but its parent element node is not
copied, and the preserve
.
The rationale for error
When an element or processing instruction node is copied, its base-uri
property is set to be the same as that of its new parent,
with the following exception: if a copied element node has an xml:base
attribute, its base-uri
property is set to
the value of that attribute, base-uri
property of the new parent node.
All other properties of the copied nodes are preserved.
If the content sequence contains a document node, the document node is replaced in the content sequence by its children.
Adjacent text nodes in the content sequence are merged into a single text node by concatenating their contents, with no intervening blanks. After concatenation, any text node whose content is a zero-length string is deleted from the content sequence.
If the content sequence contains an attribute node or a
namespace node following a node that is not an attribute node or a
namespace node, a
The properties of the newly constructed element node are determined as follows:
node-name
is the
parent
is set to empty.
attributes
consist of all the attributes specified in the start tag as described in parent
property of each of these attribute nodes has been set to the newly constructed element node. If two or more attributes have the same node-name
, a xml:space
has a value other than preserve
or default
, a
children
consist of all the element, text, comment, and processing
instruction nodes in the content sequence. Note that the parent
property of each of these nodes has been set to the newly constructed element node.
If the constructed node has an attribute named Otherwise,
the base-uri
is set to the following value:
xml:base
, then the value of this attribute,
in-scope-namespaces
consist of all the namespace bindings resulting from namespace declaration attributes as described in
The nilled
property is false
.
The string-value
property is equal to the concatenated contents of the text-node descendants in document order. If there are no text-node descendants, the string-value
property is a zero-length string.
The typed-value
property is equal to the string-value
property, as an instance of xs:untypedAtomic
.
If strip
, the type-name
property is xs:untyped
. On the other hand, if construction mode is preserve
, the type-name
property is xs:anyType
.
The is-id
and is-idrefs
properties are set to false
.
Example:
The constructed element node has one child, a text node containing the value "1
".
Example:
The constructed element node has one child, a text node containing the value "1 2 3
".
Example:
The constructed element node has one child, a text node containing the value "123
".
Example:
The constructed element node has one child, a text node containing the value "1 2 3
".
Example:
The constructed element node has one child, a text node containing the value "I saw 8 cats.
".
Example:
The constructed element node has one child, a text node containing the value "I saw 8 cats.
".
Example:
The constructed element node has three children: a text node containing "I saw
", a child element node named howmany
, and a text node containing " cats.
". The child element node in turn has a single text node child containing the value "8
".
In a direct element constructor, whitespace characters may appear in the content of the constructed element. In some cases, enclosed expressions and/or nested elements may be separated only by whitespace characters. For
example, in the expression below, the end-tag
</title>
and the start-tag <author>
are separated by a newline character and four space
characters:
 
or by
The strip
, boundary whitespace is not considered significant and
is discarded. On the other hand, if boundary-space policy is preserve
, boundary whitespace is
considered significant and is
preserved.
Example:
The constructed
cat
element node has two child element nodes named
breed
and color
. Whitespace surrounding
the child elements will be stripped away by the element
constructor if boundary-space policy is
strip
.
Example:
If
boundary-space policy is strip
, this example is equivalent to <a>abc</a>
. However, if
boundary-space policy is preserve
, this example is
equivalent to <a> abc </a>
.
Example:
Since the
whitespace surrounding the z
is not boundary
whitespace, it is always preserved. This example is equivalent to
<a> z abc</a>
.
Example:
This
example is equivalent to <a> abc</a>
, regardless
of the boundary-space policy, because the space generated by the
Example:
This example constructs an element containing two space characters, regardless of the boundary-space policy, because whitespace inside an enclosed expression is never considered to be boundary whitespace.
Example:
This example constructs an element containing the text one little fish
, because the array is
Element constructors treat attributes named xml:space
as ordinary attributes. An xml:space
attribute does not affect the handling of whitespace by an element constructor.
XQuery allows an expression to generate a processing instruction node or a comment node. This can be accomplished by using a
A direct processing instruction constructor creates a processing instruction node whose target
property is content
property is base-uri
property of the node is empty. The parent
property of the node is empty.
The ?>
".
The following example illustrates a direct processing instruction constructor:
A direct comment constructor creates a comment node whose content
property is parent
property is empty.
The
The following example illustrates a direct comment constructor:
A direct comment constructor is different from a
An alternative way to create nodes is by using a element
, attribute
,
document
, text
,
processing-instruction
, comment
, or
namespace
.
For those kinds of nodes that have names (element, attribute, and
processing instruction nodes), the keyword that specifies the node
kind is followed by the name of the node to be created. This name may
be specified either as an EQName or as an expression enclosed in
braces.
The following example illustrates the use of computed element and
attribute constructors in a simple case where the names of the
constructed nodes are constants. This example generates exactly the
same result as the first example in
If the keyword element
is followed by an EQName, it is expanded to an node-name
property of the constructed element node. If expansion of the QName is not successful, a
If the keyword element
is followed by a
xs:QName
, xs:string
, or xs:untypedAtomic
, a
If the atomized value of the xs:QName
, that node-name
property of the constructed
element, retaining the prefix part of the QName.
If the atomized value of the xs:string
or xs:untypedAtomic
, that value is converted to an node-name
property of the constructed
element, retaining the prefix part of the QName. If conversion of the atomized
A
Its namespace prefix is xmlns
.
Its namespace URI is http://www.w3.org/2000/xmlns/
.
Its namespace prefix is xml
and its namespace
URI is not http://www.w3.org/XML/1998/namespace
.
Its namespace prefix is other than xml
and its
namespace URI is http://www.w3.org/XML/1998/namespace
.
The
Processing of the computed element constructor proceeds as follows:
If the content sequence contains an array, it is
If the content sequence contains a document node, the document node is replaced in the content sequence by its children.
Adjacent text nodes in the content sequence are merged into a single text node by concatenating their contents, with no intervening blanks. After concatenation, any text node whose content is a zero-length string is deleted from the content sequence.
If the content
sequence contains an attribute node or a namespace node following a node that is not an
attribute node or a namespace node, a
The properties of the newly constructed element node are determined as follows:
node-name
is the
parent
is empty.
attributes
consist of all the attribute nodes in the content sequence, in parent
property of each of these attribute nodes has been set to the newly constructed element node. If two or more attributes have the same node-name
, a xml:space
has a value other than preserve
or default
, a
children
consist of all the element, text, comment, and processing
instruction nodes in the content sequence. Note that the parent
property of each of these nodes has been set to the newly constructed element node.
If the constructed node has an attribute named Otherwise,
the base-uri
is set to the following value:
xml:base
, then the value of this attribute,
in-scope-namespaces
are computed as described in
The nilled
property is false
.
The string-value
property is equal to the concatenated contents of the text-node descendants in document order.
The typed-value
property is equal to the string-value
property, as an instance of xs:untypedAtomic
.
If strip
, the type-name
property is xs:untyped
. On the other hand, if construction mode is preserve
, the type-name
property is xs:anyType
.
The is-id
and is-idrefs
properties are set to false
.
A computed element constructor might be
used to make a modified copy of an existing element. For example,
if the variable $e
is bound to an element with $e
and
with numeric content equal to twice the value of
$e
:
In this example, if $e
is
bound by the expression let $e := <length
units="inches">{5}</length>
, then the result of the
example expression is the element <length
units="inches">10</length>
.
The fn:node-name($e)
is xs:QName?
, denoting zero or one QName. Therefore, if the fn:node-name($e)
could be rewritten as fn:exactly-one(fn:node-name($e))
. If the $e
is bound to exactly one element node with numeric content.
One important
purpose of computed constructors is to allow the name of a node to
be computed. We will illustrate this feature by an expression that
translates the name of an element from one language to
another. Suppose that the variable $dict
is bound to a
dictionary
element containing a sequence of entry
elements, each of which encodes translations for a specific word. Here is an example
entry that encodes the German and Italian variants of the word "address":
Suppose further that the variable $e
is bound to the following element:
Then the following expression generates a new element in which the name of $e
has been translated into Italian and the content of $e
(including its attributes, if any) has been preserved. The first enclosed expression after the element
keyword generates the name of the element, and the second enclosed
expression generates the content and attributes:
The result of this expression is as follows:
As in the previous example, if the fn:exactly-one
function in order to avoid a static type error.
Additional examples of computed element constructors can be found
in
A computed attribute constructor creates a new attribute node, with its own node identity.
Attributes have no default namespace. The rules that expand attribute names create an
If the keyword attribute
is followed by an EQName, it is expanded to an
If the EQName has a BracedURILiteral it is expanded using the specified URI to create an
If the EQName is a
If the EQName is a
The resulting node-name
property of the
constructed attribute node. If expansion of the QName is not
successful, a
If the keyword attribute
is followed by a
xs:QName
,
xs:string
, or xs:untypedAtomic
, a
If the atomized value of the xs:QName
:
If the
The resulting node-name
property of the constructed
attribute node.
If the atomized value of the xs:string
or xs:untypedAtomic
, that
value is converted to an node-name
property of the constructed attribute. If
conversion of the atomized
A
Its namespace prefix is xmlns
.
It has no namespace prefix and its local name is
xmlns
.
Its namespace URI is http://www.w3.org/2000/xmlns/
.
Its namespace prefix is xml
and its namespace
URI is not http://www.w3.org/XML/1998/namespace
.
Its namespace prefix is other than xml
and its
namespace URI is http://www.w3.org/XML/1998/namespace
.
The
Atomization converts arrays to sequences (see
If the result of atomization is an empty sequence, the value of the attribute is the zero-length string. Otherwise, each atomic value in the atomized sequence is cast into a string.
The individual strings resulting from the previous step
are merged into a single string by concatenating them with a
single space character between each pair. The resulting string
becomes the string-value
property of the new
attribute node. The type-name
property) of the new
attribute node is xs:untypedAtomic
. The
typed-value
property of the attribute node is the
same as its string-value
, as an instance of
xs:untypedAtomic
.
The parent
property of the attribute node
is set to empty.
If the attribute name is xml:id
, then
xml:id
processing is performed as defined in xs:ID
and that its value is properly normalized. If
an error is encountered during xml:id
processing, an
implementation may raise a
If the attribute name is xml:id
, the
is-id
property of the resulting attribute node is
set to true
; otherwise the is-id
property is set to false
. The is-idrefs
property of the attribute node is unconditionally set to
false
.
If the attribute name is xml:space
and the
attribute value is other than preserve
or
default
, a
Example:
The size
attribute is
"7
" and its type is
xs:untypedAtomic
.
Example:
The name of the constructed attribute is
either husband
or
wife
. Its Hello 1 2 3
Goodbye
".
All document node constructors are computed constructors. The result of a document node constructor is a new document node, with its own node identity.
A document node constructor is useful when the result of a query is to be a document in its own right. The following example illustrates a query that returns an XML document containing a root element named author-list
:
The
If the content sequence contains a document node, the document node is replaced in the content sequence by its children.
Adjacent text nodes in the content sequence are merged into a single text node by concatenating their contents, with no intervening blanks. After concatenation, any text node whose content is a zero-length string is deleted from the content sequence.
If the content sequence contains an attribute node, a
If the content sequence contains a namespace node, a
The properties of the newly constructed document node are determined as follows:
base-uri
is
set to the
children
consist of all the element, text, comment, and processing
instruction nodes in the content sequence. Note that the parent
property of each of these nodes has been set to the newly constructed document node.
The unparsed-entities
and document-uri
properties are empty.
The string-value
property is equal to the concatenated contents of the text-node descendants in document order.
The typed-value
property is equal to the string-value
property, as an instance of xs:untypedAtomic
.
No validation is performed on the constructed document node. The
All text node constructors are computed constructors. The result of a text node constructor is a new text node, with its own node identity.
The
If the result of atomization is an empty sequence, no text node is constructed. Otherwise, each atomic value in the atomized sequence is cast into a string.
The individual strings resulting from the previous step are merged into a single string by concatenating them with a single space character between each pair. The resulting string becomes the content
property of the constructed text node.
The parent
property of the constructed text node is set to empty.
It is possible for a text node constructor to construct a text node containing a zero-length string. However, if used in the content of a constructed element or document node, such a text node will be deleted or merged with another text node.
The following example illustrates a text node constructor:
A computed processing instruction constructor (
If the keyword processing-instruction
is followed by an NCName, that NCName is used as the target
property of the constructed node. If the keyword processing-instruction
is followed by a
xs:NCName
, xs:string
, or xs:untypedAtomic
, a
If the atomized value of the xs:string
or xs:untypedAtomic
, that value is cast to the type xs:NCName
. If the value cannot be cast to xs:NCName
, a
The resulting NCName is then used as the target
property of the newly constructed processing instruction node. However, a XML
" (in any combination of upper and lower case)
The
If the result of atomization is an empty sequence, it is replaced by a zero-length string. Otherwise, each atomic value in the atomized sequence is cast into a string. If any of the resulting strings contains the string "?>
", a
The individual strings resulting from the previous step are merged into a single string by concatenating them with a single space character between each pair. Leading whitespace is removed from the resulting string. The resulting string then becomes the content
property of the constructed processing instruction node.
The remaining properties of the new processing instruction node are determined as follows:
The parent
property is empty.
The base-uri
property is empty.
The following example illustrates a computed processing instruction constructor:
The processing instruction node constructed by this example might be serialized as follows:
A computed comment constructor (
If the result of atomization is an empty sequence, it is replaced by a zero-length string. Otherwise, each atomic value in the atomized sequence is cast into a string.
The individual strings resulting from the previous step are merged into a single string by concatenating them with a single space character between each pair. The resulting string becomes the content
property of the constructed comment node.
It is a
The parent
property of the constructed comment node is set to empty.
The following example illustrates a computed comment constructor:
The comment node constructed by this example might be serialized as follows:
A computed namespace constructor creates a new namespace node, with its own node identity. The parent of the newly created namespace node is empty.
If the constructor specifies a Prefix
, it is used
as the prefix for the namespace node.
If the constructor specifies a PrefixExpr
, the
prefix expression is evaluated as follows:
PrefixExpr
.
If the result of xs:string
or xs:untypedAtomic
,
then the following rules are applied in order:
If the result is castable to xs:NCName
, then it is used as the local name
of the newly constructed namespace node. (The local name of a namespace node
represents the prefix part of the namespace binding.)
If the result is the empty sequence
or a zero-length xs:string
or xs:untypedAtomic
value,
the new namespace node has no name (such a namespace node represents a binding for the default namespace).
Otherwise, a
If the result of atomization is not an empty sequence
or a single atomic value of type xs:string
or xs:untypedAtomic
,
a type error is raised
The URIExpr
is evaluated, and the result is cast
to xs:anyURI
to create the URI
property
for the newly created node.
An implementation may raise a URIExpr
of a computed namespace constructor is not a valid instance of xs:anyURI
.
An error
Bind the prefix xml
to some namespace URI
other than http://www.w3.org/XML/1998/namespace
.
Bind a prefix other than xml
to the namespace
URI http://www.w3.org/XML/1998/namespace
.
Bind the prefix xmlns
to any namespace URI.
Bind a prefix to the namespace
URI http://www.w3.org/2000/xmlns/
.
Bind any prefix (including the empty prefix) to a zero-length namespace URI.
By itself, a computed namespace constructor has no effect on
in-scope namespaces, but if an element constructor's content
sequence contains a namespace node, the namespace binding it
represents is added to the element's
A computed namespace constructor has no effect on the statically known namespaces.
The newly created namespace node has all properties defined
for a namespace node in the data model.
Examples:
A computed namespace constructor with a prefix:
A computed namespace constructor with a prefix expression:
A computed namespace constructor with an empty prefix:
Computed namespace constructors are generally used to add to the in-scope namespaces of elements created with element constructors:
In the above example, note that the xsi
namespace binding is created for the element because it is used in an attribute name. The attribute's content is simply character data, and has no effect on namespace bindings. The computed namespace constructor ensures that the xs
binding is created.
Computed namespace constructors have no effect on the statically known
namespaces. If the prefix a is not already defined in the statically
known namespaces, the following expression results in a static error
An element node constructed by a direct or computed element
constructor has an fn:name
. Note the difference between
A namespace binding is created for each namespace declared
in the current element constructor by a
A namespace binding is created for each namespace node in the content sequence of the current element constructor.
A namespace binding is created for each namespace that is
declared in a
A namespace binding is always created to bind the prefix
xml
to the namespace URI
http://www.w3.org/XML/1998/namespace
.
For each prefix used in the name of the
constructed element or in the names of its attributes, a namespace
binding must exist.
If a namespace binding does not already exist for one of these
prefixes, a new namespace binding is created for it.
If this would result in a conflict, because it would require two
different bindings of the same prefix, then the prefix used in the
node name is changed to an arbitrary
In an element constructor, if two or more namespace bindings in the
in-scope bindings would have the same prefix, then an error is raised
if they have different URIs
The following query illustrates the in-scope namespaces of a constructed element:
The p:a
element consists of the following namespace bindings:
p = "http://example.com/ns/p"
q = "http://example.com/ns/q"
r = "http://example.com/ns/r"
xml = "http://www.w3.org/XML/1998/namespace"
The namespace bindings for p
and q
are added to the result element because their respective namespaces
are used in the names of the element and its attributes. The namespace binding r="http://example.com/ns/r"
is added to the in-scope namespaces of the constructed
element because it is defined by a
No namespace binding corresponding to f="http://example.com/ns/f"
is created, because the namespace prefix f
appears only in the query prolog and is not used in an element or attribute name of the constructed node. This namespace binding does not appear in the query result, even though it is present in the
Note that the following constructed element, if nested within a validate
expression, cannot be validated:
The constructed element will have namespace bindings for the prefixes xsi
(because it is used in a name) and xml
(because it is defined for every constructed element node). During validation of the constructed element, the validator will be unable to interpret the namespace prefix xs
because it is has no namespace binding. Validation of this constructed element could be made possible by providing a
Most modern programming languages have support for collections of
key/value pairs, which may be called maps, dictionaries, associative
arrays, hash tables, keyed lists, or objects (these are not the same
thing as objects in object-oriented systems). In XQuery 3.1, we call
these maps. Most modern programming languages also support ordered
lists of values, which may be called arrays, vectors, or sequences.
In previous versions of the language, element structures and sequences were the only complex data structures. We are adding maps and arrays to XQuery 3.1 in order to provide lightweight data structures that are easier to optimize and less complex to use for intermediate processing and to allow programs to easily combine XML processing with JSON processing.
The XQuery 3.1 specification focuses on syntax provided for maps and arrays, especially constructors and lookup.
Some of the functionality typically needed for maps and
arrays is provided in functions defined in described in
A Map is created using a
In some circumstances, it is
necessary to include whitespace before or after the
colon to ensure that this grammar is correctly parsed;
this arises for example when the
The value of the expression is a map whose entries
correspond to the key-value pairs obtained by
evaluating the successive
Each XQuery 3.1 has no operators
that can distinguish a map or array from another map or array with
the same values. Future versions of the XQuery Update Facility,
on the other hand, will expose this difference, and need to be
clear about the data model instance that is constructed. In some existing implementations that support updates via
proprietary extensions, if the xs:untypedAtomic
it is converted to
xs:string
.
If the keys in a map constructor
contain both date/time values with a timezone and date/time values
with no timezone, a dynamic error is raised The reason for this rule is that comparison of a
date/time value with timezone to one without timezone depends on
knowing the implicit timezone. If values with timezones and values
without timezones could be mixed in the same map, such a map could
become invalid when the implicit timezone changes. The rule
therefore ensures that the constraint that no two entries have the
same key applies regardless what timezone is used for the
assessment. Without this rule, for example, a map created in a
static variable could be invalid during stylesheet execution,
since the implicit timezone used during the analysis phase can
differ from that used during evaluation.xs:dateTime
,
xs:date
, xs:time
, xs:gYear
,
xs:gYearMonth
, xs:gMonth
,
xs:gMonthDay
, or xs:gDay
.
Example:
The following expression constructs a map with seven entries:
Maps can nest, and can contain any XDM value. Here is an example of a nested map with values that can be string values, numeric values, or arrays:
Unlike the
Maps are functions, and function calls can be used to look up the value associated with a key in a map. The parameter to a map function specifies the key, and the function returns the associated value.
Examples:
$weekdays("Su")
returns the Su
.
$books("Green Eggs and Ham")
returns Green Eggs and Ham
.
XQuery 3.1 also provides an alternate syntax for map and
array lookup that is more terse, supports wildcards, and allows lookup to
iterate over a sequence of maps or arrays. See
Map lookups can be chained.
Examples: (These examples assume that $b
is bound to the books map from the previous section)
The expression $b("book")("title")
returns the string Data on the Web
.
The expression $b("book")("author")
returns the array of authors.
The expression $b("book")("author")(1)("last")
returns the string Abiteboul
.
(This example combines
Values in a map can be looked up using function call syntax,
the
Maps are functions, and function call syntax can be used to look up the value associated with a key in a map.
Examples:
$weekdays("Su")
returns the Su
.
$books("Green Eggs & Ham")
returns Green Eggs & Ham
.
Map lookups can be chained.
Examples: (These examples assume that $b
is bound to the books map from the previous section)
The expression $b("book")("title")
returns the string Data on the Web
.
The expression $b("book")("author")
returns the array of authors.
The expression $b("book")("author")(1)("last")
returns the string Abiteboul
.
(This example combines an
XQuery 3.1 also provides the
Examples:
The expression $b?book?title
is equivalent to $b("book")("title")
.
The expression $b?book?author(1)?last
is equivalent to $b("book")("author")(1)("last")
.
(The map lookup operator cannot be used to look up values in arrays.)
A
Examples:
The expression $books?"Green Eggs & Ham"
is equivalent to $books("Green Eggs & Ham")
.
The expression $books?(concat("Greek Eggs ","& Ham"))
is equivalent to $books?"Green Eggs & Ham"
.
If the expression on the left of the posfix map lookup operator
evaluates to an array of maps or a sequence of maps, it performs
implicit mapping.
$sequence-of-maps?key
is equivalent to
$sequence-of-maps ! .("key")
.
$array-of-maps?key
is equivalent to
$array-of-maps=>seq() ! .("key")
$array-of-maps?* ! .("key")
.
If the expression on the left of the postfix map lookup operator
is not a map, a sequence of maps, or an array of maps,
a
Examples:
The following expression returns the sequence ( "W0342", "M0535")
.
The following expression returns the sequence ( "W0342", "M0535")
.
"W0342"?id
raises a type error.
The unary form operates on the context item, and is typically
used in predicates. The expression expr[ ?key ]
is
equivalent to the expression expr[ .("key") ]
.
If the context item is an array of maps, the unary map lookup
operator performs implicit mapping.
If the expression on the left of the postfix map lookup operator
is not a map or an array of maps,
a
Examples:
The following expression returns the map { "id" : "W0342" }
.
The following expression returns the string What were you thinking?
An array is created using an
XQuery 3.1 has no operators
that can distinguish a map or array from another map or array with
the same values. Future versions of the XQuery Update Facility,
on the other hand, will expose this difference, and need to be
clear about the data model instance that is constructed. In some existing implementations that support updates via
proprietary extensions, if a member expression evaluates to a
map or array, the member is a new map or array with the same
values. XQuery 3.1 has no operators that can distinguish a map or
array from another map or array with the same values. However, we
need to be clear about the data model instance that is constructed
so that future versions of the XQuery Update Facility update the
instances defined in this specification.
The members of a
Examples:
[ 1, 2, 5, 7 ]
creates an array with four members: 1
, 2
, 5
, and 7
.
[ (), (27, 17, 0)]
creates an array with two members: ()
and the sequence (27, 17, 0)
.
[ $x, local:items(), <tautology>It is what it is.</tautology> ]
creates an array with three members: the value of $x, the result of evaluating the function call, and a tautology element.
A
Examples:
array { $x }
creates an array with one member for each item
array { local:items() }
creates an array with one member for each item local:items()
evaluates.
array { 1, 2, 5, 7 }
creates an array with four members: 1
, 2
, 5
, and 7
.
array { (), (27, 17, 0) }
creates an array with three members: 27
, 17
, and 0
.
array{ $x, local:items(), <tautology>It is what it is.</tautology> }
creates an array with the following members: the items to which $x
is bound, followed by the items to which local:items()
evaluates, followed by a tautology element.
XQuery 3.1 does not provide explicit support for sparse arrays. Use integer-valued maps to represent sparse arrays, e.g. map { 27 : -1, 153 : 17 }
.
Arrays are functions, and function calls can be used to look up
the value associated with a key in a map. The parameter to an
array function specifies the key, and the function returns the
associated value.
The key must be
n
does not exist in the array,
[err:FOAY0001]
Examples:
[ 1, 2, 5, 7 ](4)
evaluates to 7
.
[ [1, 2, 3], [4, 5, 6]](2)
evaluates to [4, 5, 6]
.
[ [1, 2, 3], [4, 5, 6]](2)(2)
evaluates to 5
.
[ 'a', 123, <name>Robert Johnson</name> ](3)
evaluates to <name>Robert Johnson</name>
.
array { (), (27, 17, 0) }(1)
evaluates to ()
27
.
array { (), (27, 17, 0) }(2)
evaluates to (27, 17, 0)
17
.
array { "licorice", "ginger" }(20)
raises a dynamic error FOAY0001
.
XQuery 3.1 also provides an alternate syntax for map and
array lookup that is more terse, supports wildcards, and allows
lookup to iterate over a sequence of maps or arrays. See
Arrays are functions in XQuery 3.1, and the function call
$a(n)
returns the value associated with position
n
, which must be a positive integer value n
does not exist in the array,
[err:FOAY0001]
Examples:
[ 1, 2, 5, 7 ](4)
evaluates to 7
.
[ 'a', 123, <name>Robert Johnson</name> ](3)
evaluates to <name>Robert Johnson</name>
.
[ [1, 2, 3], [4, 5, 6]](2)
evaluates to [4, 5, 6]
.
array { (), (27, 17, 0) }(1)
evaluates to ()
.
array { (), (27, 17, 0) }(2)
evaluates to (27, 17, 0)
.
array { "licorice", "ginger" }(20)
raises a dynamic error FOAY0001
.
If $a
is an array, fn:seq($a)
returns a sequence constructed by concatenating the members of
the array, in order, using the comma operator. The semantics of
this function are formally defined in
It is often convenient to use the fn:seq()
. The following expressions are
equivalent.
$a=>seq()
seq($a)
If every member of the array contains exactly one item, the above expressions evaluate to the same result as $a[7]
, but if a member contains a null sequence or a sequence with multiple items, this is no longer true. Consider the following examples.
[ (), (), 1, (2, 3, 4)](1)
evaluates to (), the value of the first array member.
[ (), (), 1, (2, 3, 4)]=>seq()[1]
evaluates to 1, the first item in the sequence created by concatenating the values of the array.
[ (), (), 1, (2, 3, 4)](4)
evaluates to (2, 3, 4)
, the value of the fourth member in the array.
[ (), (), 1, (2, 3, 4)]=>seq()[4]
evaluates to 4
, the value of the fourth item in the sequence created by concatenating the values of the array.
XQuery 3.1 provides a lookup operator for maps and arrays that is more convenient for some common cases. It provides a terse syntax for simple strings as keys in maps or integers as keys in arrays, supports wildcards, and iterates over sequences of maps and arrays.
UnaryLookup returns a sequence of values selected from the
context item, which must be a map or array. If the context item is
not a map or an array,
If the KeySpecifier
is not a wildcard KS
denote the items in the sequence to which the
KeySpecifier
evaluates.
If the context item is an array, the UnaryLookup operator is equivalent to the following expression:
Unary lookup is used in predicates (e.g. $map[?name='Mike']
or with the simple mapping operator (e.g. $maps ! ?name='Mike'
). See
Examples:
?name
is equivalent to .("name")
, an appropriate lookup for a map.
?2
is equivalent to .(2)
, an appropriate lookup for an array or an integer-valued map.
?("$funky / <looking @string")
is equivalent to
.("$funky / <looking @string")
, an appropriate lookup for a map with rather odd conventions for keys.
?($a)
is equivalent to for $k in $a return .($k)
, allowing keys for an array or map to be passed using a variable.
?(2 to 4)
is equivalent to for $k in (2,3,4) return .($k)
, a convenient way to return a range of values from an array.
?(3.5)
raises a type error because the parameter must be an integer.
let $x:= <node i="3"/> return ?($x/@i)
does not raise a type error because the attribute is untyped.
But let $x:= <node i="3"/> return ?($x/@i+1)
does raise a type error
because the +
operator with an untyped operand returns a double.
([1,2,3], [1,2,5], [1,2])[?3 = 5]
raises an error because ?3
on one of the
items in the sequence fails.
If the KeySpecifier
Example:
If $m
is bound to the weekdays map described in $m?*
returns the values ("Sunday","Monday","Tuesday","Wednesday", "Thursday", "Friday","Saturday")
, in
The order of keys in map:keys() is implementation-dependent, so the order of values in the result sequence is also implementation-dependent.
If the KeySpecifier is "*" and the context item is an array, unary lookup is equivalent to the following expression:
Examples:
[1, 2, 5, 7]?*
evaluates to (1, 2, 5, 7)
.
[[1, 2, 3], [4, 5, 6]]?*
evaluates to ([1, 2, 3], [4, 5, 6])
The semantics of E?S
are equivalent to for $a in E, $b in S return $a($b)
E
is an expression on the left of the postfix ?
operator and ?S
is the unary lookup operator described in
Examples:
map { "first" : "Jenna", "last" : "Scott" }?first
evaluates to "Jenna"
[4, 5, 6]?2
evaluates to 5
.
(map {"first": "Tom"}, map {"first": "Dick"}, map {"first": "Harry"})?first
evaluates to the sequence ("Tom", "Dick", "Harry")
([1,2,3], [4,5,6])?2
evaluates to the sequence (2, 5)
.
XQuery provides a versatile expression called a FLWOR expression that may contain multiple clauses. The FLWOR expression can be used for many purposes, including iterating over sequences, joining multiple documents, and performing grouping and aggregation. The name FLWOR, pronounced "flower", is suggested by the keywords for
, let
, where
, order by
, and return
, which introduce some of the clauses used in FLWOR expressions (but this is not a complete list of such clauses.)
The complete syntax of a FLWOR expression is shown here, and relevant parts of the syntax are repeated in subsequent sections of this document.
The semantics of FLWOR expressions are based on a concept called a $x
, $y
, and $z
:
In this section, tuple streams are represented as shown in the above example. Each tuple is on a separate line and is enclosed in parentheses, and the variable bindings inside each tuple are separated by commas. This notation does not represent XQuery syntax, but is simply a representation of a tuple stream for the purpose of defining the semantics of FLWOR expressions.
Tuples and tuple streams are not part of the
Conceptually, the first clause generates a tuple stream. Each clause between the first clause and the return clause takes the tuple stream generated by the previous clause as input and generates a (possibly different) tuple stream as output. The return clause takes a tuple stream as input and, for each tuple in this tuple stream, generates an
The initial clause in a FLWOR expression may be a for
, let
, or window
clause.
Intermediate clauses may be for
, let
, window
, count
, where
, group by
, or order by
clauses. These intermediate clauses may be repeated as many times as desired, in any order. The final clause of the FLWOR expression must be a return
clause. The semantics of the various clauses are described in the following sections.
The following clauses in FLWOR expressions bind values to variables:
for
, let
, window
, count
, and group by
.
The binding of variables for for
, let
, and count
is governed by the following rules
(the binding of variables in group by
is discussed in window
clauses is discussed in
The scope of a bound variable includes all subexpressions of the containing FLWOR that appear after the variable binding. The scope does not include the expression to which the variable is bound. The following code fragment, containing two let
clauses, illustrates how variable bindings may reference variables that were bound in earlier clauses, or in earlier bindings in the same clause:
A given variable may be bound more than once in a FLWOR expression, or even within one clause of a FLWOR expression. In such a case, each new binding occludes the previous one, which becomes inaccessible in the remainder of the FLWOR expression.
as
followed by the static type of the variable, declared using the syntax in let
clause raises a $salary
has a type declaration that is not satisfied by the value that is bound to it:
for
clause or window
clause, when an expression is preceded by the keyword in
, the value of that expression is called a for
and window
clauses iterate over their binding sequences, producing multiple bindings for one or more variables. Details on how binding sequences are used in for
and window
clauses are described in the following sections.
A for
clause is used for iteration. Each variable in a for
clause iterates over a sequence and is bound in turn to each item in the sequence.
If a for
clause contains multiple variables, it is semantically equivalent to multiple for
clauses, each containing one of the variables in the original for
clause.
Example:
The clause
is semantically equivalent to:
In the remainder of this section, we define the semantics of a for
clause containing a single variable and an associated expression (following the keyword in
) whose value is called the
If a single-variable for
clause is the initial clause in a FLWOR expression, it iterates over its ordered
, the order of tuples in the tuple stream preserves the order of the
If the allowing empty
is specified. If allowing empty
is specified, the output tuple stream consists of one tuple in which the variable is bound to an empty sequence. If allowing empty
is not specified, the output tuple stream consists of zero tuples.
The following examples illustrates tuple streams that are generated by initial for
clauses:
Initial clause:
or (equivalently):
Output tuple stream:
Initial clause:
Output tuple stream contains no tuples.
Initial clause:
Output tuple stream:
at
.for
clause. In this case, as the main variable iterates over the items in its allowing empty
is specified, the positional variable in the output tuple is bound to the integer zero. Positional variables always have the implied type xs:integer
. The
The following examples illustrate how a positional variable would have affected the results of the previous examples that generated tuples:
Initial clause:
Output tuple stream:
Initial clause:
Output tuple stream:
If a single-variable for
clause is an intermediate clause in a FLWOR expression, its
Although the
For a given input tuple, if the for
clause contains no items, the result depends on whether allowing empty
is specified. If allowing empty
is specified, the input tuple generates one output tuple, with the original variable bindings plus a binding of the new variable to an empty sequence. If allowing empty
is not specified, the input tuple generates zero output tuples (it is not represented in the output tuple stream.)
If the new variable introduced by a for
clause has an associated for
clause also contain bindings for the allowing empty
is specified, the
If ordered
, the tuples in the output tuple stream are ordered primarily by the order of the input tuples from which they are derived, and secondarily by the order of the
The following examples illustrates the effects of intermediate for
clauses:
Input tuple stream:
Intermediate for
clause:
Output tuple stream (assuming ordered
):
In this example, there is no output tuple that corresponds to the input tuple ($x = 4)
because, when the for
clause is evaluated with the bindings in this input tuple, the resulting $y
is empty.
This example shows how the previous example would have been affected by a
Output tuple stream (assuming ordered
):
This example shows how the previous example would have been affected by allowing empty
. Note that allowing empty
causes the input tuple ($x = 4)
to be represented in the output tuple stream, even though the $y
contains no items for this input tuple. This example illustrates that allowing empty
in a for
clause serves a purpose similar to that of an "outer join" in a relational database query. (Assume the same input tuple stream as in the previous example.)
Output tuple stream (assuming ordered
):
This example shows how a for
clause that binds two variables is semantically equivalent to two for
clauses that bind one variable each. We assume that this for
clause occurs at the beginning of a FLWOR expression. It is equivalent to an initial single-variable for
clause that provides an input tuple stream to an intermediate single-variable for
clause.
Output tuple stream (assuming ordered
):
In the above examples, if unordered
, the output tuple streams would have consisted of the same tuples, with the same values for the
A for
clause may contain one or more as
. The semantics of
The purpose of a let
clause is to bind values to one or more variables. Each variable is bound to the result of evaluating an expression.
If a let
clause contains multiple variables, it is semantically equivalent to multiple let
clauses, each containing a single variable. For example, the clause
is semantically equivalent to the following sequence of clauses:
In the remainder of this section, we define the semantics of a let
clause containing a single variable
If a single-variable let
clause is the initial clause in a FLWOR expression, it simply binds the variable let
clause is a tuple stream consisting of one tuple with a single binding that binds
If a single-variable let
clause is an intermediate clause in a FLWOR expression, it adds a new binding for variable let
clause.
The number of tuples in the output tuple stream of an intermediate let
clause is the same as the number of tuples in the input tuple stream. The number of bindings in the output tuples is one more than the number of bindings in the input tuples, unless the input tuples already contain bindings for
A let
clause may contain one or more as
. The semantics of type declarations are defined in
The following code fragment illustrates how a for
clause and a let
clause can be used together. The for
clause produces an initial tuple stream containing a binding for variable $d
to each department number found in a given input document. The let
clause adds an additional binding to each tuple, binding variable $e
to a sequence of employees whose department number matches the value of $d
in that tuple.
Like a for
clause, a window
clause
iterates over its window
clause, each tuple represents a window.
xs:integer
xs:integer
All variables in a window
clause must have distinct names;
otherwise a
The following is an example of a window
clause that
binds nine variables to the roles listed above. In this example, the
variables are named $w
, $s
,
$spos
, $sprev
, $snext
,
$e
, $epos
, $eprev
, and
$enext
respectively. A window
clause always
binds the window variable, but typically binds only a subset of the
other variables.
Windows are
created by iterating over the items in the when
keyword is true
.
The start item of the window is an item that satisfies the only
keyword determines whether a window is
generated: if only end
is specified, then no window is
generated; otherwise, the end item is set to the last item in the
In the above example, the true
,
which causes each item in the
The scoping rules for the variables bound by a window
clause are as follows:
In the when
-expression of the
In the when
-expression of the
In the clauses of the FLWOR expression that follow the window
clause, all nine of the variables bound by the window
clause (including
In a window
clause, the keyword tumbling
or sliding
determines the way in which the starting item of each window is identified, as explained in the following sections.
If the window type is tumbling
, then windows
never overlap. The search for the start of the first window begins at the beginning of the end
clause is optional; if it is omitted, the
start
clause is applied to identify all potential
starting items in the
The following examples illustrate the use of tumbling windows.
Show non-overlapping windows of three items.
Result of the above query:
Show averages of non-overlapping three-item windows.
Result of the above query:
Show first and last items in each window of three items.
Result of the above query:
Show non-overlapping windows of up to three items (illustrates end
clause without the only
keyword).
Result of the above query:
Show non-overlapping windows of up to three items (illustrates use of start
without explicit end
).
Result of the above query:
Show non-overlapping sequences starting with a number divisible by 3.
Result of the above query:
If the window type is sliding window
, then windows may
overlap. Every item in the
The following examples illustrate the use of sliding windows.
Show windows of three items.
Result of the above query:
Show moving averages of three items.
Result of the above query:
Show overlapping windows of up to three items (illustrates end
clause without the only
keyword).
Result of the above query:
The effects of a window
clause on the tuple stream are similar to the effects of a for
clause. As described in window
clause generates zero or more windows, each of which is represented by at least one and at most nine bound variables.
If the window
clause is the initial clause in a FLWOR expression, the bound variables that describe each window become an output tuple. These tuples form the initial tuple stream that serves as input to the next clause of the FLWOR expression. If ordered
, the order of tuples in the tuple stream is the
order in which their start items appear in the
If a window
clause is an intermediate clause in a FLWOR expression, each input tuple generates zero or more output tuples, each consisting of the original bound variables of the input tuple plus the new bound variables that represent one of the generated windows. For each tuple window
clause, given the bindings in the input tuple ordered
, the order of tuples in the output stream is determined primarily by the order of the input tuples from which they were derived, and secondarily by the order in which their start items appear in the unordered
, the order of tuples in the output stream is
The following example illustrates a window
clause that is the initial clause in a FLWOR expression. The example is based on input data that consists of a sequence of closing stock prices for a specific company. For this example we assume the following input data (assume that the price
elements have a validated type of xs:decimal
):
A user wishes to find "run-ups," which are defined as sequences of dates that begin with a "low" and end with a "high" price (that is, the stock price begins to rise on the first day of the run-up, and continues to rise or remain even through the last day of the run-up.) The following query uses a tumbling window to find run-ups in the input data:
For our sample input data, this tumbling window
clause generates a tuple stream consisting of two tuples, each representing a window and containing five bound variables named $w
, $first
, $second
, $last
, and $beyond
. The return
clause is evaluated for each of these tuples, generating the following query result:
The following example illustrates a window
clause that is an intermediate clause in a FLWOR expression. In this example, the input data contains closing stock prices for several different companies, each identified by a three-letter symbol. We assume the following input data (again assuming that the type of the price
element is xs:decimal
):
As in the previous example, we want to find "run-ups," which are defined as sequences of dates that begin with a "low" and end with a "high" price for a specific company. In this example, however, the input data consists of stock prices for multiple companies. Therefore it is necessary to isolate the stock prices of each company before forming windows. This can be accomplished by an initial for
and let
clause, followed by a window
clause, as follows:
In the above example, the for
and let
clauses could be rewritten as follows:
The group by
clause is described in
The for
and let
clauses in this query generate an initial tuple stream consisting of two tuples. In the first tuple, $symbol
is bound to "ABC" and $closings
is bound to the sequence of closing
elements for company ABC. In the second tuple, $symbol
is bound to "DEF" and $closings
is bound to the sequence of closing
elements for company DEF.
The window
clause operates on this initial tuple stream, generating two windows for the first tuple and two windows for the second tuple. The result is a tuple stream consisting of four tuples, each with the following bound variables: $symbol
, $closings
, $w
, $first
, $second
, $last
, and $beyond
. The return
clause is then evaluated for each of these tuples, generating the following query result:
A where
clause serves as a filter for the tuples in its input tuple stream. The expression in the where
clause, called the true
, the tuple is retained in the output tuple stream; otherwise the tuple is discarded.
Examples:
This example illustrates the effect of a where
clause on a tuple stream:
Input tuple stream:
where
clause:
Output tuple stream:
The following query illustrates how a where
clause might be used with a
The purpose of a count
clause is to enhance the tuple
stream with a new variable that is bound, in each tuple, to the
ordinal position of that tuple in the tuple stream. The name of the
new variable is specified in the count
clause.
The output tuple stream of a count
clause is the same
as its input tuple stream, with each tuple enhanced by one additional
variable that is bound to the ordinal position of that tuple in the
tuple stream. However, if the name of the new variable is the same as
the name of an existing variable in the input tuple stream, the new
variable occludes (replaces) the existing variable of the same name,
and the number of bound variables in each tuple is unchanged.
The following examples illustrate uses of the count
clause:
This example illustrates the effect of a count
clause on an input tuple stream:
Input tuple stream:
count
clause:
Output tuple stream:
This example illustrates how a counter might be used to filter the result of a query. The query ranks products in order by decreasing sales, and returns the three products with the highest sales. Assume that the variable $products
is bound to a sequence of product
elements, each of which has name
and sales
child-elements.
The result of this query has the following structure:
A group by
clause generates an output tuple stream in which each tuple represents a group of tuples from the input tuple stream
that have equivalent grouping keys.
We will refer to the tuples in the input tuple stream as
The group by
clause assigns each pre-grouping tuple to a group, and
generates one post-grouping tuple for each group.
In the post-grouping tuple for a group, each grouping key is represented by a variable that was specified in a
A group by
clause contains one or more eq
operator on let
binding is created in the pre-grouping tuples, and the grouping variable refers to that let
binding. For example, the clause:
is semantically equivalent to the following sequence of clauses:
The process of group formation proceeds as follows:
The input tuple stream is partitioned into groups of tuples
whose grouping keys are The atomized grouping key will always be either an empty
sequence or a single atomic value. Defining equivalence by
reference to the The appropriate collation for comparing two grouping keys is the collation
specified in the pertinent A
,
B
, and C
such that A eq B
,
B eq C
, but A ne C
, then the number of
items in the result of the function (as well as the choice of which
items are returned) is NaN
is equivalent to
NaN
, that untypedAtomic values are compared as
strings, and that values for which the eq
operator
is not defined are considered
non-equivalent.
Each group of tuples produced by the above process results in one
post-grouping tuple. The pre-grouping tuples from which the group is
derived have
In the post-grouping tuple generated for a given group, each
non-grouping variable is bound to a sequence containing the
concatenated values of that variable in all the pre-grouping tuples
that were assigned to that group. If ordered
, the values derived from individual tuples are
concatenated in a way that preserves the order of the pre-grouping
tuple stream; otherwise the ordering of these values is
This behavior may be surprising to SQL programmers, since SQL reduces the equivalent of a non-grouping variable to one representative value. Consider the following query:
If there are three qualifying customers in the sales department this evaluates to:
In XQuery, each group is a sequence of items that match the group
by criteria—in a tree-structured language like XQuery, this is
convenient, because further structures can be built based on the items
in this sequence. Because there are three items in the group,
$x
evaluates to a sequence of three items. To reduce this
to one item, use fn:distinct-values()
:
In general, the
The order in which tuples appear in the
post-grouping tuple stream is
An
order by
clause can be used to impose a value-based
ordering on the post-grouping tuple stream. Similarly, if it is
desired to impose a value-based ordering within a group (i.e., on the
sequence of items bound to a non-grouping variable), this can be
accomplished by a nested FLWOR expression that iterates over these
items and applies an order by
clause. In some cases, a
value-based ordering within groups can be accomplished by applying an
order by
clause on a non-grouping variable before
applying the group by
clause.
A group
by
clause rebinds all the variables in the input tuple
stream. The scopes of these variables are not affected by the
group by
clause, but in post-grouping tuples the values
of the variables represent group properties rather than properties of
individual pre-grouping tuples.
Examples:
This example illustrates the effect of a group by
clause on a tuple stream.
Input tuple stream:
group by
clause:
Output tuple stream:
This example and the ones that follow are based on two separate sequences of elements, named $sales
and $products
. We assume that the variable $sales
is bound to a sequence of elements with the following structure:
We also assume that the variable $products
is bound to a sequence of elements with the following structure:
The simplest kind of grouping query has a single
The result of this query is a sequence of elements with the following structure:
In a more realistic example, a user might be interested in the total revenue generated by each store for each product category. Revenue depends on both the quantity sold of various items and the price of each item. The following query joins the two input sequences and groups the resulting tuples by two
The result of this query is a sequence of elements with the following structure:
The result of the previous example was a "flat" list of elements. A user might prefer the query result to be presented in the form of a hierarchical report, grouped primarily by store (in order by store number) and secondarily by product category. Within each store, the user might want to see only those product categories whose total revenue exceeds $10,000, presented in descending order by their total revenue. This report is generated by the following query:
The result of this example query has the following structure:
The following example illustrates how to avoid a possible pitfall in writing grouping queries.
In each post-grouping tuple, all variables except for the grouping
variable are bound to sequences of items derived from all the
pre-grouping tuples from which the group was formed. For instance, in
the following query, $high-price
is bound to a sequence
of items in the post-grouping tuple.
If three products in the "Men's Wear" category have prices greater than 1000, the result of this query might look (in part) like this:
The repetition of "1000" in this query result is due to the fact that $high-price
is not a $high-price
to an outer-level FLWOR expression, as follows:
The result of the revised query might contain the following element:
The purpose of an order by
clause is to impose a value-based ordering on the tuples in the tuple stream. The output tuple stream of the order by
clause contains the same tuples as its input tuple stream, but the tuples may be in a different order.
An order by
clause contains one or more ordering specifications, called xs:string
, xs:anyURI
, or types derived from them (otherwise, the
The process of evaluating and comparing the orderspecs is based on the following rules:
If the value of an orderspec has the xs:untypedAtomic
(such as character
data in a schemaless document), it is cast to the type xs:string
.
Consistently treating untyped values as strings enables the sorting process to begin without complete knowledge of the types of all the values to be sorted.
All the non-empty orderspec values must be convertible to a common type by gt
operator. If two or more non-empty orderspec values are not convertible to a common type that has a gt
operator, a
Example: The orderspec values include a value of type hatsize
, which is derived from xs:integer
, and a value of type shoesize
, which is derived from xs:decimal
. The least common type reachable by subtype substitution and type promotion is xs:decimal
.
Example: The orderspec values include a value of type xs:string
and a value of type xs:anyURI
. The least common type reachable by subtype substitution and type promotion is xs:string
.
If the resulting sequence contains values that are instances of more than one primitive type (meaning the 19 primitive types defined in
If each value is an instance of one of the types xs:string
or xs:anyURI
, then all values are cast to type xs:string
.
If each value is an instance of one of the types xs:decimal
or xs:float
, then all values are cast to type xs:float
.
If each value is an instance of one of the types xs:decimal
, xs:float
, or xs:double
, then all values are cast to type xs:double
.
Otherwise, a
The primitive type of an xs:integer
value for this purpose is xs:decimal
.
For the purpose of determining their relative position in the ordering sequence, the
When the orderspec specifies empty least
,
the following rules are applied in order:
If
If NaN
and NaN
nor an empty sequence, then
If a specific collation xs:string
or are convertible to
xs:string
by
If fn:compare(V, W, C)
is less than
zero, then
If none of the above rules apply, then:
If W gt V
is true,
then
When the orderspec specifies empty greatest
,
the following rules are applied in order:
If
If NaN
and NaN
nor an empty sequence, then
If a specific collation xs:string
or are convertible to
xs:string
by
If fn:compare(V, W, C)
is less than
zero, then
If none of the above rules apply, then:
If W gt V
is true,
then
When the orderspec specifies neither empty least
nor empty greatest
, the
empty least
or empty greatest
are used.
If
If descending
, then
If descending
, then
If neither
If stable
is specified, the original order of
If stable
is not specified, the order of
If two orderspecs return the special floating-point values positive and negative zero, neither of these values is +0.0 gt -0.0
and -0.0 gt +0.0
are both false
.
Examples:
This example illustrates the effect of an order by
clause on a tuple stream. The keyword stable
indicates that, when two tuples have equal sort keys, their order in the input tuple stream is preserved.
Input tuple stream:
order by
clause:
Output tuple stream:
The following example shows how an order by
clause can be used to sort the result of a query, even if the sort key is not included in the query result. This query returns employee names in descending order by salary, without returning the actual salaries:
Since the order by
clause in a FLWOR expression is the only facility provided by XQuery for specifying a value ordering, a FLWOR expression must be used in some queries where iteration would not otherwise be necessary. For example, a list of books with price less than 100 might be obtained by a simple $books/book[price < 100]
. But if these books are to be returned in alphabetic order by title, the query must be expressed as follows:
The return
clause is the final clause of a FLWOR expression. The return
clause is evaluated once for each tuple in its input tuple stream, using the variable bindings in the respective tuples, in the order in which these tuples appear in the input tuple stream. The results of these evaluations are concatenated, as if by the
The following example illustrates a FLWOR expression containing several clauses. The for
clause iterates over all the departments in an input document named depts.xml
, binding the variable $d
to each department in turn. For each binding of $d
, the let
clause binds variable $e
to all the employees in the given department, selected from another input document named emps.xml
(the relationship between employees and departments is represented by matching their deptno
values). Each tuple in the resulting tuple stream contains a pair of bindings for $d
and $e
($d
is bound to a department and $e
is bound to a set of employees in that department). The where
clause filters the tuple stream, retaining only those tuples that represent departments having at least ten employees. The order by
clause orders the surviving tuples in descending order by the average salary of the employees in the department. The return
clause constructs a new big-dept
element for each surviving tuple, containing the department number, headcount, and average salary.
The order in which items appear in the result of a FLWOR expression depends on the ordering of the input tuple stream to the return
clause, which in turn is influenced by order by
clauses and by
The result of this query is a sequence of assignment
elements, each containing a deptno
element and a name
element. The sequence will be ordered primarily by the deptno
values because of the order by
clause. If ordered
, subsequences of assignment
elements with equal deptno
values will be ordered by the document order of their name
elements within the emps.xml
document; otherwise the ordering of these subsequences will be
Parentheses are helpful in return
clauses that contain comma operators,
since FLWOR expressions have a higher precedence than the comma
operator. For example, the following query raises an error because
after the comma, $j
is no longer within the FLWOR expression, and is an
undefined variable:
Parentheses can be used to bring $j
into the return
clause of the FLWOR expression, as the
programmer probably intended:
The purpose of ordered
and unordered
expressions is to set the ordered
or unordered
for a certain region in a query. The specified ordering mode applies to the expression nested inside the curly braces. For expressions where the ordering of the result is not significant, a performance advantage may be realized by setting the ordering mode to unordered
, thereby granting the system flexibility to return the result in the order that it finds most efficient.
/
" or "//
" operator or an union
, intersect
, and except
expressions; the fn:id
, fn:element-with-id
, and fn:idref
functions; and certain clauses within a FLWOR expression. If ordering mode is ordered
, node sequences returned by path expressions, union
, intersect
, and except
expressions, and the fn:id
and fn:idref
functions are in
In a region of a query where ordering mode is unordered
, the result of an expression is fn:position
, fn:last
, fn:index-of
, fn:insert-before
, fn:remove
, fn:reverse
, and fn:subsequence
.
The functions fn:boolean
and fn:not
are unordered
and the argument contains at least one node and at least one atomic value (see (//a/b)[5]
will return the fifth qualifying b
-element in b
-element.
The fn:id
and fn:idref
functions are described in unordered
is a feature of XQuery rather than of the functions themselves.
The use of an unordered
expression is illustrated by the following example, which joins together two documents named parts.xml
and suppliers.xml
. The example returns the part numbers of red parts, paired with the supplier numbers of suppliers who supply these parts. If an unordered
expression were not used, the resulting list of (part number, supplier number) pairs would be required to have an ordering that is controlled primarily by the parts.xml
and secondarily by the suppliers.xml
. However, this might not be the most efficient way to process the query if the ordering of the result is not important. An XQuery implementation might be able to process the query more efficiently by using an index to find the red parts, or by using suppliers.xml
rather than parts.xml
to control the primary ordering of the result. The unordered
expression gives the query evaluator freedom to make these kinds of optimizations.
In addition to ordered
and unordered
expressions, XQuery provides a function named fn:unordered
that operates on any sequence of items and returns the same sequence in an fn:unordered
function may be thought of as giving permission for the argument expression to be materialized in whatever order the system finds most efficient. The fn:unordered
function relaxes ordering only for the sequence that is its immediate operand, whereas an unordered
expression sets the
XQuery 3.1 supports a conditional expression based on the keywords if
, then
, and else
.
The expression following the if
keyword is called the then
and else
keywords are called the
The first step in processing a conditional expression is to find
the
The value of a conditional expression is defined as follows: If the
effective boolean value of the test expression is true
, the value of the then-expression is returned. If the
effective boolean value of the test expression is false
,
the value of the else-expression is returned.
Conditional expressions have a special rule for propagating true
, the conditional expression ignores (does not raise) any dynamic errors encountered in the else-expression. In this case, since the else-expression can have no observable effect, it need not be evaluated. Similarly, if the effective value of the test expression is false
, the conditional expression ignores any
Here are some examples of conditional expressions:
In this example, the test expression is a comparison expression:
In this example, the test expression tests for the existence of an attribute
named discounted
, independently of its value:
The
In a switch
expression, the switch
keyword is followed by an expression enclosed
in parentheses, called the switch
expression consists of one or more
case
clauses, with one or more case operand
expressions
each, and a default
clause.
The first step in evaluating a switch expression is to apply
atomization to the value of the switch operand expression. If the
result is a sequence of length greater than one, a type error is
raised
The resulting value is matched against each
The
The resulting value is atomized.
If the atomized sequence has length greater than one, a type error is raised
The atomized value of the switch operand expression is compared with the
atomized value of the
Switch expressions have rules regarding the propagation of dynamic
errors that take precedence over the general rules given in
The following example shows how a switch expression might be used:
Quantified expressions support existential and universal quantification. The
value of a quantified expression is always true
or false
.
A some
or every
, followed by one or more in-clauses that are used to bind variables,
followed by the keyword satisfies
and a test expression. Each in-clause associates a variable with an
expression that returns a sequence of items, called the binding sequence for that variable. The in-clauses generate tuples of variable bindings, including a tuple for each combination of items in the binding sequences of the respective variables. Conceptually, the test expression is evaluated for each
tuple of variable bindings. Results depend on the
If the quantifier is some
, the quantified expression is true
if at least one evaluation of the test expression has the true
; otherwise the quantified expression is false
. This rule implies that, if the in-clauses generate zero binding
tuples, the value of the quantified expression is false
.
If the quantifier is every
, the quantified expression is true
if every evaluation of the test expression has the true
; otherwise the quantified expression is false
. This rule implies that, if the in-clauses generate zero binding
tuples, the value of the quantified
expression is true
.
The scope of a variable bound in a quantified expression comprises all subexpressions of the quantified expression that appear after the variable binding. The scope does not include the expression to which the variable is bound.
Each variable bound in an in-clause of a quantified expression may have an optional
The order in which test expressions are evaluated for the various binding
tuples is some
, an implementation may
return true
as soon as it finds one binding tuple for which the test expression has
an true
, and it may raise a every
, an implementation may return false
as soon as it finds one binding tuple for which the test expression has
an false
, and it may raise a
Here are some examples of quantified expressions:
This expression is true
if every part
element has a discounted
attribute (regardless of the values of these attributes):
This expression is true
if at least
one employee
element satisfies the given comparison expression:
In the following examples, each quantified expression evaluates its test
expression over nine tuples of variable bindings, formed from the Cartesian
product of the sequences (1, 2, 3)
and (2, 3, 4)
. The expression beginning with some
evaluates to true
, and the expression beginning with every
evaluates to false
.
This quantified expression may either return true
or raise a true
for one variable binding
and raises a
This quantified expression may either return false
or raise a false
for one variable binding and raises a
This quantified expression contains a true
or raise a
The try/catch expression provides error handling for dynamic errors
and type errors raised during dynamic evaluation, including errors
raised by the XQuery implementation and errors explicitly raised in a
query using the fn:error()
function.
A try/catch expression catches try
clause. If the target expression does not raise a
dynamic error or a type error, the result of the
try/catch expression is the result of the target
expression.
If the target expression raises a dynamic error or
a type error, the result of the try/catch expression
is obtained by evaluating the first catch
clause that "matches" the error value, as described
below.
If no catch clause "matches" the
error value, then the try/catch expression raises the
error that was raised by the target
expression.
A catch
clause with one or more
NameTests matches any error whose error code matches
one of these NameTests. For instance, if the error
code is err:FOER0000
, then it matches a
catch
clause whose ErrorList is
err:FOER0000 | err:FOER0001
. Wildcards
may be used in NameTests; thus, the error code
err:FOER0000
also matches a
catch
clause whose ErrorList is
err:*
or *:FOER0000
or
*
.
Within the scope of the catch
clause, a
number of variables are implicitly declared, giving
information about the error that occurred. These
variables are initialized as described in the following
table:
Variable | Type | Value |
---|---|---|
err:code | xs:QName | The error code |
err:description | xs:string? | A description of the error condition; an empty sequence
if no description is available (for example, if the |
err:value | item()* | Value associated with the error. For an error raised by
calling the |
err:module | xs:string? | The URI (or system ID) of the module containing the expression where the error occurred, or an empty sequence if the information is not available. |
err:line-number | xs:integer? | The line number within the stylesheet module of the
instruction where the error occurred, or an empty sequence if the information
is not available. The value |
err:column-number | xs:integer? | The column number within the stylesheet module of the
instruction where the error occurred, or an empty sequence if the information
is not available. The value |
err:additional | item()* |
|
Try/catch expressions have a special rule for propagating dynamic errors. The try/catch expression ignores any dynamic errors encountered in catch clauses other than the first catch clause that matches an error raised by the try clause, and these catch clause expressions need not be evaluated.
Static errors are not caught by the try/catch expression.
If a function call occurs within a try
clause,
errors raised by evaluating the corresponding function are caught by the try/catch
expression. If a variable reference is used in a try
clause, errors raised by binding a value to the variable are not
caught unless the binding expression occurs within the try
clause.
The presence of a try/catch expression does not prevent an implementation from using a lazy evaluation strategy, nor does it prevent an optimizer performing expression rewrites. However, if the evaluation of an expression inside a try/catch is rewritten or deferred in this way, it must take its try/catch context with it. Similarly, expressions that were written outside the try/catch expression may be evaluated inside the try/catch, but only if they retain their original try/catch behavior. The presence of a try/catch does not change the rules that allow the processor to evaluate expressions in such a way that may avoid the detection of some errors.
Here are some examples of try/catch expressions.
A try/catch expression without a CatchErrorList catches any error:
The CatchErrorList in this try/catch expression specifies that only err:FORG0001
is caught:
The CatchErrorList in this try/catch expression specifies that errors err:FORG0001
and err:XPTY0004
are caught:
In some implementations, err:XPTY0004
is detected during static
evaluation; it can only be caught if it is raised during dynamic evaluation.
This try/catch expression shows how to return information about the error using implicitly defined error variables. Since the CatchErrorList is a wildcard, it catches any error:
Errors raised by using the result of a try/catch expression are not caught, since they are outside the scope of the try
expression.
In this example, the try block succeeds, returning the string "oops", which is not a valid argument to the function.
instance of
, typeswitch
,cast
, castable
, and treat
expressions.
The boolean
operator instance of
returns true
if the value of its first operand matches
the false
. For example:
5 instance of xs:integer
This example returns true
because the given value is an instance of the given type.
5 instance of xs:decimal
This example returns true
because the given value is an integer literal, and xs:integer
is derived by restriction from xs:decimal
.
<a>{5}</a> instance of xs:integer
This example returns false
because the given value is an element rather than an integer.
(5, 6) instance of xs:integer+
This example returns true
because the given sequence contains two integers, and is a valid instance of the specified type.
. instance of element()
This example returns true
if the context item is an element node or false
if the context item is defined but is not an element node.
If the context item is
The
In a typeswitch
expression, the
typeswitch
keyword is followed by an expression enclosed
in parentheses, called the typeswitch
expression consists of one or more
case
clauses and a default
clause.
Each case
clause specifies one or more
return
expression. typeswitch
expression is the first case
clause in which the value of the operand expression matches a case
clause, using the rules of typeswitch
expression is the value of
the return
expression in the effective case. If the value
of the operand expression does not match any case
clause, the value of the typeswitch
expression is the
value of the return
expression in the
default
clause.
In a case
or
default
clause, if the value to be returned depends on
the value of the operand expression, the clause must specify a
variable name. Within the return
expression of the
case
or default
clause, this variable name
is bound to the value of the operand expression.
Inside a case
clause, the default
clause, the static type of the variable is the
same as the static type of the operand expression.
If the value to be returned by a case
or
default
clause does not depend on the value of the
operand expression, the clause need not specify a variable.
The
scope of a variable binding in a case
or
default
clause comprises that clause. It is not an error
for more than one case
or default
clause in
the same typeswitch
expression to bind variables with the
same name.
A special rule applies to propagation of typeswitch
expressions. A typeswitch
expression ignores (does not raise) any dynamic errors encountered in case
clauses other than the default
clause are raised only if there is no
The following example shows how a typeswitch
expression might
be used to process an expression in a way that depends on its
The following example shows a union of sequence types in a single case:
Occasionally
it is necessary to convert a value to a specific datatype. For this
purpose, XQuery 3.1 provides a cast
expression that
creates a new value of a specific type based on an existing value. A
cast
expression takes two operands: an xs:NOTATION
, xs:anySimpleType
,
or xs:anyAtomicType
?
" denotes that an empty
sequence is permitted. If the target type is a lexical QName that has no namespace prefix, it
is considered to be in the
Casting a node to xs:QName
can cause surprises because it uses the static context of the cast expression to provide the namespace bindings for this operation.
Instead of casting to xs:QName
, it is generally preferable to use the fn:QName
function, which allows the namespace context to be taken from the document containing the QName.
The semantics of the cast
expression
are as follows:
The input expression is evaluated.
The result of the first step is
If the result of atomization is a
sequence of more than one atomic value, a
If the result of atomization is an empty sequence:
If
?
is specified after the target type, the result of the
cast
expression is an empty sequence.
If ?
is not specified after the target type, a
If the result of atomization is a single atomic value, the result
of the cast expression depends on the input type and the target
type. In general, the cast expression attempts to create a new value
of the target type based on the input value. Only certain combinations
of input type and target type are supported. A summary of the rules
are listed below—the normative definition of these rules is
given in
cast
is supported for the combinations of
input type and target type listed in xs:string
can be cast into the
schema type xs:decimal
. For each of these built-in combinations,
the semantics of casting are specified in
cast
is
supported if the input type is a non-primitive atomic type that is derived by restriction from the target
type. In this case, the input value
is mapped into the value space of the target type, unchanged except
for its type. For example, if shoesize
is derived by
restriction from xs:integer
, a value of type
shoesize
can be cast into the schema type
xs:integer
.
cast
is supported if the target type is a
non-primitive atomic type and the input type is
xs:string
or xs:untypedAtomic
. The
input value is first converted to a value in the lexical space of
the target type by applying the whitespace normalization rules
for the target type (as defined in
cast
is supported to any target type
if the input type is xs:string
or
xs:untypedAtomic
. The target type may be an atomic
type, a union type, or a list type. The semantics are based on
the rules for validation in
The effect of casting a string S to a simple type T is the same as constructing an element or attribute node whose string value is S, validating it using T as the governing type, and atomizing the resulting node. The result may be a single atomic value or (if list types are involved) a sequence of zero or more atomic values.
If the target type is
cast
is supported if
the target type is a non-primitive atomic type that is derived by restriction from the input type. The input value must satisfy all the
facets of the target type (in the case of the pattern facet, this is
checked by generating a string representation of the input value,
using the rules for casting to xs:string
). The resulting
value is the same as the input value, but with a different
If a primitive type P1 can be cast into a primitive type P2, then any type derived by restriction from P1 can be cast into any type derived by restriction from P2, provided that the facets of the target type are satisfied. First the input value is cast to P1 using rule (b) above. Next, the value of type P1 is cast to the type P2, using rule (a) above. Finally, the value of type P2 is cast to the target type, using rule (d) above.
For any combination of input
type and target type that is not in the above list, a
cast
expression raises a
If casting from the input type to the target type is supported but nevertheless it is not possible to cast the input value into the value space of the target type, a "2003-02-31" cast as xs:date
would raise a
XQuery 3.1
provides an expression that tests whether a given value
is castable into a given target type.
The SimpleTypeName must be the name of a type defined
in the simple
xs:NOTATION
, xs:anySimpleType
, or xs:anyAtomicType
?
" denotes that an empty
sequence is permitted.
The expression E castable as T
returns true
if the result of evaluating E
can be successfully cast into the target type T
by using a cast
expression;
otherwise it returns false
.
If evaluation of E
fails with a dynamic error,
the castable
expression as a whole fails.
The castable
expression can be used as a
For every xs:NOTATION
and xs:anyAtomicType
, which are not instantiable), a
T($arg)
are defined to be equivalent to the expression (($arg) cast as T?)
.
The following examples illustrate the use of constructor functions:
This
example is equivalent to ("2000-01-01" cast as
xs:date?)
.
This
example is equivalent to
(($floatvalue * 0.2E-5) cast as xs:decimal?)
.
This example returns an
xs:dayTimeDuration
value equal to 21 days. It is
equivalent to ("P21D" cast as xs:dayTimeDuration?)
.
If
usa:zipcode
is a user-defined atomic type
in the ("12345" cast as
usa:zipcode?)
.
An instance of an atomic type that is not in a namespace can be constructed in either of the following ways:
By using a cast
expression, if the
By using a constructor function, if the
XQuery 3.1 provides an
expression called treat
that can be used to modify the
Like cast
, the treat
expression takes two operands: an expression and a cast
, however, treat
does not change the
treat
is to ensure that an expression has an expected
dynamic type at evaluation time.
The semantics of expr1
treat as
type1
During static analysis:
The
treat
expression is type1
type1
During expression evaluation:
If expr1
type1
treat
expression returns the value of
expr1
expr1
treat
expression ensures that the value of
its expression operand conforms to the expected type at
run-time.
Example:
The
$myaddress
may be element(*, Address)
, a
less specific type than element(*, USAddress)
. However,
at run-time, the value of $myaddress
must match the type
element(*, USAddress)
using rules for
!
)The simple map operator "!
" is used for simple mappings. Both its left-hand side expression and its right-hand-side expression may return a mixed sequence of nodes and non-nodes.
Each operation E1!E2
is evaluated as follows: Expression E1
is evaluated to a sequence S
. Each item in S
then serves in turn to provide an inner focus (the item as the context item, its position in S
as the context position, the length of S
as the context size) for an evaluation of E2
in the E2
are combined as follows: Every evaluation of E2
returns a (possibly empty) sequence of items. These sequences are concatenated and returned. If ordering mode is ordered, the returned sequence preserves the orderings within and among the subsequences generated by the evaluations of E2
; otherwise the order of the returned sequence is implementation-dependent.
Simple map operators have functionality similar to
Operator | Path operator (E1 / E2 ) | Simple map operator (E1 ! E2 ) |
---|---|---|
E1 | Any sequence of nodes | Any sequence of items |
E2 | Either a sequence of nodes or a sequence of non-node items | A sequence of items |
Additional processing | Duplicate elimination and document ordering | Simple sequence concatenation |
The following examples illustrate the use of simple map operators combined with path expressions.
child::div1 / child::para / string() ! concat("id-", .)
Selects the para
element children of the div1
element children of the context node; that is, the para
element grandchildren of the context node that have div1
parents. It then outputs the strings obtained by prepending "id-"
to each of the string values of these grandchildren.
$emp ! (@first, @middle, @last)
Returns the values of the attributes first
, middle
, and last
for element $emp
, in the order given. (The /
operator here returns the attributes in an unpredictable order.)
$docs ! ( //employee)
Returns all the employees within all the documents identified by the variable docs, in document order within each document, but retaining the order of documents.
avg( //employee / salary ! translate(., '$', '') ! number(.))
Returns the average salary of the employees, having converted the salary to a number by removing any $
sign and then converting to a number. (The second occurrence of !
could not be written as /
because the left-hand operand of /
cannot be an atomic value.)
A validate
expression can be used to validate a
document node or an element node with respect to the validate
expression does not evaluate to
exactly one document or element node, a validate
expression is called the
A validate
expression returns a new node with its own identity and with no parent.
The new node and its descendants are given
A validate
expression may optionally specify a strict
.
A validate
expression may optionally specify a
The result of a validate
expression is defined by the following rules.
If the operand node is a document node, its children must
consist of exactly one element node and zero or more comment and
processing instruction nodes, in any order; otherwise, a
The operand node is converted to an XML Information Set
(
If a type name is provided, and the type name is xs:untyped
, all elements receive the type annotation xs:untyped
,
and all attributes receive the type annotation xs:untypedAtomic
.
If the type name is xs:untypedAtomic
, the node receives the type annotation xs:untypedAtomic;
a type error processor-stipulated type definition
for validation.
When no type name is provided:
If strict
, then there must be a
top-level element declaration in the
If lax
, then schema-validity
assessment is carried out in accordance with
If lax
and the root element
information item has neither a top-level element
declaration nor an xsi:type
attribute, validate
expression, this
recursive checking is required.
If the operand node is an element node, the validation rules named "Validation Root Valid (ID/IDREF)" are not applied. This means that document-level constraints relating to uniqueness and referential integrity are not enforced.
There is no check that the document contains unparsed entities whose names match the
values of nodes of type xs:ENTITY
or xs:ENTITIES
.
Validity assessment is affected by the presence or absence of xsi:type
attributes
on the elements being validated, and may generate new information items such as default attributes.
The outcome of the validation expression depends on the
validity
property of the root element information item in the PSVI that results
from the validation process.
If the validity
property of the root element
information item is valid
,
or if lax
and the validity
property of the root
element information item is notKnown
,
the PSVI is converted back into an validate
expression.
Otherwise, a
The effect of these rules is as follows, where the If If If a type name is specified in the validate expression, no attempt is
made to locate an element declaration matching the name of the validated
element; the element can have any name, and its content is validated against
the named type.
strict
,
the validated element must have a top-level element declaration in the effective schema, and must conform to this
declaration.lax
, the validated element must conform
to its top-level element declaration if such a declaration exists in the effective schema. If
lax
and there is no top-level element declaration for the
element, and the element has an xsi:type
attribute, then the
xsi:type
attribute must name a top-level type definition in the
effective schema, and the element must conform to that type.
During conversion of the PSVI into an notKnown
are
converted into element nodes with xs:anyType
, and any attribute information items whose validity property is
notKnown
are converted into attribute nodes with xs:untypedAtomic
, as described in
An extension expression consists of one or more (#
and #)
, and consists of an identifying EQName followed by #)
. If the EQName of a
pragma is a
Since there is no default namespace for
pragmas, a pragma's EQName must provide a
Each implementation recognizes an
If the namespace URI of a pragma's
If an implementation recognizes the namespace of one or more pragmas in an
It is a
If an implementation recognizes a pragma, it must report any static
errors in the following expression even if it will not evaluate that
expression (however, static type errors are raised only if the
The following examples illustrate three ways in which extension expressions might be used.
A pragma can be used to furnish a hint for how to evaluate the following expression, without actually changing the result. For example:
An implementation that recognizes the exq:use-index
pragma might use an
index to evaluate the expression that follows. An implementation that
does not recognize this pragma would evaluate the expression in its normal
way.
A pragma might be used to modify the semantics of the following
expression in ways that would not (in the absence of the pragma) be
conformant with this specification. For example, a pragma might be used to
permit comparison of xs:duration
values using implementation-defined
semantics (this would normally be an error). Such changes to the language
semantics must be scoped to the expression contained within the curly
braces following the pragma.
A pragma might contain syntactic constructs that are evaluated in place of the following expression. In this case, the following expression itself (if it is present) provides a fallback for use by implementations that do not recognize the pragma. For example:
Here an implementation that recognizes the pragma will return the result of
evaluating the proprietary syntax exq:distinct //city by
@country
,
while an implementation that does not recognize the pragma will instead
return the result of the expression //city[not(@country =
preceding::city/@country)]
. If no fallback expression is required, or
if none is feasible, then the expression between the curly braces may be
omitted, in which case implementations that do not recognize the pragma will
raise a
A query can be assembled from one or more fragments called
The XQuery syntax does not allow a
The first part of the Prolog consists of setters, imports, namespace declarations, and default
namespace declarations.
The second part of the Prolog consists of declarations of variables, functions, and options. These declarations appear at the end of the Prolog because they may be affected by declarations and imports in the first part of the Prolog.
Process the module using the specification of the XQuery version identified in the
version declaration. Process the module using the specification of XQuery
An implementation may issue a warning in this
case. Raise a static error In general, this should be done only if a
processor is not able to evaluate such a query.
encoding
is an encoding name, and must
conform to the definition of EncName
specified in UTF-8
", "UTF-16
", or "US-ASCII
".
The handling of an encoding declaration is
If a version declaration is present, no The effect of a Comment before the end of a version declaration is
implementation-dependent because it may suppress query processing by interfering with
detection of the encoding declaration.
The following examples illustrate version declarations:
module
and contains a namespace prefix and a
The namespace prefix specified in a module declaration must not be xml
or
xmlns
Any
The following is an example of a module declaration:
preserve
, boundary whitespace is preserved. If boundary-space policy is
strip
, boundary whitespace is stripped (deleted). A further discussion of
whitespace in constructed elements can be found in
The following example illustrates a boundary-space declaration:
If a Prolog contains more than one boundary-space declaration, a
gt
operator on strings is defined by a
call to the fn:compare
function, which takes an optional collation parameter.
Since the gt
operator does not specify a collation, the fn:compare
function implements gt
by using the default collation.
If neither the implementation nor the Prolog specifies a default collation, the Unicode
codepoint collation (http://www.w3.org/2005/xpath-functions/collation/codepoint
)
is used.
The following example illustrates a default collation declaration:
If a default collation declaration specifies a collation by a relative URI, that relative URI
is
fn:doc
function.
As discussed in the definition of
The following is an example of a base URI declaration:
If a Prolog contains more than one base URI declaration, a
In the terminology of ../data/
, and the query is contained in a file whose URI is
file:///C:/temp/queries/query.xq
, then the file:///C:/temp/data/
.
It is not intrinsically an error if this process fails to establish an absolute base URI;
however, the
preserve
, the type of a constructed element node is xs:anyType
,
and all attribute and element nodes copied during node construction retain their original
types. If construction mode is strip
, the type of a constructed element node is
xs:untyped
; all element nodes copied during node construction receive the type
xs:untyped
, and all attribute nodes copied during node construction receive the
type xs:untypedAtomic
.
The following example illustrates a construction declaration:
If a Prolog specifies more than one construction declaration, a
ordered
or unordered
expression.
The following example illustrates an ordering mode declaration:
If a Prolog contains more than one ordering mode declaration, a
NaN
values as ordering keys in an order by
clause in a FLWOR expression.order by
clause may
override the default order for empty sequences by specifying empty greatest
or
empty least
.
The following example illustrates an empty order declaration:
If a Prolog contains more than one empty order declaration, a
It is important to distinguish an order by
clause is present, and
specifies how empty sequences are treated by the order by
clause (unless
overridden). An order by
clause.
The following example illustrates a copy-namespaces declaration:
If a Prolog contains more than one copy-namespaces declaration, a
fn:format-number()
functionfn:format-number()
properties is discussed in
It is a
The following query formats numbers using two different decimal format declarations:
The output of this query is:
The namespace prefix specified in a schema import must not be xml
or
xmlns
The first at
keyword are optional location hints, and can be interpreted or disregarded in an
implementation-dependent way. Multiple location hints might be used to indicate more than one
possible place to look for the schema or multiple physical resources to be assembled to form
the schema.
A schema import that specifies a zero-length string as target namespace is considered to
import a schema that has no target namespace. Such a schema import must not bind a namespace
prefix
It is a http://www.w3.org/2001/XMLSchema
(predeclared prefix xs
), even
though the built-in types defined in this schema are implicitly included in the
It is a
The following example imports a schema, specifying both its target namespace and its
location, and binding the prefix soap
to the target namespace:
The following example imports a schema by specifying only its target namespace, and makes it the default element/type namespace:
The following example imports a schema that has no target namespace, providing a location hint, and sets the default element/type namespace to "no namespace" so that the definitions in the imported schema can be referenced:
The following example imports a schema that has no target namespace and sets the default element/type namespace to "no namespace". Since no location hint is provided, it is up to the implementation to find the schema to be imported.
If a module A
imports module B
, the static context of module
A
will contain the B
, and the dynamic context of module A
will contain the
B
, with the
exception of non-public functions and variables, and of the functions and variables not
declared directly in B
.
The following example illustrates a module import:
If a query imports the same module via multiple paths, only one instance of the module is imported. Because only one instance of a module is imported, there is only one instance of each variable declared in a module's prolog.
A module may import its own target namespace (this is interpreted as importing an
The namespace prefix specified in a module import must not be xml
or
xmlns
The first at
keyword are optional location hints,
and can be interpreted or disregarded in an
It is a eq
operator)
Each
A module import does not import schema definitions from the imported module. In the
following query, the type geometry:triangle is not defined, even if it is known in the
imported module, so the variable declaration raises an error
Without the type declaration for the variable, the variable declaration succeeds:
Importing the schema that defines the type of the variable, the variable declaration succeeds:
The target namespace of a module should be treated in the same way as other namespace URIs.
To maximize interoperability, query authors should use a string that is a valid absolute IRI.
Implementions must accept any string of Unicode characters. Target namespace URIs are compared using the Unicode codepoint collation rather than any concept of semantic equivalence.
Implementations may provide mechanisms allowing the target namespace URI to be used as input to a process that delivers the module as a resource, for example a catalog, module repository, or URI resolver. For interoperability, such mechanisms should not prevent the user from choosing an arbitrary URI for naming a module.
Similarly, implementations may perform syntactic transformations on the target namespace URI to obtain the names of related resources, for example to implement a convention relating the name or location of compiled code to the target namespace URI; but again, such mechanisms should not prevent the user from choosing an arbitrary target namespace URI.
As with other namespace URIs, it is common practice to use target namespace URIs whose scheme is "http" and whose authority part uses a DNS domain name under the control of the user.
The specifications allow, and some users might consider it good practice, for the target namespace URI of a function library to be the same as the namespace URI of the XML vocabulary manipulated by the functions in that library.
Several different modules with the same target namespace can be used in the same query. The
names of public variables and public functions must be unique within the
If one module contains an "import module" declaration with the target namespace
M
, then all public variables and public functions in the contexts of modules
whose target namespace is M
must be accessible in the importing module,
regardless whether the participation of the imported module was directly due to this "import
module" declaration.
The term "location URIs" refers to the URIs in the "at" clause of an "import module" declaration.
Products should (by default or at user option) take account of all the location URIs in an "import module" declaration, treating each location URI as a reference to a module with the specified target namespace URI. Location URIs should be made absolute with respect to the static base URI of the module containing the "import module" declaration where they appear. The mapping from location URIs to module source code or compiled code MAY be done in any way convenient to the implementation. If possible given the product's architecture, security requirements, etc, the product should allow this to fetch the source code of the module to use the standard web mechanisms for dereferencing URIs in standard schemes such as the "http" URI scheme.
When the same absolutized location URI is used more than once, either in the same "import module" declaration or in different "import module" declarations within the same query, a single copy of the resource containing the module is loaded. When different absolutized location URIs are used, each results in a single module being loaded, unless the implementation is able to determine that the different URIs are references to the same resource. No error due to duplicate variable or functions names should arise from the same module being imported more than once, so long as the absolute location URI is the same in each case.
Implementations must report a static error if a location URI cannot be resolved after all available recovery strategies have been exhausted.
Implementations must resolve cycles in the import graph, either at the level of target namespace URIs or at the level of location URIs, and ensure that each module is imported only once.
If the URILiteral part of a namespace declaration is a zero-length string, any existing
namespace binding for the given prefix is removed from the local
.
The following query illustrates a namespace declaration:
In the query result, the newly created node is in the namespace associated with the namespace
URI http://example.org
.
The namespace prefix specified in a namespace declaration must not be xml
or
xmlns
http://www.w3.org/XML/1998/namespace
or
http://www.w3.org/2000/xmlns/
It is a
XQuery has several predeclared namespace prefixes that are present in the xml
must not be redeclared, and no other prefix may be bound to the namespace
URI associated with the prefix xml
xml = http://www.w3.org/XML/1998/namespace
xs = http://www.w3.org/2001/XMLSchema
xsi = http://www.w3.org/2001/XMLSchema-instance
fn = http://www.w3.org/2005/xpath-functions
local = http://www.w3.org/2005/xquery-local-functions
(see
Additional predeclared namespace prefixes may be added to the
When element or attribute names are compared, they are considered identical if the local parts and namespace URIs match on a codepoint basis. Namespace prefixes need not be identical for two names to match, as illustrated by the following example:
Although the namespace prefixes xx
and foo
differ, both are bound
to the namespace URI http://example.org
. Since xx:bing
and
foo:bing
have the same local name and the same namespace URI, they match. The
output of the above query is as follows.
The namespace URI specified in a default namespace declaration must not be
http://www.w3.org/XML/1998/namespace
or
http://www.w3.org/2000/xmlns/
The following kinds of default namespace declarations are supported:
A
A default element/type namespace declaration may be overridden by a
If no default element/type namespace declaration is present, unprefixed element and type
names are in no namespace (however, an implementation may define a different default as
specified in
A
If no default function namespace declaration is present, the default function namespace
is the namespace of XPath/XQuery functions,
http://www.w3.org/2005/xpath-functions
(however, an implementation may
define a different default as specified in
The following example illustrates the declaration of a default function namespace:
The effect of declaring a default function namespace is that all functions in the default
function namespace, including implicitly-declared
Only
Unprefixed attribute names and variable names are in no namespace.
XQuery uses annotations to declare properties associated with functions (inline or declared
in the prolog) and variables. For instance, a function may be declared %public
or
%private
. The semantics associated with these properties are described in
Annotations are (QName, value)
pairs. If the EQName of the annotation is a
http://www.w3.org/2012/xquery
namespace.
eg
prefix is bound to a namespace
associated with a particular implementation, it could define an annotation like
eg:sequential
. Implementations must not define annotations in the following
reserved namespaces; it
http://www.w3.org/XML/1998/namespace
http://www.w3.org/2001/XMLSchema
http://www.w3.org/2001/XMLSchema-instance
http://www.w3.org/2005/xpath-functions
http://www.w3.org/2005/xpath-functions/math
http://www.w3.org/2012/xquery
An annotation can provide values explicitly using a parenthesized list of %java:method("java.lang.Math.sin")
sets the value of the
java:method
annotation to the string value java.lang.Math.sin
.
A
A
During static analysis, a variable declaration causes a pair (expanded QName N, type
T)
to be added to the VarName
. If N is equal (as
defined by the eq operator) to the expanded QName of another variable in in-scope variables, a
All variable names declared in a library module must (when expanded) be in the target
namespace of the library module %private
or %public
(which is the default). %private
annotation. A
private variable is hidden from %private
annotation. A public variable is accessible to
%public
and %private
annotations in a main module is not an
error, but it does not affect module imports, since a main module cannot be imported. It is
a %private
and a %public
annotation, more than one
%private
annotation, or more than one %public
annotation.
Variable names that have no namespace prefix are in no namespace. Variable declarations that have no namespace prefix may appear only in a main module.
Here are some examples of variable declarations:
The following declaration specifies both the type and the value of a variable. This
declaration causes the type xs:integer
to be associated with variable
$x
in the 7
to be associated with variable $x
in the
The following declaration specifies a value but not a type. The $x
has a static type of
xs:decimal
, inferred from its value which is 7.5.
The following declaration specifies a type but not a value. The keyword
external
indicates that the value of the variable will be provided by the
external environment. At evaluation time, if the variable $x
in the xs:integer
, a
The following declaration specifies neither a type nor a value. It simply declares that
the query depends on the existence of a variable named $x
, whose type and
value will be provided by the external environment. During query analysis, the type of
$x
is considered to be item()*
. During query evaluation, the
$x
, and its value must be compatible with its type.
The following declaration, which might appear in a library module, declares a variable whose name includes a namespace prefix:
This is an example of an external variable declaration that provides a
VarDefaultValue
:
The syntax for variable declarations allows annotations, but XQuery 3.0 does not define annotations that apply to variable declarations. An implementation can provide annotations it needs. For instance, an implemenation that supports volatile external variables might allow them to be declared using an annotation:
The type of the declared variable is as follows:
If TypeDeclaration
is present, then the SequenceType
in the
TypeDeclaration
; otherwise
If the Static Typing Feature is in effect and VarValue
is present, then the
static type inferred from static analysis of the expression VarValue
;
Type inference might not be computable until after the check for circular dependencies, described below, is complete.
Otherwise, item()*
.
VarValue
or VarDefaultValue
),
the expression is called an
In a module's dynamic context, a variable value (or the context item) may
In the following example, the value of variable $a
$b
because the evaluation of $a's initializing expression accesses the value of $b during the
evaluation of local:f()
.
A directed graph can be built with all variable values and the context item as nodes, and
with the
During query evaluation, each variable declaration causes a pair (expanded QName N,
value V)
to be added to the VarName
. The value V is as
follows:
If VarValue
is specified, then V is the result of evaluating
VarValue
as described below.
If external
is specified, then:
if a value is provided for the variable by the external environment, then V is that value. The means by which typed values of external variables are provided by the external environment is implementation-defined.
if no value is provided for the variable by the external environment, and
VarDefaultValue
is specified, then V is the result of evaluating
VarDefaultValue
as described below.
If no value is provided for the variable by the external environment, and
VarDefaultValue
is not specified, then a
It is implementation-dependent whether this error is raised if the evaluation of the query does not reference the value of the variable.
In all cases the value V must match the type T according to the rules for SequenceType
matching; otherwise a
If VarValue
or VarDefaultValue
is evaluated, the static and dynamic
contexts for the evaluation are the current module's static and dynamic context.
A context item declaration allows a query to specify the
Only the main module can set the value of the
In every module that does not contain a context item declaration, the effect is as if the declaration
appeared in that module.
During static analysis, the context item declaration has the effect of setting the context
item static type T
in the static context. The context item static type is set to
ItemType
if specified, or to item()
otherwise.
If a module contains more than one context item declaration, a static error is raised
The static context for an initializing expression includes all functions, variables, and namespaces that are declared or imported anywhere in the Prolog.
During query evaluation, a QueryBody
in the main
module, and for the initializing expression of every variable declaration in every module,
selecting the context item for the singleton focus as follows:
If VarValue
is specified, then the result of evaluating
VarValue
.
If external
is specified, then:
if a value is provided for the context item by the external environment, then that value.
The means by which an external value is provided by the external environment is implementation-defined.
if no value is provided for the context item by the external environment, and
VarDefaultValue
is specified, then the result of evaluating
VarDefaultValue
as described below.
In all cases where the context item has a value, that value must match the type
T
according to the rules for SequenceType matching; otherwise a type error is
raised
If VarValue
or VarDefaultValue
is evaluated, the static and dynamic
contexts for the evaluation are the current module's static and dynamic context.
Here are some examples of context item declarations.
Declare the type of the context item:
Declare a default context item, which is a system log in a default location. If the system log is in a different location, it can be specified in the external environment:
In addition to the built-in functions described in
A function declaration specifies whether a function is
external
. The purpose of a function declaration for an external function is to
declare the datatypes of the function parameters and result, for use in type checking of the
query that contains or imports the function declaration.
A function declaration may use the %private
or %public
annotations
to specify that a function is public or private; if neither of these annotations is used, the
function is public. %private
annotation. A private function
is hidden from %private
annotation. A public function is accessible to
%public
and %private
annotations
in a main module is not an error, but it does not affect module imports, since a main module
cannot be imported. It is a %private
and a %public
annotation, more than one
%private
annotation, or more than one %public
annotation.
An XQuery implementation may provide a facility whereby external functions can be implemented
using a host programming language, but it is not required to do so. If such a facility is
provided, the protocols by which parameters are passed to an external function, and the result
of the function is returned to the invoking query, are xs:anyAtomicType
.
An implementation can define annotations, in its own namespace, to support functionality beyond the scope of this specification. For instance, an implementation that supports external Java functions might use an annotation to associate a Java function with an XQuery external function:
Every declared function must be in a namespace; that is, every declared function name must
(when expanded) have a non-null namespace URI
http://www.w3.org/XML/1998/namespace
http://www.w3.org/2001/XMLSchema
http://www.w3.org/2001/XMLSchema-instance
http://www.w3.org/2005/xpath-functions
http://www.w3.org/2005/xpath-functions/math
http://www.w3.org/2012/xquery
In order to allow main modules to declare functions for local use within the module without
defining a new namespace, XQuery predefines the namespace prefix local
to the
namespace http://www.w3.org/2005/xquery-local-functions
. It is suggested (but not
required) that this namespace be used for defining local functions.
If a function parameter is declared using a name but no type, its default type is
item()*
. If the result type is omitted from a function declaration, its default
result type is item()*
.
The parameters of a function declaration are considered to be variables whose scope is the
function body. It is an
A FunctionDecl
defines a function with the following properties:
EQName
of the FunctionDecl
, expanded (if
necessary) using the
EQName
s in the ParamList
,
expanded (if necessary) using the
FunctionTest
built from the
SequenceType
s (explicit or implicit) in the FunctionDecl
and
its ParamList
, and from any Annotation
s preceding the
FunctionDecl
.
FunctionDecl
's
FunctionBody
.
The following example illustrates the declaration and use of a local function that accepts a
sequence of employee
elements, summarizes them by department, and returns a
sequence of dept
elements.
Using a function, prepare a summary of employees that are located in Denver.
A function declaration may be recursive—that is, it may reference itself. Mutually
recursive functions, whose bodies reference each other, are also allowed. The following
example declares a recursive function that computes the maximum depth of a node hierarchy, and
calls the function to find the maximum depth of a particular document. The function
local:depth
calls the built-in functions empty
and
max
, which are in the default function namespace.
Find the maximum depth of the document named partlist.xml
.
Typically, a particular option will be recognized by some implementations and not by others. The syntax is designed so that option declarations can be successfully parsed by all implementations.
If the EQName of an option is a
If the EQName of an option does not have a prefix, the http://www.w3.org/2012/xquery
namespace,
which is reserved for option declarations defined by the XQuery family of specifications.
XQuery does not currently define declaration options in this namespace.
Each implementation recognizes the http://www.w3.org/2012/xquery
namespace URI
and and all options defined in this namespace in this specification. In addition, each
implementation recognizes an
Otherwise, the effect of the option declaration, including its error behavior, is
Implementations may impose rules on where particular option declarations may appear relative to variable declarations and function declarations, and the interpretation of an option declaration may depend on its position.
An option declaration must not be used to change the syntax accepted by the processor, or to
suppress the detection of
The following examples illustrate several possible uses for option declarations:
This option declaration might be used to specify how comments in source documents
returned by the fn:doc()
function should be handled:
This option declaration might be used to associate a namespace used in function names with a Java class:
The XQuery Working Group has not yet determined conformance criteria for XQuery 3.1; in particular, we have not decided which of the new features of XQuery 3.1 are optional. This section currently contains the conformance criteria for XQuery 3.0, with two modifications: (1) support for all axes is now required, (2) conformance criteria for syntax extensions are given.
This section defines the conformance criteria for an XQuery processor. In this section, the
following terms are used to indicate the requirement levels defined in
An XQuery processor that claims to conform to this specification
An implementation that claims
An implementation of everything specified in this document except those features
specified in
A definition of every item specified to be
Implementations are not required to define items specified to be
An implementation of
An implementation of all functions defined in
The features discussed in this section are optional. An implementation
The description of each feature mentions any errors that may occur if a query relies on a feature that is not present.
validate
expression (see
If an XQuery implementation does not provide the Schema Aware Feature, it validate
expression.
If an implementation provides the Schema Aware Feature, it
xs:untyped
and attributes node types other
than xs:untypedAtomic
.
If an XQuery implementation does not provide the Typed Data Feature, it
The XDM has the type xs:untyped
for every element node and
xs:untypedAtomic
for every attribute node, including nodes
created by the query.
Elements constructed by the query always have the type
xs:untyped
; attributes constructed by the query always have
the type xs:untypedAtomic
. (This is equivalent to using
construction mode = strip
.)
If an implementation provides the
If an implementation does not provide the
An implementation that does not provide the Module Feature
In the absence of the Module Feature, each query consists of a single
The means by which serialization is invoked is
If an error is raised during the serialization process as specified in
An implementation that does not provide the Serialization Feature fn:serialize
; it fn:serialize
is invoked, as specified in
Some implementations return query results without serialization. For instance, an implementation might provide results via an XML API or a binary representation such as a persistent DOM.
An implementation that does not provide the Higher-Order Function Feature
If an implementation provides the Higher-Order Function Feature, then it must provide
fn:function-lookup
, fn:function-name
,
fn:function-arity
, fn:for-each
,
fn:filter
, fn:fold-left
, fn:fold-right
, and
fn:for-each-pair
. If an implementation does not provide the Higher
Order Function Feature, a
fn:put()
Feature
fn:put()
function, defined in fn:put()
has side effects. It is provided
as a separate feature because some implementations may
want to be able to output files even if they do not
conform to the XQuery Update Facility specification.
An implementation that does not provide the
fn:put()
is
present in a query.
An implementation that provides the
All XQuery implementations process data represented in the
For suggestions on processing XML 1.1 documents with XSD 1.0, see
For the xs:decimal
type, the maximum number of decimal
digits (totalDigits
facet) (must be at least 18).
For the types xs:date
, xs:time
,
xs:dateTime
, xs:gYear
, and
xs:gYearMonth
: the maximum value of the year component
and the maximum number of fractional second digits (must be at least
3).
For the xs:duration type
: the maximum absolute values of the
years, months, days, hours, minutes, and seconds components.
For the xs:yearMonthDuration
type: the maximum absolute
value, expressed as an integer number of months.
For the xs:dayTimeDuration
type: the maximum absolute value,
expressed as a decimal number of seconds.
For the types xs:string
, xs:hexBinary
,
xs:base64Binary
, xs:QName
,
xs:anyURI
, xs:NOTATION
, and types derived
from them: limitations (if any) imposed by the implementation on lengths
of values.
The limits listed above need not be fixed, but may depend on environmental
factors such as system resources. For example, the length of a value of type
xs:string
may be limited by available memory.
For discussion of errors due to
Any syntactic extensions to XQuery are
The grammar of XQuery 3.1 uses the same simple Extended Backus-Naur Form (EBNF) notation as
All named symbols have a name that begins with an uppercase letter.
It adds a notation for referring to productions in external specs.
Comments or extra-grammatical constraints on grammar productions are between '/*' and '*/' symbols.
A 'xgc:' prefix is an extra-grammatical constraint, the details of which are
explained in
A 'ws:' prefix explains the whitespace rules for the production, the details of which
are explained in
A 'gn:' prefix means a 'Grammar Note', and is meant as a clarification for parsing
rules, and is explained in
The terminal symbols for this grammar include the quoted strings used in the production rules
below, and the terminal symbols defined in section
The EBNF notation is described in more detail in
To increase readability, the EBNF in the main body of this document omits some of these notational features. This appendix is the normative version of the EBNF.
The following definitions will be helpful in defining precisely this exposition.
matches any
matches any
matches any
matches the sequence of characters that appear inside the double quotes.
matches the sequence of characters that appear inside the single quotes.
matches any string matched by the production defined in the external specification as per the provided reference.
Patterns (including the above constructs) can be combined with grammatical operators to form more complex patterns, matching more complex sets of character strings. In the examples that follow, A and B represent (sub-)patterns.
A
is treated as a unit and may be combined as described in this list.
matches A
or nothing; optional A
.
matches A
followed by B
. This operator has higher
precedence than alternation; thus A B | C D
is identical to (A B) |
(C D)
.
matches A
or B
but not both.
matches any string that matches A
but does not match B
.
matches one or more occurrences of A
. Concatenation has higher
precedence than alternation; thus A+ | B+
is identical to (A+) |
(B+)
.
matches zero or more occurrences of A
. Concatenation has higher
precedence than alternation; thus A* | B*
is identical to (A*) |
(B*)
This section contains constraints on the EBNF productions, which are required to parse
syntactically valid sentences. The notes below are referenced from the right side of the
production, with the notation:
A single slash may appear either as a complete path expression or as the first part of a
path expression in which it is followed by a *
token and
keywords like union
could be either an operator or a <
token could be either an operator or the
start of a / * 5
is easily taken to
be a complete expression, / *
, which has a very different
interpretation (the child nodes of /
).
Therefore to reduce the need for lookahead, if the token immediately following a slash
can form the start of a
A single slash may be used as the left-hand argument of an operator by parenthesizing it:
(/) * 5
. The expression 5 *
/
, on the other hand, is syntactically valid without parentheses.
The version of XML and XML Names (e.g. prefix : localname
is not a
syntactically valid
XML 1.0 and XML 1.1 differ in their handling of C0 control characters
(specifically #x1 through #x1F, excluding #x9, #xA, and #xD) and C1 control characters
(#x7F through #x9F). In XML 1.0, these C0 characters are prohibited, and the C1 characters
are permitted. In XML 1.1, both sets of control characters are permitted, but only if
written as character references. It is RECOMMENDED that implementations should follow the
XML 1.1 rules in this respect; however, for backwards compatibility with Direct use of C1 control characters often suggests a
character encoding error, such as using encoding CP-1252 and mislabeling it as
iso-8859-1.
Unprefixed function names spelled the same way as language keywords could make the
language harder to recognize. For instance, if(foo)
could be taken either as
a
A function named "if" can be called by binding its namespace to a prefix and using the prefixed form: "library:if(foo)" instead of "if(foo)".
As written, the grammar in
Thus, 4 treat as item() + - 5
must be interpreted as (4 treat as item()+) - 5
, taking the '+' as an
OccurrenceIndicator and the '-' as a subtraction operator. To force the interpretation of
"+" as an addition operator (and the corresponding interpretation of the "-" as a unary
minus), parentheses may be used: the form (4 treat as item()) +
-5
surrounds the
function () as xs:string *
is interpreted as function () as (xs:string
*)
, not as (function () as xs:string) *
. Parentheses can be used as
shown to force the latter interpretation.
This rule has as a consequence that certain forms which would otherwise be syntactically
valid and unambiguous are not recognized: in "4 treat as item() + 5", the "+" is taken as
an
This section contains general notes on the EBNF productions, which may be helpful in
understanding how to interpret and implement the EBNF. These notes are not normative. The
notes below are referenced from the right side of the production, with the notation:
Look-ahead is required to distinguish address (: this
may be empty :)
may be mistaken for a call to a function named "address"
unless this lookahead is employed. Another example is for (:
whom the bell :) $tolls in 3 return $tolls
, where the keyword "for" must
not be mistaken for a function name.
Comments are allowed everywhere that
A comment can contain nested comments, as long as all "(:" and ":)" patterns are balanced, no matter where they occur within the outer comment.
Lexical analysis may typically handle nested comments by incrementing a counter for each "(:" pattern, and decrementing the counter for each ":)" pattern. The comment does not terminate until the counter is back to zero.
Some illustrative examples:
(: commenting out a (: comment :) may be confusing, but often helpful
:)
is a syntactically valid Comment, since balanced nesting of comments
is allowed.
"this is just a string :)"
is a syntactically
valid expression. However, (: "this is just a string :)" :)
will
cause a syntax error. Likewise, "this is another string
(:"
is a syntactically valid expression, but (: "this is another
string (:" :)
will cause a syntax error. It is a limitation of nested
comments that literal content can cause unbalanced nesting of comments.
for (: set up loop :) $i in $x return $i
is
syntactically valid, ignoring the comment.
5 instance (: strange place for a comment :) of
xs:integer
is also syntactically valid.
<eg (: an example:)>{$i//title}</eg>
is not syntactically valid.
<eg> (: an example:) </eg>
is syntactically valid, but the characters that look like a comment are
in fact literal element content.
The terminal symbols assumed by the grammar above are described in this section.
Quoted strings appearing in production rules are terminal symbols.
Other terminal symbols are defined in
Some productions are defined by reference to the XML and XML Names specifications (e.g.
It is
When tokenizing, the longest possible match that is consistent with the EBNF is used.
All keywords are case sensitive. Keywords are not reserved—that is, any
The following symbols are used only in the definition of terminal symbols; they are not
terminal symbols in the grammar of
XQuery 3.1 expressions consist of
Terminal symbols that are not used exclusively in
It is customary to separate consecutive terminal symbols by
Prior to parsing, the XQuery 3.1 processor must normalize all line breaks.
The rules for line breaking follow the rules of
For
the two-character sequence #xD #xA
any #xD character that is not immediately followed by #xA.
For
the two-character sequence #xD #xA
the two-character sequence #xD #x85
the single character #x85
the single character #x2028
any #xD character that is not immediately followed by #xA or #x85.
The characters #x85 and #x2028 cannot be reliably recognized and translated
until the
foo- foo
results in a syntax error. "foo-" would be recognized as a
QName.
foo -foo
is syntactically equivalent to foo - foo
, two QNames separated by a subtraction
operator.
foo(: This is a comment :)- foo
is syntactically
equivalent to foo - foo
. This is because the comment prevents the two
adjacent terminals from being recognized as one.
foo-foo
is syntactically equivalent to single QName.
This is because "-" is a valid character in a QName. When used as an operator after
the characters of a name, the "-" must be separated from the name, e.g. by using
whitespace or parentheses.
10div 3
results in a syntax error.
10 div3
also results in a syntax error.
10div3
also results in a syntax error.
Explicit whitespace notation is specified with the EBNF productions, when it is different from the default rules, using the notation shown below. This notation is not inherited. In other words, if an EBNF rule is marked as /* ws: explicit */, the notation does not automatically apply to all the 'child' EBNF productions of that rule.
/* ws: explicit */ means that the EBNF notation explicitly notates, with
S
or otherwise, where
For example, whitespace is not freely allowed by the direct constructor productions, but is specified explicitly in the grammar, in order to be more consistent with XML.
The following names are not allowed as function names in an unprefixed form because expression syntax takes precedence.
array
attribute
comment
document-node
element
empty-sequence
function
if
item
map
namespace-node
node
processing-instruction
schema-attribute
schema-element
switch
text
typeswitch
The grammar in
# | Operator | Associativity |
---|---|---|
1 |
| either |
2 |
| NA |
3 |
| either |
4 |
| either |
5 |
| NA |
6 |
| left-to-right |
7 |
| NA |
8 |
| left-to-right |
9 |
| left-to-right |
10 |
| either |
11 |
| left-to-right |
12 |
| NA |
13 |
| NA |
14 |
| NA |
15 |
| NA |
16 |
| right-to-left |
17 |
| left-to-right |
18 |
| left-to-right |
19 |
| left-to-right |
In the "Associativity" column, "either" indicates that all the operators at that level have
the associative property (i.e., (A op B) op C
is equivalent to A op (B op
C)
), so their associativity is inconsequential. "NA" (not applicable) indicates that
the EBNF does not allow an expression that directly contains multiple operators from that
precedence level, so the question of their associativity does not arise.
Parentheses can be used to override the operator precedence in the usual way. Square brackets in an expression such as A[B] serve two roles: they act as an operator causing B to be evaluated once for each item in the value of A, and they act as parentheses enclosing the expression B.
Curly braces in an expression such as validate{E} or ordered{E} perform a similar bracketing role to the parentheses in a function call, but with the difference in most cases that E is an Expr rather than ExprSingle, meaning that it can use the comma operator.
order by
clauses (see
Numeric type promotion:
A value of type xs:float
(or any type
derived by restriction from xs:float
) can be promoted to
the type xs:double
. The result is the
xs:double
value that is the same as the original
value.
A value of type xs:decimal
(or any type derived
by restriction from xs:decimal
) can be promoted to either
of the types xs:float
or xs:double
. The
result of this promotion is created by casting the original value to
the required type. This kind of promotion may cause loss of
precision.
URI type promotion: A value of type xs:anyURI
(or any type derived by restriction from xs:anyURI
) can be promoted to the type xs:string
. The result of this promotion is created by casting the original value to the type xs:string
.
Since xs:anyURI
values can be promoted to xs:string
, functions and operators that compare strings using the xs:anyURI
values using the xs:anyURI
values, or any combination of the two types are consistent and well-defined.
Note that
A function that expects a parameter $p
of type xs:float
can be invoked with a value of type xs:decimal
. This is an example of $p instance of xs:decimal
returns false
.
A function that expects a parameter $p
of type xs:decimal
can be invoked with a value of type xs:integer
. This is an example of $p instance of xs:integer
returns true
.
The operator mapping tables in this section list the
combinations of types for which the various operators of XQuery 3.1
are defined.
The and
and
or
operators are defined directly in the main body of
this document, and do not occur in the operator mapping tables.
If an operator in the operator mapping tables expects an operand of type
gt
operator may
be applied to two xs:date
operands, returning
xs:boolean
. Therefore, the gt
operator may
also be applied to two (possibly different) subtypes of
xs:date
, also returning xs:boolean
.
xs:integer
, xs:decimal
,
xs:float
, and xs:double
xs:numeric
+
operator might be
thought of as representing the following four operators:
Operator | First operand type | Second operand type | Result type |
+
|
xs:integer
|
xs:integer
|
xs:integer
|
+
|
xs:decimal
|
xs:decimal
|
xs:decimal
|
+
|
xs:float
|
xs:float
|
xs:float
|
+
|
xs:double
|
xs:double
|
xs:double
|
A numeric operator may be validly applied to an operand of type (xs:integer, xs:decimal, xs:float, xs:double)
into which all operands can be converted by hatsize
is derived from xs:integer
and the type shoesize
is derived from xs:float
. Then if the +
operator is invoked with operands of type hatsize
and shoesize
, it returns a result of type xs:float
. Similarly, if +
is invoked with two operands of type hatsize
it returns a result of type xs:integer
.
xs:gYearMonth
, xs:gYear
,
xs:gMonthDay
, xs:gDay
, and
xs:gMonth
.xs:gDay
, the other
operand must be of type xs:gDay
.)
Operator | Type(A) | Type(B) | Function | Result type |
---|---|---|---|---|
A + B | numeric | numeric | op:numeric-add(A, B) | numeric |
A + B | xs:date | xs:yearMonthDuration | op:add-yearMonthDuration-to-date(A, B) | xs:date |
A + B | xs:yearMonthDuration | xs:date | op:add-yearMonthDuration-to-date(B, A) | xs:date |
A + B | xs:date | xs:dayTimeDuration | op:add-dayTimeDuration-to-date(A, B) | xs:date |
A + B | xs:dayTimeDuration | xs:date | op:add-dayTimeDuration-to-date(B, A) | xs:date |
A + B | xs:time | xs:dayTimeDuration | op:add-dayTimeDuration-to-time(A, B) | xs:time |
A + B | xs:dayTimeDuration | xs:time | op:add-dayTimeDuration-to-time(B, A) | xs:time |
A + B | xs:dateTime | xs:yearMonthDuration | op:add-yearMonthDuration-to-dateTime(A, B) | xs:dateTime |
A + B | xs:yearMonthDuration | xs:dateTime | op:add-yearMonthDuration-to-dateTime(B, A) | xs:dateTime |
A + B | xs:dateTime | xs:dayTimeDuration | op:add-dayTimeDuration-to-dateTime(A, B) | xs:dateTime |
A + B | xs:dayTimeDuration | xs:dateTime | op:add-dayTimeDuration-to-dateTime(B, A) | xs:dateTime |
A + B | xs:yearMonthDuration | xs:yearMonthDuration | op:add-yearMonthDurations(A, B) | xs:yearMonthDuration |
A + B | xs:dayTimeDuration | xs:dayTimeDuration | op:add-dayTimeDurations(A, B) | xs:dayTimeDuration |
A - B | numeric | numeric | op:numeric-subtract(A, B) | numeric |
A - B | xs:date | xs:date | op:subtract-dates(A, B) | xs:dayTimeDuration |
A - B | xs:date | xs:yearMonthDuration | op:subtract-yearMonthDuration-from-date(A, B) | xs:date |
A - B | xs:date | xs:dayTimeDuration | op:subtract-dayTimeDuration-from-date(A, B) | xs:date |
A - B | xs:time | xs:time | op:subtract-times(A, B) | xs:dayTimeDuration |
A - B | xs:time | xs:dayTimeDuration | op:subtract-dayTimeDuration-from-time(A, B) | xs:time |
A - B | xs:dateTime | xs:dateTime | op:subtract-dateTimes(A, B) | xs:dayTimeDuration |
A - B | xs:dateTime | xs:yearMonthDuration | op:subtract-yearMonthDuration-from-dateTime(A, B) | xs:dateTime |
A - B | xs:dateTime | xs:dayTimeDuration | op:subtract-dayTimeDuration-from-dateTime(A, B) | xs:dateTime |
A - B | xs:yearMonthDuration | xs:yearMonthDuration | op:subtract-yearMonthDurations(A, B) | xs:yearMonthDuration |
A - B | xs:dayTimeDuration | xs:dayTimeDuration | op:subtract-dayTimeDurations(A, B) | xs:dayTimeDuration |
A * B | numeric | numeric | op:numeric-multiply(A, B) | numeric |
A * B | xs:yearMonthDuration | numeric | op:multiply-yearMonthDuration(A, B) | xs:yearMonthDuration |
A * B | numeric | xs:yearMonthDuration | op:multiply-yearMonthDuration(B, A) | xs:yearMonthDuration |
A * B | xs:dayTimeDuration | numeric | op:multiply-dayTimeDuration(A, B) | xs:dayTimeDuration |
A * B | numeric | xs:dayTimeDuration | op:multiply-dayTimeDuration(B, A) | xs:dayTimeDuration |
A idiv B | numeric | numeric | op:numeric-integer-divide(A, B) | xs:integer |
A div B | numeric | numeric | op:numeric-divide(A, B) | numeric; but xs:decimal if both operands are xs:integer |
A div B | xs:yearMonthDuration | numeric | op:divide-yearMonthDuration(A, B) | xs:yearMonthDuration |
A div B | xs:dayTimeDuration | numeric | op:divide-dayTimeDuration(A, B) | xs:dayTimeDuration |
A div B | xs:yearMonthDuration | xs:yearMonthDuration | op:divide-yearMonthDuration-by-yearMonthDuration (A, B) | xs:decimal |
A div B | xs:dayTimeDuration | xs:dayTimeDuration | op:divide-dayTimeDuration-by-dayTimeDuration (A, B) | xs:decimal |
A mod B | numeric | numeric | op:numeric-mod(A, B) | numeric |
A eq B | numeric | numeric | op:numeric-equal(A, B) | xs:boolean |
A eq B | xs:boolean | xs:boolean | op:boolean-equal(A, B) | xs:boolean |
A eq B | xs:string | xs:string | op:numeric-equal(fn:compare(A, B), 0) | xs:boolean |
A eq B | xs:date | xs:date | op:date-equal(A, B) | xs:boolean |
A eq B | xs:time | xs:time | op:time-equal(A, B) | xs:boolean |
A eq B | xs:dateTime | xs:dateTime | op:dateTime-equal(A, B) | xs:boolean |
A eq B | xs:duration | xs:duration | op:duration-equal(A, B) | xs:boolean |
A eq B | Gregorian | Gregorian | op:gYear-equal(A, B) etc. | xs:boolean |
A eq B | xs:hexBinary | xs:hexBinary | op:hexBinary-equal(A, B) | xs:boolean |
A eq B | xs:base64Binary | xs:base64Binary | op:base64Binary-equal(A, B) | xs:boolean |
A eq B | xs:anyURI | xs:anyURI | op:numeric-equal(fn:compare(A, B), 0) | xs:boolean |
A eq B | xs:QName | xs:QName | op:QName-equal(A, B) | xs:boolean |
A eq B | xs:NOTATION | xs:NOTATION | op:NOTATION-equal(A, B) | xs:boolean |
A eq B | xs:hexBinary | xs:hexBinary | op:hexBinary-equal(A, B) | xs:boolean |
A eq B | xs:base64Binary | xs:base64Binary | op:hexBinary-equal(A, B) | xs:boolean |
A ne B | numeric | numeric | fn:not(op:numeric-equal(A, B)) | xs:boolean |
A ne B | xs:boolean | xs:boolean | fn:not(op:boolean-equal(A, B)) | xs:boolean |
A ne B | xs:string | xs:string | fn:not(op:numeric-equal(fn:compare(A, B), 0)) | xs:boolean |
A ne B | xs:date | xs:date | fn:not(op:date-equal(A, B)) | xs:boolean |
A ne B | xs:time | xs:time | fn:not(op:time-equal(A, B)) | xs:boolean |
A ne B | xs:dateTime | xs:dateTime | fn:not(op:dateTime-equal(A, B)) | xs:boolean |
A ne B | xs:duration | xs:duration | fn:not(op:duration-equal(A, B)) | xs:boolean |
A ne B | Gregorian | Gregorian | fn:not(op:gYear-equal(A, B)) etc. | xs:boolean |
A ne B | xs:hexBinary | xs:hexBinary | fn:not(op:hexBinary-equal(A, B)) | xs:boolean |
A ne B | xs:base64Binary | xs:base64Binary | fn:not(op:base64Binary-equal(A, B)) | xs:boolean |
A ne B | xs:anyURI | xs:anyURI | fn:not(op:numeric-equal(fn:compare(A, B), 0)) | xs:boolean |
A ne B | xs:QName | xs:QName | fn:not(op:QName-equal(A, B)) | xs:boolean |
A ne B | xs:NOTATION | xs:NOTATION | fn:not(op:NOTATION-equal(A, B)) | xs:boolean |
A ne B | xs:hexBinary | xs:hexBinary | fn:not(op:hexBinary-equal(A, B)) | xs:boolean |
A ne B | xs:base64Binary | xs:base64Binary | fn:not(op:base64Binary-equal(A, B)) | xs:boolean |
A gt B | numeric | numeric | op:numeric-greater-than(A, B) | xs:boolean |
A gt B | xs:boolean | xs:boolean | op:boolean-greater-than(A, B) | xs:boolean |
A gt B | xs:string | xs:string | op:numeric-greater-than(fn:compare(A, B), 0) | xs:boolean |
A gt B | xs:date | xs:date | op:date-greater-than(A, B) | xs:boolean |
A gt B | xs:time | xs:time | op:time-greater-than(A, B) | xs:boolean |
A gt B | xs:dateTime | xs:dateTime | op:dateTime-greater-than(A, B) | xs:boolean |
A gt B | xs:yearMonthDuration | xs:yearMonthDuration | op:yearMonthDuration-greater-than(A, B) | xs:boolean |
A gt B | xs:dayTimeDuration | xs:dayTimeDuration | op:dayTimeDuration-greater-than(A, B) | xs:boolean |
A gt B | xs:anyURI | xs:anyURI | op:numeric-greater-than(fn:compare(A, B), 0) | xs:boolean |
A gt B | xs:hexBinary | xs:hexBinary | op:hexBinary-greater-than(A, B) | xs:boolean |
A gt B | xs:base64Binary | xs:base64Binary | op:base64Binary-greater-than(A, B) | xs:boolean |
A lt B | numeric | numeric | op:numeric-less-than(A, B) | xs:boolean |
A lt B | xs:boolean | xs:boolean | op:boolean-less-than(A, B) | xs:boolean |
A lt B | xs:string | xs:string | op:numeric-less-than(fn:compare(A, B), 0) | xs:boolean |
A lt B | xs:date | xs:date | op:date-less-than(A, B) | xs:boolean |
A lt B | xs:time | xs:time | op:time-less-than(A, B) | xs:boolean |
A lt B | xs:dateTime | xs:dateTime | op:dateTime-less-than(A, B) | xs:boolean |
A lt B | xs:yearMonthDuration | xs:yearMonthDuration | op:yearMonthDuration-less-than(A, B) | xs:boolean |
A lt B | xs:dayTimeDuration | xs:dayTimeDuration | op:dayTimeDuration-less-than(A, B) | xs:boolean |
A lt B | xs:anyURI | xs:anyURI | op:numeric-less-than(fn:compare(A, B), 0) | xs:boolean |
A lt B | xs:hexBinary | xs:hexBinary | op:hexBinary-less-than(A, B) | xs:boolean |
A lt B | xs:base64Binary | xs:base64Binary | op:base64Binary-less-than(A, B) | xs:boolean |
A ge B | numeric | numeric | op:numeric-greater-than(A, B) or op:numeric-equal(A, B) | xs:boolean |
A ge B | xs:boolean | xs:boolean | fn:not(op:boolean-less-than(A, B)) | xs:boolean |
A ge B | xs:string | xs:string | op:numeric-greater-than(fn:compare(A, B), -1) | xs:boolean |
A ge B | xs:date | xs:date | fn:not(op:date-less-than(A, B)) | xs:boolean |
A ge B | xs:time | xs:time | fn:not(op:time-less-than(A, B)) | xs:boolean |
A ge B | xs:dateTime | xs:dateTime | fn:not(op:dateTime-less-than(A, B)) | xs:boolean |
A ge B | xs:yearMonthDuration | xs:yearMonthDuration | fn:not(op:yearMonthDuration-less-than(A, B)) | xs:boolean |
A ge B | xs:dayTimeDuration | xs:dayTimeDuration | fn:not(op:dayTimeDuration-less-than(A, B)) | xs:boolean |
A ge B | xs:anyURI | xs:anyURI | op:numeric-greater-than(fn:compare(A, B), -1) | xs:boolean |
A ge B | xs:hexBinary | xs:hexBinary | fn:not(op:hexBinary-less-than(A, B)) | xs:boolean |
A ge B | xs:base64Binary | xs:base64Binary | fn:not(op:base64Binary-less-than(A, B)) | xs:boolean |
A le B | numeric | numeric | op:numeric-less-than(A, B) or op:numeric-equal(A, B) | xs:boolean |
A le B | xs:boolean | xs:boolean | fn:not(op:boolean-greater-than(A, B)) | xs:boolean |
A le B | xs:string | xs:string | op:numeric-less-than(fn:compare(A, B), 1) | xs:boolean |
A le B | xs:date | xs:date | fn:not(op:date-greater-than(A, B)) | xs:boolean |
A le B | xs:time | xs:time | fn:not(op:time-greater-than(A, B)) | xs:boolean |
A le B | xs:dateTime | xs:dateTime | fn:not(op:dateTime-greater-than(A, B)) | xs:boolean |
A le B | xs:yearMonthDuration | xs:yearMonthDuration | fn:not(op:yearMonthDuration-greater-than(A, B)) | xs:boolean |
A le B | xs:dayTimeDuration | xs:dayTimeDuration | fn:not(op:dayTimeDuration-greater-than(A, B)) | xs:boolean |
A le B | xs:anyURI | xs:anyURI | op:numeric-less-than(fn:compare(A, B), 1) | xs:boolean |
A le B | xs:hexBinary | xs:hexBinary | fn:not(op:hexBinary-greater-than(A, B)) | xs:boolean |
A le B | xs:base64Binary | xs:base64Binary | fn:not(op:base64Binary-greater-than(A, B)) | xs:boolean |
A is B | node() | node() | op:is-same-node(A, B) | xs:boolean |
A << B | node() | node() | op:node-before(A, B) | xs:boolean |
A >> B | node() | node() | op:node-after(A, B) | xs:boolean |
A union B | node()* | node()* | op:union(A, B) | node()* |
A | B | node()* | node()* | op:union(A, B) | node()* |
A intersect B | node()* | node()* | op:intersect(A, B) | node()* |
A except B | node()* | node()* | op:except(A, B) | node()* |
A to B | xs:integer | xs:integer | op:to(A, B) | xs:integer* |
A , B | item()* | item()* | op:concatenate(A, B) | item()* |
A || B | xs:anyAtomicType | xs:anyAtomicType | fn:concat(A, B) | xs:string |
Operator | Operand type | Function | Result type |
---|---|---|---|
+ A | numeric | op:numeric-unary-plus(A) | numeric |
- A | numeric | op:numeric-unary-minus(A) | numeric |
The tables in this section describe how values are assigned to the various components of the static context and dynamic context, and to the parameters that control the serialization process.
The following table describes the components of the
Component | Default initial value | Can be overwritten or augmented by implementation? | Can be overwritten or augmented by prolog? | Can be overwritten or augmented by expressions? | Consistency rules |
---|---|---|---|---|---|
Statically known namespaces |
fn , xml , xs , xsi , local
| overwriteable and augmentable (except for xml ) | overwriteable and augmentable by | overwriteable and augmentable by element constructor | Only one namespace can be assigned to a given prefix per lexical scope. |
Default element/type namespace | no namespace | overwriteable | overwriteable by | overwriteable by element constructor | Only one default namespace per lexical scope. |
In-scope variables | none | augmentable | overwriteable and augmentable by | overwriteable and augmentable by variable-binding expressions | Only one definition per variable per lexical scope. |
Context item static type | item() | overwriteable | overwriteable by | overwriteable by expresssions that set the context item | None. |
Ordering mode |
ordered
| overwriteable | overwriteable by | overwriteable by expression | Value must be ordered or unordered . |
Default function namespace |
fn
| overwriteable (not recommended) | overwriteable by | no | None. |
In-scope schema types | built-in types in xs
| augmentable | augmentable by | no | Only one definition per global or local type. |
In-scope element declarations | none | augmentable | augmentable by | no | Only one definition per global or local element name. |
In-scope attribute declarations | none | augmentable | augmentable by | no | Only one definition per global or local attribute name. |
Statically known function signatures | functions in fn namespace, and constructors for built-in | augmentable | augmentable by | no | Each function must have a unique |
Default collation | Unicode codepoint collation | overwriteable | overwriteable by | no | None. |
Construction mode |
preserve
| overwriteable | overwriteable by | no | Value must be preserve or strip . |
Default order for empty sequences | implementation-defined | overwriteable | overwriteable by | no | Value must be greatest or least . |
Boundary-space policy |
strip
| overwriteable | overwriteable by | no | Value must be preserve or strip . |
Copy-namespaces mode |
inherit, preserve
| overwriteable | overwriteable by | no | Value consists of inherit or no-inherit , and preserve or no-preserve . |
Static Base URI | See rules in | overwriteable | overwriteable by | no | Value must be a valid lexical representation of the type xs:anyURI. |
Statically known decimal formats | the default (unnamed) decimal format, which has an implementation-dependent value | augmentable | augmentable, using | no | each QName uniquely identifies a decimal format |
Statically known documents | none | augmentable | no | no | None. |
Statically known collections | none | augmentable | no | no | None. |
Statically known default collection type |
node()*
| overwriteable | no | no | None. |
Statically known collations | only the default collation | augmentable | no | no | Each URI uniquely identifies a collation. |
XPath 1.0 Compatibility Mode |
false
| no | no | no | Must be false . |
Serialization Parameters | |||||
allow-duplicate-names | no | overwriteable | overwriteable by prolog | no |
|
byte-order-mark | implementation-defined | overwriteable | overwriteable by prolog | no |
|
cdata-section-elements | empty | overwriteable and augmentable | overwriteable by prolog | no |
|
doctype-public | none | overwriteable | overwriteable by prolog | no |
|
doctype-system | none | overwriteable | overwriteable by prolog | no |
|
encoding | implementation-defined choice between "utf-8" and "utf-16" | overwriteable | overwriteable by prolog | no |
|
escape-uri-attributes | (not applicable when method = xml) | overwriteable and augmentable | overwriteable by prolog | no |
|
html-version | implementation-defined | overwriteable | overwriteable by prolog | no |
|
include-content-type | (not applicable when method = xml) | overwriteable | overwriteable by prolog | no |
|
indent | no | overwriteable | overwriteable by prolog | no |
|
item-separator | implementation-defined | overwriteable | overwriteable by prolog | no |
|
json-node-output-method | xml | overwriteable | overwriteable by prolog | no |
|
media-type | implementation-defined | overwriteable | overwriteable by prolog | no |
|
method | xml | overwriteable | overwriteable by prolog | no |
|
normalization-form | implementation-defined | overwriteable | overwriteable by prolog | no |
|
omit-xml-declaration | implementation-defined | overwriteable | overwriteable by prolog | no |
|
standalone | implementation-defined | overwriteable | overwriteable by prolog | no |
|
suppress-indentation | empty | overwriteable and augmentable | overwriteable by prolog | no |
|
undeclare-prefixes | no | overwriteable | overwriteable by prolog | no |
|
use-character-maps | empty | overwriteable and augmentable | overwriteable by prolog | no |
|
version | implementation-defined | overwriteable | overwriteable by prolog | no |
|
The following table describes the components of the
Component | Default initial value | Can be overwritten or augmented by implementation? | Can be overwritten or augmented by prolog? | Can be overwritten or augmented by expressions? | Consistency rules |
---|---|---|---|---|---|
Context item | the | overwriteable | no, but the | overwritten during evaluation of path expressions and predicates | The query body and the prolog of every module in a query
share the same |
Context position | 1 if the | overwriteable | no | overwritten during evaluation of path expressions and predicates | If context item is defined, context position must be >0 and <= context size; else context position is |
Context size | 1 if the | overwriteable | no | overwritten during evaluation of path expressions and predicates | If context item is defined, context size must be >0; else context size is |
Variable values | none | augmentable | overwriteable and augmentable by | overwriteable and augmentable by variable-binding expressions | Names and values must be consistent with in-scope variables. |
Named functions | functions in fn namespace, and constructors for built-in | augmentable | augmentable by
| no | Must be consistent with statically known function signatures |
Current dateTime | none | must be initialized | no | no | Must include a timezone. Remains constant during evaluation of a query. |
Implicit timezone | none | must be initialized | no | no | Remains constant during evaluation of a query. |
Available documents | none | must be initialized | no | no | None |
Available text resources | none | must be initialized | no | no | None |
Available node collections | none | must be initialized | no | no | None |
Default node collection | none | overwriteable | no | no | None |
Available resource collections | none | must be initialized | no | no | None |
Default resource collection | none | overwriteable | no | no | None |
The following items in this specification are
The version of Unicode that is used to construct expressions.
The
The
The circumstances in which
The method by which errors are reported to the external processing environment.
Which version of XML and XML Names (e.g.
How XDM instances are created from sources other than an Infoset or PSVI.
Any components of the
The default handling of empty sequences returned by an ordering key (orderspec) in an order by
clause (empty least
or empty greatest
).
The names and semantics of any
The names and semantics of any
Protocols (if any) by which parameters can be passed to an external function, and the result of the function can returned to the invoking query.
The process by which the specific modules to be imported by a
The means by which serialization is invoked, if the
The default values for the byte-order-mark
, encoding
, media-type
, normalization-form
, omit-xml-declaration
, standalone
, and version
parameters, if the
The result of an unsuccessful call to an external function (for example, if the function implementation cannot be found or does not return a value of the declared type).
Limits on ranges of values for various data types, as enumerated in
Syntactic extensions to XQuery, including both their syntax and semantics, as discussed in
Whether the type system is based on
The signatures of functions provided by the implementation or via an implementation-defined API (see
Any
Any rules used for static typing (see
Any serialization parameters provided by the implementation
The means by which the location hint for a serialization parameter document identifies the corresponding XDM instance (see
What error, if any, is returned if an external function's implementation does not return the declared result type (see
Any annotations defined by the implementation, and their associated behavior (see
Any
The effect of function assertions understood by the implementation on
Any implementation-defined variables defined by the implementation. (see
The ordering associated with fn:unordered
in the implementation (see
Any additional information provided for try/catch via the err:additional
variable (see
The default boundary-space policy (see
The default collation (see
The default base URI (see
Additional
It is a
It is a
It is a
It is a
During the analysis phase, it is a ()
or data(())
is
empty-sequence()
.
It is a
An implementation that does not support the Schema Aware Feature must raise
a
It is a
It is a
An implementation that does not support the Module Feature raises a
It is a
It is a
It is a E1
in a path
expression E1/E2
does not evaluate to a sequence of nodes.
It is a
It is a
It is a
It is a
It is a ?>
".
In a validate expression, it is a valid
if
validation mode is strict
, or either valid
or
notKnown
if validation mode is lax
.
It is a validate
expression does not evaluate to exactly one document or element
node.
It is a
A
It is a
It is a eq
operator).
It is a
It is a
It is a
It is a
It is a xs:NCName
.
It is a
Its namespace prefix is xmlns
.
It has no namespace prefix and its local name is xmlns
.
Its namespace URI is http://www.w3.org/2000/xmlns/
.
Its namespace prefix is xml
and its namespace URI is not
http://www.w3.org/XML/1998/namespace
.
Its namespace prefix is other than xml
and its namespace URI is
http://www.w3.org/XML/1998/namespace
.
It is a http://www.w3.org/XML/1998/namespace,
http://www.w3.org/2001/XMLSchema, http://www.w3.org/2001/XMLSchema-instance,
http://www.w3.org/2005/xpath-functions
,
http://www.w3.org/2005/xpath-functions/math
, http://www.w3.org/2012/xquery
.
An implementation xs:anyURI
It is a
It is a
It is a eq
operator.)
It is a treat
expression does not match the treat
expression. This error might also be raised by a
path expression beginning with "/
" or "//
" if the context node
is not in a tree that is rooted at a document node. This is because a leading
"/
" or "//
" in a path expression is an abbreviation for an
initial step that includes the clause treat as document-node()
.
It is a
The type must be the name of a type defined in the {variety}
of the type must be
simple
.
It is a
It is a
It is a
It is a
It is a
It is a
It is a
It is a
A
A
A
A
A
A xml
or xmlns
appears in a namespace
declaration
The prefix xml
is bound to some namespace URI other than
http://www.w3.org/XML/1998/namespace
.
A prefix other than xml
is bound to the namespace URI
http://www.w3.org/XML/1998/namespace
.
The prefix xmlns
is bound to any namespace URI.
A prefix other than xmlns
is bound to the namespace URI
http://www.w3.org/2000/xmlns/
.
A
It is a
It is a
An implementation that does not support the Validation Feature must raise a validate
expression.
It is a collation
subclause in an order by
clause of a FLWOR
expression does not identify a collation that is present in
It is a
It is a cast
or castable
expression is
xs:NOTATION
xs:anySimpleType
,xs:anyAtomicType
.
It is a
It is a validate
statement does not have a top-level element
declaration in the strict
.
It is a
It is a preserve
and no-preserve
.
It is a EncName
specified in
It is a
It is a for
or window
clause of a FLWOR expression, and its
associated positional variable, do not have distinct names (
It is a
An implementation xml:id
error, as
defined in xml:id
.
An implementation xml:space
has a value other than preserve
or
default
.
The name of each grouping variable must be equal (by the eq
operator on
It is a
Its namespace prefix is xmlns
.
Its namespace URI is http://www.w3.org/2000/xmlns/
.
Its namespace prefix is xml
and its namespace URI is not
http://www.w3.org/XML/1998/namespace
.
Its namespace prefix is other than xml
and its namespace URI is
http://www.w3.org/XML/1998/namespace
.
It is a static error for a decimal-format to specify a value that is not valid for a
given property, as described in
It is a static error if, for any named or unnamed decimal format, the properties
representing characters used in a picture string do not each have distinct values. These
properties are
ContextItemDecl
must not occur after an expression
that relies on the initial context item, and no query
An error is raised if a computed namespace constructor attempts to do any of the following:
Bind the prefix xml
to some namespace URI other than
http://www.w3.org/XML/1998/namespace
.
Bind a prefix other than xml
to the namespace URI
http://www.w3.org/XML/1998/namespace
.
Bind the prefix xmlns
to any namespace URI.
Bind a prefix to the namespace URI http://www.w3.org/2000/xmlns/
.
Bind any prefix (including the empty prefix) to a zero-length namespace URI.
In an element constructor, if two or more namespace bindings in the in-scope bindings would have the same prefix, then an error is raised if they have different URIs; if they would have the same prefix and URI, duplicate bindings are ignored.
If the name of an element in an element constructor is in no namespace, creating a default namespace for that element using a computed namespace constructor is an error.
All variables in a window
clause must have distinct names.
A validate
expression must be found in the
It is a
It is a %private
and a %public
annotation.
It is a %private
or
%public
, more than one %private
annotation, or more than
one %public
annotation.
It is a %deterministic
or %nondeterministic
.
It is a
It is a http://www.w3.org/2010/xslt-xquery-serialization
namespace is not one of the serialization parameter names listed in use-character-maps
It is a
It is a
Specifying a
It is a
It is a
It is a %private
or %public
.%private
and a
%public
annotation, more than one %private
annotation,
or more than one %public
annotation.
In a cast expression, if an item is of type xs:untypedAtomic
and the
expected type is
In a direct element constructor, the name used in the end tag must exactly match the name used in the corresponding start tag, including its prefix or absence of a prefix.
It is a static error if the implementation is not able to process the value of an
output:parameter-document
declaration to produce an XDM instance.
It is a %public
or
%private
.
An implementation that does not provide the Higher-Order Function Feature
An implementation-defined limit has been exceeded.
It is a http://www.w3.org/2000/xmlns/
.
The namespace axis is not supported.
No two keys in a map may have the
Position n
does not exist in this array.
The keys in a map constructor cannot contain both date/time values with a timezone and date/time values with no timezone.
application/xquery
Media TypeThis Appendix specifies the media type for XQuery Version 1.0. XQuery is a language for querying over collections of data from XML data sources, as specified in the main body of this document. This media type is being submitted to the IESG (Internet Engineering Steering Group) for review, approval, and registration with IANA (Internet Assigned Numbers Authority.)
This document, found at
application/xquery
media type,
which is intended to be used for transmitting queries written in the
XQuery language.
This document was prepared by members of the W3C XML Query Working
Group. Please send comments to public-qt-comments@w3.org,
a public mailing list with archives at
application/xquery
MIME media type name: application
MIME subtype name: xquery
Required parameters: none
Optional parameters: none
The syntax of XQuery is expressed in Unicode but may be written
with any Unicode-compatible character encoding, including UTF-8 or
UTF-16, or transported as US-ASCII or ISO-8859-1 with Unicode
characters outside the range of the given encoding represented using
an XML-style ෝ
syntax.
None known.
The public
This
The most common file extensions in use for XQuery are
.xq
and .xquery
.
The appropriate Macintosh file type code is TEXT
.
The intended usage of this media type is for interchange of XQuery expressions.
XQuery was produced by, and is maintained by, the World Wide Web Consortium's XML Query Working Group. The W3C has change control over this specification.
For use with transports that are not 8-bit clean, quoted-printable encoding is recommended since the XQuery syntax itself uses the US-ASCII-compatible subset of Unicode.
An XQuery document may contain an
An XQuery file may have the string xquery version "V.V"
near the
beginning of the document, where "V.V"
is a version number.
Currently the version number, if present, must be "1.0"
"3.0"
, or "3.1"
XQuery documents use the Unicode character set and, by default, the UTF-8 encoding.
Queries written in XQuery may cause arbitrary URIs or IRIs to be
dereferenced. Therefore, the security issues of file:
URIs can in some cases be
accessed, processed and returned as results. XQuery expressions can invoke any of the functions defined in
fn:doc()
and fn:doc-available()
functions allow local filesystem probes as well as
access to any URI-defined resource accessible from the system
evaluating the XQuery expression.
XQuery is a full declarative programming language, and supports user-defined functions, external function libraries (modules) referenced by URI, and system-specific "native" functions.
Arbitrary recursion is possible, as is arbitrarily large memory usage, and implementations may place limits on CPU and memory usage, as well as restricting access to system-defined functions.
The XML Query Working group is working on a facility to allow XQuery expressions to create and update persistent data. Untrusted queries should not be given write access to data.
The optional XQuery Update Facility allows XQuery expressions to create and update persistent data, potentially including writing to arbitrary locations on the local filesystem as well as to remote URIs. Untrusted queries should not be given write access to data.
Furthermore, because the XQuery language permits extensions,
it is possible that application/xquery
may describe content that has
security implications beyond those described here.
This section contains examples of several important classes of queries that can be expressed using XQuery. The applications described here include joins across multiple data sources, grouping and aggregation, queries based on sequential relationships, recursive transformations, and selection of distinct combinations of values.
This section needs to be rewritten in light of the new features of XQuery 3.0, which can significantly simplify some of these queries.
Joins, which combine data from multiple sources into a single result, are a very important type of query. In this section we will illustrate how several types of joins can be expressed in XQuery. We will base our examples on the following three documents:
A document named parts.xml
that contains many part
elements; each part
element in turn contains partno
and description
subelements.
A document named suppliers.xml
that contains many
supplier
elements; each supplier
element in turn
contains suppno
and suppname
subelements.
A document named catalog.xml
that contains information about the
relationships between suppliers and parts. The catalog document contains many
item
elements, each of which in turn contains
partno
, suppno
, and price
subelements.
A conventional ("inner") join returns information from two or more related sources, as illustrated by the following example, which combines information from three documents. The example generates a "descriptive catalog" derived from the catalog document, but containing part descriptions instead of part numbers and supplier names instead of supplier numbers. The new catalog is ordered alphabetically by part description and secondarily by supplier name.
The previous query returns information only about parts that have suppliers and suppliers
that have parts. An
The following query demonstrates a left outer join. It returns names of all the suppliers in alphabetic order, including those that supply no parts. In the result, each supplier element contains the descriptions of all the parts it supplies, in alphabetic order.
The previous query preserves information about suppliers that supply no parts. Another
type of join, called a supplier
elements, each containing nested
part
elements for the parts that it supplies (if any), followed by a
list of part
elements for the parts that have no supplier. This might be
thought of as a "supplier-centered" full outer join. Other forms of outer join queries
are also possible.
The previous query uses an element constructor to enclose its output inside a
master-list
element. The concatenation operator (",") is used to
combine the two main parts of the query. The result is an ordered sequence of
supplier
elements followed by an orphan-parts
element that
contains descriptions of all the parts that have no supplier.
XQuery uses the <<
and >>
operators to compare
nodes based on document order. Although these operators are quite simple, they can be
used to express complex queries for XML documents in which sequence is meaningful. The
first two queries in this section involve a surgical report that contains
procedure
, incision
, instrument
,
action
, and anesthesia
elements.
The following query returns all the action
elements that occur between the
first and second incision
elements inside the first procedure. The original
document order among these nodes is preserved in the result of the query.
It is worth noting here that document order is defined in such a way that a node is
considered to precede its descendants in document order. In the surgical report, an
action
is never part of an incision
, but an
instrument
is. Since the >>
operator is based on
document order, the predicate $i >> ($proc//incision)[1]
is true for
any instrument
element that is a descendant of the first
incision
element in the first procedure.
For some queries, it may be helpful to declare a function that can test whether a node
precedes another node without being its ancestor. The following function returns
true
if its first operand precedes its second operand but is not an
ancestor of its second operand; otherwise it returns false
:
Similarly, a local:follows
function could be written:
Using the local:precedes
function, we can write a query that finds
instrument
elements between the first two incisions, excluding from the
query result any instrument
that is a descendant of the first
incision
:
The following query reports incisions for which no prior anesthesia was recorded in the
surgical report. Since an anesthesia
is never part of an
incision
, we can use <<
instead of the
less-efficient local:precedes
function:
In some documents, particular sequences of elements may indicate a logical hierarchy.
This is most commonly true of HTML. The following query returns the introduction of an
XHTML document, wrapping it in a div
element. In this example, we assume
that an h2
element containing the text "Introduction" marks the beginning
of the introduction, and the introduction continues until the next h2
or
h1
element, or the end of the document, whichever comes first.
Note that the above query makes explicit the hierarchy that was implicit in the original
document. In this example, we assume that the h2
element containing the
text "Introduction" has no subelements.
Occasionally it is necessary to scan over a hierarchy of elements, applying some transformation at each level of the hierarchy. In XQuery this can be accomplished by defining a recursive function. In this section we will present two examples of such recursive functions.
Suppose that we need to compute a table of contents for a given document by scanning over
the document, retaining only elements named section
or title
,
and preserving the hierarchical relationships among these elements. For each
section
, we retain subelements named section
or
title
; but for each title
, we retain the full content of
the element. This might be accomplished by the following recursive function:
The "skeleton" of a given document, containing only its sections and titles, can then be
obtained by invoking the local:sections-and-titles
function on the root
node of the document, as follows:
As another example of a recursive transformation, suppose that we wish to scan over a
document, transforming every attribute named color
to an element named
color
, and every element named size
to an attribute named
size
. This can be accomplished by the following recursive function
(note that the element constructor in case $e
generates attributes before
child elements):
The transformation can be applied to a whole document by invoking the
local:swizzle
function on the root node of the document, as
follows:
It is sometimes necessary to search through a set of data to find all the distinct
combinations of a given list of properties. For example, an input data set might consist
of a large set of order
elements, each of which has the same basic
structure, as illustrated by the following example:
From this data set, a user might wish to find all the distinct combinations of
product
, size
, and color
that occur together
in an order
. The following query returns this list, enclosing each distinct
combination in a new element named option
:
This appendix lists the changes that have been made to this specification since the publication of the XQuery 3.0 Recommendation.
The following names are now reserved, and cannot appear as function names (see
map
array
If U
is a union type with T
as one of its members, and if E
is an element with T
as its type annotation, the expression now returns true
. In previous versions of XQuery 3.1, it returned false
.
The following substantive changes have been made in this Working Draft.
If a value in a map constructor or a member in an array constructor is a map or array, it is copied. If a value in a map
constructor or a member in an array constructor is a node, it is not copied. Resolves
In the definition of xs:numeric
. Resolves
Modified rule 14 of
In
Changed the semantics of for $a in E, $b in S return $a($b)
. Resolves
Arrays in element content are flattened, not atomized. Resolves
The error when atomizing a function, map, or array is [err:FOTY0013]
, not [err:FOTY0012]
. Resolves
The following are some of the editorial changes that have been made.
Modified the wording used to describe node identity per
Fixed specification gaps in unary lookup. Resolves
If a map key expression is not a single value, raises XPTY0004. Formerly, the error was XQDY0136. Resolves
Clarified error code XQST0134 for XPath implementations that do not support the namespace axis, default axis for namespace-node() in abbreviated syntax. Resolves
Added the serialization options allow-duplicate-names
and json-node-output-method
to
Simplified type conversions for value comparisons and orderspecs, eliminating the concept of lowest common supertype. Resolves
Modified text of
Fixed an example that lists the namespaces for an element node. Resolves
Added
Added
Defined
Added
Defined semantics of element constructors such that arrays in content are atomized to their member sequences.
Added exponent-separator
to the static context to support fn:format-number()
.
Added
Added support for hexBinary and base64binary comparisons to
Eliminated use of to array functions that are no longer in Functions & and Operators, such as fn:seq()
. Changed ay:
prefix to array:
to match current Functions & and Operators.
Added
If the keys in a
In maps, keys of type xs:untypedAtomic
are no longer converted to xs:string
.