This is one document in a set of eight documents that are being progressed to Edited Recommendation together (XPath 2.0, XQuery 1.0, XQueryX 1.0, XSLT 2.0, Data Model (XDM), Functions and Operators, Formal Semantics, Serialization).
This document, published on 14 December 2010, is an Edited
This document has been reviewed by W3C Members, by software developers, and by other W3C groups and interested parties, and is endorsed by the Director as a W3C Recommendation. It is a stable document and may be used as reference material or cited from another document. W3C's role in making the Recommendation is to draw attention to the specification and to promote its widespread deployment. This enhances the functionality and interoperability of the Web.
An implementation report is available at
Please report errors in and submit comments on this document using W3C's
This document was produced by
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.
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 1.0 is an extension of XPath Version 2.0. Any expression that is syntactically valid and executes successfully in both XPath 2.0 and XQuery 1.0 will return the same result in both languages. Since these languages are so closely related, their grammars and language descriptions are generated from a common source to ensure consistency, and the editors of these specifications work together closely.
XQuery also depends on and is closely related to the following specifications:
The type system of XQuery is based on
The built-in function library and the operators supported by
XQuery are defined in
One requirement in
This document specifies a grammar for XQuery, 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 production describes the syntax of a function call:
The production should be read as follows: A function call consists of a QName followed by an open-parenthesis. The open-parenthesis is followed by an optional argument list. The argument list (if present) consists of one or more expressions, separated by commas. The optional argument list is followed by a close-parenthesis.
Certain aspects of language
processing are described in this specification as
This document normatively defines the dynamic semantics of
XQuery. The static semantics of XQuery are normatively defined
in
The basic building block of XQuery is the
This specification contains no
assumptions or requirements regarding the character set encoding of strings
of
Like XML, XQuery is a case-sensitive language. Keywords in
XQuery use lower-case characters and are not reserved—that is, names in XQuery expressions are allowed to be the same as language keywords, except for certain unprefixed function-names listed in
xs:string
. The xs:QName
.
Names in XQuery are called xs:anyURI
type in
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
Element nodes have a property called
In
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
let
,for
,
some
, or every
expression) extends the
The static type of a variable may be either declared in a query or (if the
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 union
, intersect
, and except
expressions, and FLWOR expressions that have no order by
clause.
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:resolve-uri
function.)xs:anyURI
type in
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()*
.
The individual
components of the
The
Certain language constructs, notably the E1/E2
and 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: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: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.
XQuery 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; 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
property.) The type annotation of a node is a
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 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
Each expression is then assigned a
During the
The purpose of the
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
An XQuery implementation is not required to provide a serialization interface. For example, an implementation may only provide
a DOM interface (see
method = "xml"
and version = "1.0"
.
The
In order for XQuery to
be well defined, the input
Some of the consistency constraints use the term
For every node that has a type annotation, if that type annotation is found in the
For every element name
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 includes a declared type, the external environment must provide a value for the variable that matches the declared type, using the matching rules in
For each function declared as external: the
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.
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 fn:error()
function must not be evaluated during the
In addition to the errors defined in this
specification, an implementation may raise a
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.
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 XQuery to another. However, the contents of this namespace may be extended to include additional error definitions.
The method by which an XQuery 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 only raises an 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 the detection and reporting of
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 detecting 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. For example, there is a rule that in casting a string to a QName the operand must be a string literal. This rule applies to the original expression and not to any rewritten form of the expression.
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 expressions.
An ordering called
Document order is a total ordering, although the relative order of some nodes is
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 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
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
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].
The static semantics of fn:boolean
are defined in
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
)
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 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 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: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
In certain places in the XQuery grammar, a statically known valid URI is required. These places are denoted by the grammatical symbol
Syntactically, a URILiteral is identical to a xs:anyURI
.
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 URILiteral is subjected to whitespace normalization as defined for the
xs:anyURI
type in 

does not prevent its
being normalized to a space character.
The URILiteral is not automatically subjected to percent-encoding or decoding
as
defined in
The xs:anyURI
type is designed to
anticipate the introduction of Internationalized Resource Identifiers (IRI's)
as defined in
The following is an example of a valid URILiteral:
The type system of XQuery is based on
xs:NOTATION
or xs:anyAtomicType
, in which case its derived
types can be so used). Every schema type is either a
Atomic types represent the intersection between the categories of xs:integer
or my:hatsize
, is both a
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
The relationships among the schema types in the xs
namespace are illustrated in Figure 2. A more complete description of the XQuery type hierarchy can be found in
Figure 2: Hierarchy of Schema Types used in XQuery
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 atomic type from which it is derived (such as
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
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 expression, the
With the
exception of the special type empty-sequence()
, a item()
, which
permits any kind of item, item types divide into element()
) and xs:integer
).
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
.
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 nodes or atomic values
instance of
expression returns true
if the false
if
it does not.
QNames appearing in a eq
operator.
The rules for
Some of the rules for
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
is
defined below and is defined formally in
derives-from(
)
returns true
if
There exists some schema type derives-from(
)
and derives-from(
)
are true.
derives-from(
)
returns false
if
No schema type derives-from(
)
and derives-from(
)
are true.
derives-from(
)
raises a
The derives-from
pseudo-function cannot be
written as a real XQuery function, because types are not valid
function parameters.
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
. If a QName that is used as an
Example: The
xs:decimal
matches the value
12.34
(a decimal literal). xs:decimal
also
matches a value whose type is shoesize
, if
shoesize
is an atomic type derived by restriction from
xs:decimal
.
The names of non-atomic
types such as xs:IDREFS
are not accepted in this context,
but can often be replaced by an atomic type with an occurrence
indicator, such as
xs:IDREF+
.
item()
matches
any single item.
Example: item()
matches the atomic
value 1
or the element
<a/>
.
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")
.
comment()
matches any comment 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)
.
An
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
schema-element(
)
If the
A
The name of the candidate node matches the specified
derives-from(
)
is true
, where
If the element declaration for
nillable
, then the
nilled
property of the candidate node is false
.
Example: The schema-element(customer)
matches a candidate element node if customer
is a top-level element declaration in the customer
or is in a customer
, the type annotation of the candidate node is the same as or derived from the schema type declared for the customer
element, and either the candidate node is not nilled
or customer
is declared to be nillable
.
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
schema-attribute(
)
If 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.
Comments may be used to provide informative annotation for
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 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 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 represented 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."
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
.
Every variable reference must match a name in the A variable may be declared in a The A variable may be bound by an XQuery expression. typeswitch
expressions (
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 dynamic error
If a variable reference matches two or more variable bindings that are in scope, then the reference is taken as referring to the inner binding, that is, the one whose scope is smaller. At evaluation time, the value of a variable reference is the value of the expression to which the relevant variable is bound. The scope of a variable binding is defined separately for each kind of expression that can bind variables.
Parentheses may be used to enforce a particular evaluation order in
expressions that contain multiple operators. For example, the expression (2 + 4)
* 5
evaluates to thirty, since the parenthesized expression (2 + 4)
is evaluated first and its result is multiplied by five. Without
parentheses, the expression 2 + 4 * 5
evaluates to twenty-two, because the multiplication operator has higher
precedence than the addition operator.
Empty parentheses are used to denote an empty sequence, as
described in
A fn:doc("bib.xml")/books/book[fn:count(./author)>1]
)
or an atomic value (as in the expression (1 to
100)[. mod 5 eq 0]
).
If the
A
If the
A function call is evaluated as follows:
Argument expressions are evaluated, producing argument
values. The order of argument evaluation is
Each argument value is converted by applying the function conversion rules listed below.
If the function is a built-in function, it is evaluated using the converted argument values. The result is either an instance of the function's declared return type or a dynamic error. Errors raised by built-in functions are defined in
If the function is a user-declared function that has a body, the converted argument values are bound to the formal parameters of the function, and the function body is evaluated. The value returned by the function body is then converted to the declared return type of the function by applying the function conversion rules.
When a converted argument
value is bound to a function parameter, the argument
value retains its most specific $p
of type
xs:decimal
can be invoked with an
argument of type xs:integer
, which is
derived from xs:decimal
. During the
processing of this function invocation, the $p
inside the body of the
function is considered to be
xs:integer
. Similarly, the value
returned by a function retains its most specific
type, which may be derived from the declared return
type of the function. For example, a function that
has a declared return type of
xs:decimal
may in fact return a value
of dynamic type xs:integer
.
During evaluation of a function body, the
If the function
is a user-declared external function, its
The
If the
expected type is a sequence of an atomic type
(possibly with an occurrence indicator *
,
+
, or ?
), the following
conversions are applied:
Each item in the atomic
sequence that is of type
xs:untypedAtomic
is cast to the expected
atomic type. For xs:untypedAtomic
are cast to xs:double
.
For each
For each item of type xs:anyURI
in the atomic sequence that can be
If, after the
above conversions, the resulting value does not match
the expected type according to the rules for
Since the arguments of a function call are separated by commas, any
argument expression that contains a top-level
my:three-argument-function(1,
2, 3)
denotes a function call with three arguments.
my:two-argument-function((1,
2), 3)
denotes a function call with two arguments, the first of which is a
sequence of two values.
my:two-argument-function(1,
())
denotes a function call with two arguments, the second of which is an
empty sequence.
my:one-argument-function((1, 2,
3))
denotes a function call with one argument that is a sequence of three
values.
my:one-argument-function(( ))
denotes a function call with one argument that is an empty sequence.
my:zero-argument-function( )
denotes a function call with zero arguments.
/
" 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
(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
(however, "//
" by itself is not a valid path expression
The descendants of a node do not include attribute nodes .
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 operation
E1/E2
is evaluated as follows:
Expression E1
is evaluated,
and if the result is not a (possibly empty) sequence of nodes, a E1
then serves in turn to provide an 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. ordered
, the resulting node sequence is returned in
If every evaluation of E2
returns a (possibly empty) sequence of
atomic values, 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 atomic value, a
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 atomic values.
As an example of a path expression, child::div1/child::para
selects the
para
element children of the div1
element children of the context node, or, in other words, the
para
element grandchildren of the context node
that have div1
parents.
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.
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
(subject to limitations as described in
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.
A QName in a name test is resolved into an
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 QName, using the
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.
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.
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 nondeterministic, as explained in
Otherwise, the predicate truth value is the
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
unless the axis step contains an attribute
. For example, the path expression 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 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 atomic values or nodes, but a sequence is never an item in another sequence. When a new sequence is created by concatenating two or more input sequences, the new sequence contains all the items of the input sequences and its length is the sum of the lengths of the input sequences.
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
.
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
:
The following example also illustrates the use of a filter expression as a tiger
:
XQuery 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
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. Assume that the variables $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 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
The first step in evaluating an arithmetic expression is to evaluate its operands. The order in which the operands are evaluated is
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 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
:
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 for compatibility with
Comparison expressions allow two values to be compared. XQuery 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
If the atomized operand is an empty sequence, the result of the value 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.
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: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
.
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 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
.
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 dynamic error is raised. [err:FORG0001]
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 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 have the same identity, and are thus the same node; otherwise it
is 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 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 QName, and the value of the attribute is specified by a string of characters enclosed in single or double quotes. As in the main content of the element constructor, an attribute value may contain expressions enclosed in curly braces, which are evaluated and replaced by their value during processing of the element constructor.
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 treated as a string 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:
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 type-name
property) of 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
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 xs:anyURI
. The resulting value is used as the namespace
URI in the following rules.
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,
resolved (if it is relative) against the base-uri
property of its new parent
node.
Enclosed expressions are evaluated as follows:
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 type-name
property is set to 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
.
xs:QName
or xs:NOTATION
or is
derived by restriction from xs:QName
or
xs:NOTATION
.
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, resolved (if it is relative) against
the 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 following a node that is not an
attribute 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 dynamic error
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 value of the base-uri
is set to the following value:xml:base
, then the value of this attribute, resolved if it is
relative against the xml:base
attribute is normalized as described in
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.
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
, or comment
.
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 a QName 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 a QName, it is expanded using the 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 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 following a node that is not an
attribute 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 dynamic error
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 value of the base-uri
is set to the following value:xml:base
, then the value of this attribute, resolved if it is
relative against the xml:base
attribute is normalized as described in
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.
If the keyword attribute
is followed by a QName, that QName is expanded using the 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
This step is necessary because attributes have no default namespace. Therefore any attribute name that has a namespace URI must also have a prefix.
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
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
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 dynamic error
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
The properties of the newly constructed document node are determined as follows:
base-uri
is taken from base-uri
property is empty.
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:
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 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 namespace 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 namespaces, a new namespace binding is created for it. If the name of the node includes a prefix, that
prefix is used in the namespace binding; if the name has no prefix, then a
binding is created for the empty prefix. 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
The following query serves as an example:
The p:a
element consists of the following
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
XQuery provides a feature called a FLWOR expression that supports iteration and binding of variables to intermediate results. This
kind of expression is often useful for computing joins between two or more
documents and for restructuring data. The name FLWOR,
pronounced "flower", is suggested by the keywords for
, let
, where
, order by
, and return
.
The for
and let
clauses in a FLWOR expression generate an ordered sequence of tuples of bound variables, called the where
clause serves to filter the tuple stream, retaining some tuples and discarding others. The optional order by
clause can be used to reorder the tuple stream. The return
clause constructs the result of the FLWOR expression. The return
clause is evaluated once for every tuple in the tuple stream, after filtering by the where
clause, using the variable bindings in the respective tuples. The result of the FLWOR
expression is an ordered sequence containing the results of these
evaluations, concatenated as if by the
The following example of a FLWOR expression includes all of the possible clauses. The for
clause iterates over all the departments in an input document, binding the variable $d
to each department number 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. The result of the for
and let
clauses is a tuple stream in which each tuple contains a pair of bindings for $d
and $e
($d
is bound to a department number and $e
is bound to a set of employees in that department). The where
clause filters the tuple stream by keeping only those binding-pairs 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 clauses in a FLWOR expression are described in more detail below.
The purpose of the for
and let
clauses in a FLWOR expression is to produce a tuple stream in which each tuple consists of one or more bound variables.
The simplest example of a for
clause contains one variable and an associated expression. for
clause is called the for
clause iterates over the items in the binding sequence, binding the variable to each item in turn. If ordered
, the resulting sequence of variable bindings is ordered according to the order of values in the binding sequence; otherwise the ordering of the variable bindings is
A for
clause may also contain multiple variables, each with an associated expression whose value is the binding sequence for that variable. In this case, the for
clause iterates each variable over its binding sequence. The resulting tuple stream contains one tuple for each combination of values in the respective binding sequences. If ordered
, the order of the tuple stream is determined primarily by the order of the binding sequence of the leftmost variable, and secondarily by the binding sequences of the other variables, working from left to right. Otherwise, the ordering of the variable bindings is
A let
clause may also contain one or more variables, each with an associated expression. Unlike a for
clause, however, a let
clause binds each variable to the result of its associated expression, without iteration. The variable bindings generated by let
clauses are added to the binding tuples generated by the for
clauses. If there are no for
clauses, the let
clauses generate one tuple containing all the variable bindings.
Although for
and let
clauses both bind variables, the manner in which variables are bound is quite
different, as illustrated by the following examples. The first example uses a let
clause:
The variable $s
is bound to the result of the expression (<one/>,
<two/>, <three/>)
. Since there are no for
clauses, the let
clause generates one tuple that contains the binding of $s
.
The return
clause is invoked for this tuple, creating the following output:
The next example is a similar query that contains a for
clause instead of a let
clause:
In this example, the variable $s
iterates over the given expression. If ordered
, $s
is first bound to <one/>
, then to <two/>
, and finally to <three/>
. One tuple is generated for each of these bindings, and the return
clause is invoked for each tuple, creating the following output:
The following example illustrates how binding tuples are generated by a for
clause that contains multiple variables when ordered
.
The tuple stream generated by the above for
clause is as follows:
If unordered
, the for
clause in the above example would generate the same tuple stream but the order of the tuples would be
The scope of a variable bound in a for
or let
clause comprises all subexpressions of the containing FLWOR expression
that appear after the variable binding. The scope does not
include the expression to which the variable is bound. The following example illustrates how bindings in for
and let
clauses may reference variables that were bound in earlier clauses, or in earlier bindings in the same clause of the FLWOR expression:
The for
and let
clauses of a given FLWOR expression may bind the same variable name more than once. In this case, each new binding occludes the previous one, which becomes inaccessible in the remainder of the FLWOR expression.
Each variable bound in a
for
or let
clause may have an optional
$salary
has a type declaration that is not satisfied by the value that is bound to the variable:
Each variable bound in a for
clause may have an associated at
. The positional variable always has an implied type of xs:integer
. As a variable iterates over the items in its
Positional variables are illustrated by the following for
clause:
If ordered
, the tuple stream generated by the above for
clause is as follows:
If unordered
, the order of the tuple stream is for
clause contains subexpressions that are affected by unordered
.
The optional where
clause serves as a filter for the tuples of variable bindings
generated by the for
and let
clauses. The expression in the where
clause, called the true
, the tuple is retained and its variable bindings are used in an
execution of the return
clause. If the false
, the tuple is discarded. The
The following expression illustrates how a where
clause might be applied to a
The return
clause of a FLWOR expression is evaluated once for each tuple in the tuple stream, and the results of these evaluations are concatenated, as if by the
If no order by
clause is present, the order of the tuple stream is determined by the for
and let
clauses and by order by
clause is present, it reorders the tuples in the tuple stream into a new, value-based order. In either case, the resulting order determines the order in which the return
clause is evaluated, once for each tuple, using the variable bindings in the respective tuples. Note that order by
clause is present, since order by
takes precedence over
An order by
clause contains one or more ordering specifications, called where
clause, the orderspecs are evaluated, using the variable bindings in that tuple. The relative order of two tuples is determined by comparing the values of their orderspecs, working from left to right until a pair of unequal values is encountered. If an orderspec specifies a 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
.
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 T1 and T2 are two tuples in the tuple stream, and V1 and V2 are the first pair of values encountered when evaluating their orderspecs from left to right for which one value is
If V1 is descending
, then T1 precedes T2 in the tuple stream; otherwise, T2 precedes T1 in the tuple stream.
If V2 is descending
, then T2 precedes T1 in the tuple stream; otherwise, T1 precedes T2 in the tuple stream.
If neither V1 nor V2 is
If stable
is specified, the original order of T1 and T2 is preserved in the tuple stream.
If stable
is not specified, the order of T1 and T2 in the tuple stream is
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
.
An order by
clause makes it easy to sort the result of a FLWOR expression, even if the sort key is not included in the result of the expression. For example, the following expression 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 following example illustrates an order by
clause that uses several options. It causes a collection of books to be sorted in primary order by title, and in secondary descending order by price. A specific stable
indicates that their input order is preserved.
Parentheses are helpful in return
clauses that contain comma operators,
since FLWOR expressions have a higher precedence than the comma
operator. For instance, the following query raises an error because
after the comma, $j
is no longer within the FLWOR expression, and is an
Parentheses can be used to bring $j
into the return
clause of the FLWOR expression, as the
programmer probably intended:
The following example illustrates how FLWOR expressions can be nested, and how ordering can be specified at multiple levels of an element hierarchy. The example query inverts a document hierarchy to
transform a bibliography into an author list. The input (bound to the variable $bib
) is a bib
element containing a list of
books, each of which in turn contains a list of authors. The example is based on
the following input:
The following query transforms the input document into a list in which each author's name appears only once, followed by a list of titles of books written by that author. The fn:distinct-values
function is used to eliminate duplicates (by value) from a list of author nodes. The author list, and the lists of books published by each author, are returned in alphabetic order using the
The result of the above expression is as follows:
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
and fn:idref
functions; and FLWOR expressions that have no order by
clause. 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 may be nondeterministic if the expression invokes certain functions that are affected by the ordering of node sequences. These functions include fn:position
, fn:last
, fn:index-of
, fn:insert-before
, fn:remove
, fn:reverse
, and fn:subsequence
. Also, within a (//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 a nondeterministic order. A call to the 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 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:
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
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
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 a return
expression. typeswitch
expression is the first case
clause such that the value of the operand expression matches the 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 case
clause. Inside a 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
Occasionally
it is necessary to convert a value to a specific datatype. For this
purpose, XQuery 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
or xs:anyAtomicType
?
" denotes that an empty
sequence is permitted. If the target type has no namespace prefix, it
is considered to be in the cast
expression
are as follows:
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
If the target type of a
cast
expression is xs:QName
, or is a type
that is derived from xs:QName
or
xs:NOTATION
, and if the base type of the input is not
the same as the base type of the target type, then the input
expression must be a string literal
The reason for this rule is that
construction of an instance of one of these target types from a
string requires knowledge about namespace bindings. If the input
expression is a non-literal string, it might be derived from an
input document whose namespace bindings are different from the
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 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
provides an expression that tests whether a given value
is castable into a given target type. The target
type must be an atomic type that is in the xs:NOTATION
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
If the target type of a castable
expression is xs:QName
, or is a type that is derived from xs:QName
or xs:NOTATION
, and the input argument of the expression is of type xs:string
but it is not a literal string, the result of the castable
expression is false
.
For every atomic type in the 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 constructor functions for xs:QName
and for types derived from xs:QName
and xs:NOTATION
require their arguments to be string literals or to have a base type that is the same as the base type of the target type; otherwise a type error cast
expressions for these types, as defined in
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 a
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 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
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
. 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 (
Validity assessment is carried out on the root element information item of the resulting Infoset, using the
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 item
3 of
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)" is 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
.
There is no check that the document contains notations whose names match the values of nodes of type xs:NOTATION
.
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 next step depends on 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
(for any 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: If strict
, the validated element must have a top-level element declaration in the effective schema, and must conform to this declaration. If 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. The validated element corresponds either to the operand node or (if the operand node is a document node) to its element child.
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 QName followed by #)
. The QName of a
pragma must resolve to a namespace URI and local name, using the
Since there is no default namespace for pragmas, a pragma QName must include a namespace prefix.
Each implementation recognizes an
If the namespace part of a pragma QName is not recognized by the
implementation as a pragma namespace, then the pragma
is ignored. If all the pragmas in an
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.
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 resolved to an absolute URI using the
fn:doc
function resolves a relative URI using the base URI of the
calling module.
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.
/
" or "//
" operator or an union
, intersect
, and except
expressions; and FLWOR expressions that have no order by
clause. If ordering mode is ordered
, node sequences returned by path, union
, intersect
, and except
expressions are in
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
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 may 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.
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) to the
Each
A module may import its own target namespace (this is interpreted as importing an
It is a
An
in the type of a variable that is declared in the imported module and referenced in the importing module, OR
in a parameter-type or result-type of a function that is declared in the imported module and referenced in the importing module.
An EN
such that:
schema-element(EN)
appears in the declared
type of a variable
in the imported module, and that variable is referenced
in the importing module, OR
schema-element(EN)
appears in a parameter-type or
result-type of a function declared in the imported module, and
that function is referenced in the importing module.
An AN
such that:
schema-attribute(AN)
appears in the declared
type of a variable
in the imported module, and that variable is referenced
in the importing module, OR
schema-attribute(AN)
appears in a parameter-type
or result-type
of a function declared in the imported module, and that function
is referenced in the importing module.
To illustrate the above rules, suppose that a certain schema defines a type named triangle
. Suppose that a library module imports the schema, binds its target namespace to the prefix geometry
, and declares a function with the following math:area($t as geometry:triangle) as xs:double
. If a query wishes to use this function, it must import geometry:triangle
used in the signature of the area
function.
The following example illustrates a module import:
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
may 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.
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.
A eq
operator) to the name of another variable in
If a
variable declaration includes a type, that type is added to
the
$x
$y
or a function f2
if a reference to $y
or f2
appears in
the initializing expression of $x
, or if there exists a variable $z
or a function f3
such that $x
$z
or f3
and $z
or f3
$y
or f2
.
f1
$y
or
a function f2
if a reference to $y
or f2
appears in the body of f1
, or if there exists a variable $z
or a function f3
such that f1
$z
or f3
and $z
or f3
$y
or f2
.
If a variable
If the variable declaration
includes the keyword external
, a value must be
provided for the variable by the external environment before
the query can be evaluated. If an external variable declaration also includes a declared type, the value provided by the external environment must match the declared type according to the rules for item()*
. Any reference to a variable that was declared external
, but was not bound to a value by the external environment, raises a dynamic error
All variable names declared in a
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.
The term
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 type
error is raised.
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:
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.
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
.
Every user-defined 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
It is a eq
operator) to the
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
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.
Rules for converting function arguments to their declared parameter types, and for converting the result of a function to its declared result type, are described in
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. In its declaration, the
user-declared 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
.
Since a
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.
The QName of an option must resolve to a namespace URI and local name, using the
There is no default namespace for options.
Each implementation recognizes an
If the namespace part of the QName is not a namespace recognized by the implementation as one used to denote option declarations, then the option declaration is ignored.
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 static errors. However, it may be
used without restriction to modify the semantics of the query. The scope of
the option declaration is
The following examples illustrate several possible uses for option declarations:
This option declaration might be used to set a serialization parameter:
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:
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
Minimal Conformance to this specification
Support for 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
Support for
Support for all functions defined in
If an XQuery implementation does not support the Schema Import Feature, it
If an implementation does not support the Schema Import Feature, the
validate
expression (see
If an XQuery implementation does not support the Schema Validation Feature, it
validate
expression.
If an implementation does not support the
An implementation that does not support the
In some cases, the static typing rules defined in fn:root
). Some
implementations may wish to support more precise static typing rules.
A conforming implementation that implements the
ancestor
,
ancestor-or-self
, following
,
following-sibling
, preceding
, and
preceding-sibling
.
Conforming XQuery implementations that do not support the Full Axis Feature
XQuery does not recognize the namespace
axis (defined by XPath 1.0
and deprecated by XPath 2.0).
A conforming implementation that does not support the Module Feature
In the absence of the Module Feature, each query consists of a single
A conforming XQuery implementation that supports the Serialization Feature
If an error is raised during the serialization process as specified in
Not all implementations need to serialize. For instance, an implementation might provide results via an XML API instead of producing a textual representation.
All XQuery implementations process data represented in the
At the time of writing there is no published version of XML Schema that references the XML 1.1 specifications. This means that datatypes such as xs:NCName
and xs:ID
are constrained by the XML 1.0 rules. It is recommended that an XQuery 1.0 processor should implement defined by later versions of XML Schema as they become available.
For suggestions on processing XML 1.1 documents, 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.
Any syntactic extensions to XQuery are
The grammar of XQuery 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 legal 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 legal without parentheses.
An implementation's choice to support the prefix : localname
is not a valid QName for purposes
of this specification, just as it is not permitted in a XML document.
Also, comments are not permissible on either side of the colon. Also extra-grammatical constraints such as well-formedness constraints must be taken into account.
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 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
This rule has as a consequence that certain forms which
would otherwise be legal 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 legal Comment, since balanced nesting of comments is allowed.
"this is just a string :)"
is a legal expression. However, (: "this is just a string :)" :)
will cause a syntax error. Likewise, "this is another string (:"
is a legal 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 legal, ignoring the comment.
5 instance (: strange place for a comment :) of xs:integer
is also syntactically legal.
<eg (: an example:)>{$i//title}</eg>
is not syntactically legal.
<eg> (: an example:) </eg>
is syntactically legal, 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
It is
When tokenizing, the longest possible match that is valid in the current context is used.
All keywords are case sensitive. Keywords are not reserved—that is, any QName may duplicate a keyword except as noted in
The following symbols are used only in the definition of
terminal symbols; they are not terminal symbols in the
grammar of
XQuery 1.0 expressions consist of
Terminal symbols that are not used exclusively in
It is customary to separate consecutive terminal symbols by
The XQuery processor must behave as if it normalized all line breaks on input, before parsing. The normalization should be done according to the choice to support either
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.
attribute
comment
document-node
element
empty-sequence
if
item
node
processing-instruction
schema-attribute
schema-element
text
typeswitch
The grammar in
# | Operator | Associativity |
---|---|---|
1 | , (comma) | left-to-right |
2 | := (assignment) | right-to-left |
3 | left-to-right | |
4 | left-to-right | |
5 | left-to-right | |
6 | left-to-right | |
7 | left-to-right | |
8 | left-to-right | |
9 | left-to-right | |
10 | left-to-right | |
11 | left-to-right | |
12 | left-to-right | |
13 | left-to-right | |
14 | left-to-right | |
15 | left-to-right | |
16 | right-to-left | |
17 | left-to-right | |
18 | left-to-right | |
19 | left-to-right |
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
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
.+
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:hex-binary-equal(A, B) | xs:boolean |
A eq B | xs:base64Binary | xs:base64Binary | op:base64-binary-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 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:hex-binary-equal(A, B)) | xs:boolean |
A ne B | xs:base64Binary | xs:base64Binary | fn:not(op:base64-binary-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 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 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 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 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 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()* |
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 a query? | Scope | Consistency rules |
---|---|---|---|---|---|
XPath 1.0 Compatibility Mode | false | no | no | global | Must be false . |
Statically known namespaces | fn , xml , xs , xsi , local | overwriteable and augmentable (except for xml ) | overwriteable and augmentable by prolog or element constructor | lexical | Only one namespace can be assigned to a given prefix per lexical scope. |
Default element/type namespace | no namespace | overwriteable | overwriteable by prolog or element constructor | lexical | Only one default namespace per lexical scope. |
Default function namespace | fn | overwriteable (not recommended) | overwriteable by prolog | module | None. |
In-scope schema types | built-in types in xs | augmentable | augmentable by schema import in prolog | module | Only one definition per global or local type. |
In-scope element declarations | none | augmentable | augmentable by schema import in prolog | module | Only one definition per global or local element name. |
In-scope attribute declarations | none | augmentable | augmentable by schema import in prolog | module | Only one definition per global or local attribute name. |
In-scope variables | none | augmentable | overwriteable and augmentable by prolog and by variable-binding expressions | lexical | Only one definition per variable per lexical scope. |
Function signatures | functions in fn namespace, and constructors for built-in atomic types | augmentable | augmentable by module import and by function declaration in prolog; augmentable by schema import (which adds constructor functions for user-defined types) | module | Each function must have a unique expanded QName and number of arguments. |
Statically known collations | only the default collation | augmentable | no | module | Each URI uniquely identifies a collation. |
Default collation | Unicode codepoint collation | overwriteable | overwriteable by prolog | module | None. |
Construction mode | preserve | overwriteable | overwriteable by prolog | module | Value must be preserve or strip . |
Ordering mode | ordered | overwriteable | overwriteable by prolog or expression | lexical | Value must be ordered or unordered . |
Default order for empty sequences | implementation-defined | overwriteable | overwriteable by prolog | module | Value must be greatest or least . |
Boundary-space policy | strip | overwriteable | overwriteable by prolog | module | Value must be preserve or strip . |
Copy-namespaces mode | inherit, preserve | overwriteable | overwriteable by prolog | module | Value consists of inherit or no-inherit , and preserve or no-preserve . |
Base URI | See rules in | overwriteable | overwriteable by prolog | module | Value must be a valid lexical representation of the type xs:anyURI. |
Statically known documents | none | augmentable | no | module | None. |
Statically known collections | none | augmentable | no | module | None. |
Statically known default collection type | node()* | overwriteable | no | module | None. |
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 a query? | Scope | Consistency rules |
---|---|---|---|---|---|
Context item | none | overwriteable | overwritten during evaluation of path expressions and predicates | dynamic | None |
Context position | none | overwriteable | overwritten during evaluation of path expressions and predicates | dynamic | If context item is defined, context position must be >0 and <= context size; else context position is |
Context size | none | overwriteable | overwritten during evaluation of path expressions and predicates | dynamic | If context item is defined, context size must be >0; else context size is |
Variable values | none | augmentable | overwriteable and augmentable by prolog and by variable-binding expressions | dynamic | Names and values must be consistent with in-scope variables. |
Function implementations | functions in fn namespace, and constructors for built-in atomic types | augmentable | augmentable by module import and by function declaration in prolog; augmentable by schema import (which adds constructor functions for user-defined types) | global | Must be consistent with function signatures |
Current dateTime | none | must be initialized by implementation | no | global | Must include a timezone. Remains constant during evaluation of a query. |
Implicit timezone | none | must be initialized by implementation | no | global | Remains constant during evaluation of a query. |
Available documents | none | must be initialized by implementation | no | global | None |
Available collections | none | must be initialized by implementation | no | global | None |
Default collection | none | overwriteable | no | global | None |
The following table specifies default values for the parameters that control the process of serializing an method = "xml"
). The meanings of the various parameters are defined in
Parameter | Default Value |
---|---|
byte-order-mark | implementation-defined |
cdata-section-elements | empty |
doctype-public | (none) |
doctype-system | (none) |
encoding | implementation-defined choice between "utf-8" and "utf-16" |
escape-uri-attributes | (not applicable when method = xml) |
include-content-type | (not applicable when method = xml) |
indent | no |
media-type | implementation-defined |
method | xml |
normalization-form | implementation-defined |
omit-xml-declaration | implementation-defined |
standalone | implementation-defined |
undeclare-prefixes | no |
use-character-maps | empty |
version | implementation-defined |
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.
Whether the implementation is based on the rules of
Any components of the
Which of the
The default handling of empty sequences returned by an ordering key (sortspec) 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
Any
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
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()
.
(Not currently used.)
(Not currently used.)
It is a
An implementation that does not support the Schema Import Feature must raise a
An implementation must raise a
It is a
It is a
(Not currently used.)
(Not currently used.)
An implementation that does not support the Module Feature raises a
It is a
It is a
It is a
It is a
(Not currently used.)
It is a
(Not currently used.)
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
.
(Not currently used.)
(Not currently used.)
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
An
in the type of a variable that is declared in the imported module and referenced in the importing module, OR
in a parameter-type or result-type of a function that is declared in the imported module and referenced in the importing module.
An EN
such that:
schema-element(EN)
appears in the declared
type of a variable
in the imported module, and that variable is referenced
in the importing module, OR
schema-element(EN)
appears in a parameter-type or
result-type of a function declared in the imported module, and
that function is referenced in the importing module.
An AN
such that:
schema-attribute(AN)
appears in the declared
type of a variable
in the imported module, and that variable is referenced
in the importing module, OR
schema-attribute(AN)
appears in a parameter-type
or result-type
of a function declared in the imported module, and that function
is referenced in the importing module.
(Not currently used.)
It is a
It is a
It is a
It is a xs:NCName
.
(Not currently used.)
(Not currently used.)
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
.
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
(Not currently used.)
(Not currently used.)
It is a
It is a
(Not currently used.)
It is a
It is a
It is a
It is a
It is a
(Not currently used.)
(Not currently used.)
It is a
A
A
A
A
A
A xml
or xmlns
appears in a namespace declaration, or if any of the following conditions
is statically detected in any expression or 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
(Not currently used.)
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
(Not currently used.)
(Not currently used.)
It is a
It is a
cast
or castable
expression is xs:NOTATION
or xs:anyAtomicType
.
It is a
(Not currently used.)
(Not currently used.)
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
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
.
It is a
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
.
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 with Unicode
characters outside the range of the given encoding represented using
an XML-style ෝ
syntax.
None known.
This media type registration is for XQuery queries as described
by the XQuery 1.0 specification, which is located at
The public
This new media type is being registered to allow for deployment of XQuery on the World Wide Web.
The most common file extensions in use for XQuery are
.xq
and .xquery
.
The appropriate Macintosh file type code is TEXT
.
COMMON
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"
.
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.
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.
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.
Many queries
involve forming data into groups and
applying some aggregation function
such as fn:count
or
fn:avg
to each group. The
following example shows how such a
query might be expressed in XQuery,
using the catalog document defined in
the previous section.
This query finds the part number and average price for parts that have at least 3 suppliers.
The fn:distinct-values
function
in this query eliminates duplicate
part numbers from the set of all part
numbers in the catalog document. The
result of fn:distinct-values
is a
sequence in which order is not
significant.
Note that $pn
, bound by a
for clause, represents an individual
part number, whereas $i
, bound by a
let clause, represents a set of items
which serves as argument to the
aggregate functions
fn:count($i)
and
fn:avg($i/price)
. The query
uses an element constructor to enclose
each part number and average price in
a containing element called
well-supplied-item
.
The method illustrated above generalizes easily to grouping by more than one data value. For example, consider a census document containing a sequence of person
elements, each with subelements named state
, job
, and income
. A census analyst might need to prepare a report listing the average income
for each combination of state
and job
. This report might be produced using the following query:
The if-then-else
expression in the above example prevents generation of groups that contain no data. For example, the census data may contain some persons who live in Nebraska, and some persons whose job is Deep Sea Fisherman, but no persons who live in Nebraska and have the job of Deep Sea Fisherman. If output groups are desired for all possible combinations of states and jobs, the if-then-else
expression can be omitted from the query. In this case, the output may include "empty" groups such as the following:
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 define 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 specification gives considerable flexibility to implementations in the way that modules are implemented, in particular, in the way that module URIs and their location URIs are interpreted. This flexibility is intentional, because XQuery implementations are designed to operate in a wide variety of environments, and some of those environments impose constraints. Nevertheless, in the interests of interoperability, the Working Group hopes that it will be useful to offer some suggestions for how implementations might choose to interpret the specification, in the absence of implementation factors that make a different interpretation necessary.
Generally, Module URIs should be treated in the same way as other namespace URIs.
Query authors should use a string that is a legal absolute IRI. Implementors should accept any string of Unicode characters. Module URIs should be compared using the Unicode codepoint collation rather than any concept of semantic equivalence.
Implementations may provide mechanisms allowing the module 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 module URI to obtain the names of related resources, for example to implement a convention relating the name or location of compiled code to the module URI; but again, such mechanisms should not prevent the user from choosing an arbitrary module URI.
As with other namespace URIs, common practice is often to use module 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 module URI of a function library to be the same as the namespace URI of the XML vocabulary manipulated by the functions in that library.
The specifications allow several different modules with the same Module URI to participate in a query.
Although other interpretations are possible, it is suggested that in such cases implementations should require the names of global variables and functions to be unique within the query as a whole: that is, if two modules with the same module URI participate in a query, the names of their global variables and functions should not overlap.
If one module contains an "import module" declaration for the module URI M, then all global variables and functions declared in participating modules whose module URI is M should be accessible in the importing module, regardless whether the participation of the imported module was directly due to this "import module" declaration.
There should only be one instance of a global variable with any given name. For example, if a global variable V is initialized using an element constructor, then there should only be one instance of this element, even if the module in which V is declared is imported by several other modules.
(A different approach to this might be used in an environment where a group of modules can be compiled as a unit; in such cases a module used within the compiled unit might be considered distinct from an instance of the same module imported from elsewhere in the query.)
The term "location URIs" is used here to refer 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 module URI. Location URIs should be made absolute with respect to the static base URI of the query 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 should be loaded. When different absolutized location URIs are used, each should result 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.
By default, implementations should report a static error if a location URI cannot be resolved. However, this is not intended to disallow recovery strategies being used if appropriate.
It is not an error to have a cycle in the import graph, either at the level of module URIs or at the level of location URIs. The only rules concerning cycles affect the relationships between functions and variables defined in different modules.
This version of the XQuery specification was created by applying the errata from
Erratum | Bugzilla | Category | Description |
|
| substantive | Specifies that error XQTY0086 applies to copied attribute nodes as well as copied element nodes, including copied attribute nodes that have no parent. The error is raised when construction-mode calls for the type of a QName to be preserved, but copy-namespaces-mode does not preserve the namespace binding that is needed by the QName. |
|
| substantive | Reverses the order of Rules 1 and 2 in XQuery Section 3.7.3.1, Computed Element Constructors (processing of content sequence). Also reverses the order of Rules 1 and 2 in Section 3.7.3.3, Document Node Constructors. These changes are necessary in order to cause document nodes to be replaced by their children before adjacent text nodes are merged. |
|
| editorial | For valid syntax, adds parentheses to the expansion for leading "/" and leading "//" in a path expression. |
|
| substantive | Adds more details to the rules defining permissible expression rewrites for optimization and other purposes. |
|
| substantive | Clarifies the conditions under which a castable expression may raise an error. |
|
| substantive | Tightens the rules for the in-scope schema definitions that must be present in an importing module. For example, if the imported module contains a function definition that includes a parameter of type schema-element(EN) and that function is referenced in the importing module, then the importing module must have an in-scope element declaration for EN. |
|
| substantive | In Section 3.13 (Validate Expression), Rule 3c, deletes "Identity-constraint Satisfied" from the list of rules that are not applied during validation. This rule must be applied. |
|
| substantive | Deletes error code XQST0073, because it is redundant to error code XQST0093. |
|
| substantive | Specifies that, in a computed attribute constructor, if the QName of the constructed attribute has a namespace URI but no prefix, an implementation-dependent prefix is generated. |
|
| editorial | Clarifies that the default initial static type of the context item is undefined. |
|
| editorial | Clarifies behavior of node constructors when base-URI in static context is undefined. |
|
| substantive | Specifies that an error results if the PITarget specified in a SequenceType of form processing-instruction(PITarget) is not a syntactically valid NCName. |
|
| substantive | Disallows enclosed expressions inside a namespace declaration attribute, and clarifies handling of consecutive curly-braces, consecutive single-quotes, and consecutive double-quotes inside attribute values. |
|
| editorial | Calls attention to the entry in Appendix C that defines the initial values for context item, position, and size, which can be referenced in initializing expressions in variable declarations. |
|
| editorial | Removes references to error code FORG0001 from description of cast expression. Replaces them with a reference to Functions and Operators for normative description of error behavior. |
|
| editorial | Deletes unnecessary reference to RFC2396 from Normative References. This item is never referenced in the normative text. |
|
| substantive | Specifies that, in the order-by clause of a FLWOR expression, a user-specified collation applies only if the value of the ordering expression is of type xs:string or is convertible to xs:string. |
|
| substantive | Specifies that general comparisons cast an untyped operand to the primitive base type of the other operand rather than to the most specific type of the other operand. |
|
| substantive | Specifies rules that prevent the redefinition of certain predefined namespace prefixes. |
|
| editorial | Corrects a list of examples of primitive atomic types. |
|
| substantive | Allows (and encourages) the use of XML 1.0 editions newer than the Third Edition. |
|
| substantive | Specifies conformance criteria for syntax extensions. |
|
| editorial | Defines the meaning of "undefined" for Data Model properties. |
|
| substantive | Clarifications on parsing leading / in XPath expressions. |
|
| editorial | Adds a missing word to an error description. |
|
| substantive | Corrects the description of precedence with respect to parentheses and square brackets. |
|
| substantive | Specifies that leading and trailing whitespace are stripped from a PITarget specified in a SequenceType of form processing-instruction(PITarget) before it is tested to see if it is a syntactically valid NCName. Also makes the description of the error introduced in E12 more precise. If accepted, this supersedes E12. |
|
| substantive | A new non-normative appendix designed to give guidance on the handling of modules. |
|
| editorial | State more explicitly that user-defined types in an imported schema add constructors for these types to the set of known function signatures. |
|
| editorial | Fixes an example by replacing the undefined variable <partno> {$p} </partno> with <partno> {$pn} </partno>). |
(None.) | (None.) | editorial | In |
(None.) | (None.) | Editorial | In |