W3C

XQuery 1.0: An XML Query Language

W3C Working Draft 20 December 2001

This version:
http://www.w3.org/TR/2001/WD-xquery-20011220
Latest version:
http://www.w3.org/TR/xquery
Previous versions:
http://www.w3.org/TR/2001/WD-xquery-20010607
Editors:
Scott Boag (XSL WG), IBM Research <scott_boag@us.ibm.com>
Don Chamberlin (XML Query WG), IBM Almaden Research Center <chamberlin@almaden.ibm.com>
Mary F. Fernandez (XML Query WG), AT&T Labs <mff@research.att.com>
Daniela Florescu (XML Query WG)
Jonathan Robie (XML Query WG), Software AG <Jonathan.Robie@SoftwareAG-USA.com>
Jérôme Siméon (XML Query WG), Bell Labs, Lucent Technologies <simeon@research.bell-labs.com>
Mugur Stefanescu (XML Query WG), Concentric Visions <MStefanescu@Concentricvisions.com>

Abstract

XML is an extremely 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. Because query languages have traditionally been designed for specific kinds of data, most existing proposals for XML query languages are robust for particular types of data sources but weak for other types. This specification describes a query language called XQuery, which is designed to be broadly applicable across all types of XML data sources.

Status of this Document

This is a public W3C Working Draft for review by W3C Members and other interested parties. This section describes the status of this document at the time of its publication. It is a draft document and may be updated, replaced, or obsoleted by other documents at any time. It is inappropriate to use W3C Working Drafts as reference material or to cite them as other than "work in progress." A list of current public W3C technical reports can be found at http://www.w3.org/TR/.

Much of this document is the result of joint work by the XML Query and XSL Working Groups, which are jointly responsible for XPath 2.0, a language derived from both XPath 1.0 and XQuery. The XPath 2.0 and XQuery 1.0 Working Drafts are generated from a common source. These languages are closely related, sharing much of the same expression syntax and semantics, and much of the text found in the two Working Drafts is identical. The current version of this document is the first publicly released Working Draft containing the results of integrating these languages.

This document is a work in progress. It contains many open issues, and should not be considered to be fully stable. Vendors who wish to create preview implementations based on this document do so at their own risk. While this document reflects the general consensus of the working groups, there are still controversial areas that may be subject to change.

Comments on this document should be sent to the W3C XML Query mailing list www-xml-query-comments@w3.org (archived at http://lists.w3.org/Archives/Public/www-xml-query-comments/).

XQuery 1.0 has been defined jointly by the XML Query Working Group (part of the XML Activity) and the XSL Working Group (part of the Style Activity).

Table of Contents

1 Introduction
2 Expressions
    2.1 Basics
        2.1.1 Expression Context
            2.1.1.1 Static Context
            2.1.1.2 Evaluation Context
        2.1.2 Type Conversions
    2.2 Primary Expressions
        2.2.1 Literals
        2.2.2 Variables
        2.2.3 Parenthesized Expressions
        2.2.4 Function Calls
        2.2.5 Comments
    2.3 Path Expressions
        2.3.1 Axis Steps
            2.3.1.1 Axes
            2.3.1.2 Node Tests
        2.3.2 General Steps
        2.3.3 Step Qualifiers
            2.3.3.1 Predicates
            2.3.3.2 Dereferences
        2.3.4 Unabbreviated Syntax
        2.3.5 Abbreviated Syntax
    2.4 Sequence Expressions
        2.4.1 Constructing Sequences
        2.4.2 Combining Sequences
    2.5 Arithmetic Expressions
    2.6 Comparison Expressions
        2.6.1 Value Comparisons
        2.6.2 General Comparisons
        2.6.3 Node Comparisons
        2.6.4 Order Comparisons
    2.7 Logical Expressions
    2.8 Constructors
        2.8.1 Element Constructors
        2.8.2 Computed Element and Attribute Constructors
        2.8.3 Other Constructors and Comments
    2.9 FLWR Expressions
    2.10 Sorting Expressions
    2.11 Conditional Expressions
    2.12 Quantified Expressions
    2.13 Datatypes
        2.13.1 Referring to Datatypes
        2.13.2 Expressions on Datatypes
3 The Query Prolog
    3.1 Namespace Declarations and Schema Imports
    3.2 Function Definitions
4 Example Applications
    4.1 Filtering
    4.2 Joins
    4.3 Grouping
    4.4 Queries on Sequence

Appendices

A Complete BNF
    A.1 Grammar
    A.2 Precedence Order
    A.3 Lexical structure
        A.3.1 Lexical States
B References
    B.1 Normative References
    B.2 Non-normative References
    B.3 Background References
    B.4 Informative Material
C Glossary
D XPath 2.0 and XQuery 1.0 Issues (Non-Normative)
E Revision Log (Non-Normative)
    E.1 20 Dec 2001


1 Introduction

As increasing amounts of information are stored, exchanged, and presented using XML, the ability to intelligently query XML data sources becomes increasingly important. One of the great strengths of XML is its flexibility in representing many different kinds of information from diverse sources. To exploit this flexibility, an XML query language must provide features for retrieving and interpreting information from these diverse sources.

XQuery is designed to meet the requirements identified by the W3C XML Query Working Group [XML Query 1.0 Requirements] and the use cases in [XML Query Use Cases]. It is designed to be a small, easily implementable language in which queries are concise and easily understood. It is also flexible enough to query a broad spectrum of XML information sources, including both databases and documents. The Query Working Group has identified a requirement for both a human-readable query syntax and an XML-based query syntax. XQuery is designed to meet the first of these requirements. XQuery is derived from an XML query language called Quilt [Quilt], which in turn borrowed features from several other languages, including XPath 1.0 [XPath 1.0], XQL [XQL], XML-QL [XML-QL], SQL [SQL], and OQL [ODMG].

XQuery Version 1.0 contains XPath Version 2.0 as a subset. 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:

XQuery is a strongly typed language. Rules for assigning types to XQuery expressions are described in [XQuery 1.0 Formal Semantics]. A query may import type definitions from a Schema, according to rules that will be specified in a future edition of [XQuery 1.0 Formal Semantics].

Processing a query involves a static typing phase and a dynamic evaluation phase. The type system of XQuery is sound, in that the value yielded by dynamic evaluation is guaranteed to be an instance of the type assigned by static typing.

At user option, static typing can be disabled. A query that passes type checking will return the same result regardless of whether type checking is enabled or disabled. [Ed. Note: See Issues 41 and 55 for a further discussion of static vs. dynamic semantics.]

XQuery may have multiple conformance levels. There may be a conformance level that does not include static type checking. There may be a conformance level that does not support Schema import or reference of types other than the built-in types. [Ed. Note: See Issue 42 for a further discussion of conformance levels.]

2 Expressions

2.1 Basics

The basic building block of XQuery is the expression. The language provides several kinds of expressions which may be constructed from keywords, symbols, and operands. In general, the operands of an expression are other expressions. XQuery is a functional language which allows various kinds of expressions to be nested with full generality. It is also a strongly-typed language in which the operands of various expressions, operators, and functions must conform to designated types.

Like XML, XQuery is a case-sensitive language. All keywords in XQuery use lower-case characters.

[4]   Expr   ::=   SortExpr
|  OrExpr
|  AndExpr
|  FLWRExpr
|  QuantifiedExpr
|  TypeswitchExpr
|  IfExpr
|  GeneralComp
|  ValueComp
|  NodeComp
|  OrderComp
|  InstanceofExpr
|  RangeExpr
|  AdditiveExpr
|  MultiplicativeExpr
|  UnionExpr
|  IntersectExceptExpr
|  UnaryExpr
|  CastExpr
|  Constructor
|  PathExpr

Note:

For the grammar productions in the main body of this document, the same Basic EBNF notation is used as in [XML], except that grammar symbols always have initial capital letters. The EBNF contains only non-terminals, and all terminal tokens are expanded for readability. Optional whitespace is not represented. A normative version of the EBNF that includes tokens and token states is presented in the appendix [A Complete BNF].

Note:

The use of a prefix token ":" is allowed on unprefixed QNames to lexically distinguish tokens that are spelled the same as keywords.. For instance, the following is a path expression containing the element names "for", "where", and "return": :for/:where/:return.

The value of an expression is always a sequence. A sequence is an ordered collection of zero or more items. An item is either a simple value or a node. A simple value consists of a value contained in the value space of one of the primitive datatypes described in [XML Schema], together with a reference to a schema component that describes its type. Schema components are defined in [XQuery 1.0 and XPath 2.0 Data Model]. A node conforms to one of the seven node kinds described in [XQuery 1.0 and XPath 2.0 Data Model]. Some kinds of nodes have typed values, string values, and names, which can be extracted from the node using accessors. The typed value of a node is a sequence of zero or more simple values. The string value of a node is an instance of the type xs:string. The name of a node is an instance of the type xs:QName.

A sequence containing exactly one item is called a singleton sequence. A sequence containing zero items is called an empty sequence.

In this document, the namespace prefix xs: is considered to be bound to the XML Schema namespace http://www.w3.org/2001/XMLSchema (described in [XML Schema]), and the prefix xf: is considered to be bound to the namespace of XPath/XQuery functions and operators, http://www.w3.org/2001/12/xquery-operators (described in [XQuery 1.0 and XPath 2.0 Functions and Operators]).

2.1.1 Expression Context

The expression context for a given expression consists of all the information that can affect the result of the expression. This information is organized into two categories called the static context and the evaluation context.

This section describes the context information used by XQuery expressions, including the functions in the core function library. Other functions, outside the core function library, may require additional context information.

2.1.1.1 Static Context

The static context of an expression is defined as all information that is available during static analysis of the expression, prior to its evaluation. This information can be used to decide whether the expression contains a static error.

In XQuery, the information in the static context is provided by declarations in the query prolog (except as noted below). Static context consists of the following components:

  • In-scope namespaces. This is a set of (prefix, URI) pairs. The in-scope namespaces are used for resolving prefixes used on QNames within the expression.

  • Default namespace for element names. This is a namespace URI. This namespace is used for any unprefixed QName appearing in a position where an element name is expected.

  • Default namespace for function names. This is a namespace URI. This namespace is used for any unprefixed QName appearing as the function name in a function call.

  • In-scope type definitions. This is a set of (QName, type definition) pairs. It defines the set of types that are available for reference within the expression.

  • In-scope variables. This is a set of (QName, type) pairs. It defines the set of variables that have been declared and are available for reference within the XPath expression. The QName represents the name of the variable, and the type represents its static data type.

    Unlike the other parts of the static context, variable types are not declared in the query prolog. Instead, they are derived from static analysis of the expressions in which the variables are bound.

  • In-scope functions. This is a set of (QName, function signature) pairs. It defines the set of functions that are available to be called from within the expression. The QName represents the name of the function, and the function signature specifies the static types of the function parameters and function result.

  • In-scope collations. This is a set of (QName, collation) pairs. It defines the names of the collations that are available for use in function calls that take a collation name as an argument. A collation may be regarded as an object that supports two functions: a function that given a set of strings, returns a sequence containing those strings in sorted order; and a function that given two strings, returns true if they are considered equal, and false if not.

  • Default collation. This is a collation. This collation is used by string comparison functions when no explicit collation is specified.

  • Base URI. This is an absolute URI, used by the xf:document function when resolving the relative URI of a document to be loaded, if no explicit base URI is supplied in the function call.

2.1.1.2 Evaluation Context

The evaluation context of an expression is defined as information that is available at the time the expression is evaluated. The evaluation context consists of all the components of the static context, and the additional components listed below.

The first four components of the dynamic context (context item, context position, context size, and context document) are called the focus of the expression. The focus enables the processor to keep track of which nodes are being processed by the expression.

The focus for the outermost expression is supplied by the environment in which the expression is evaluated. Certain language constructs, notably the path expression E1/E2 and the filter expression E1[E2], create a new focus for the evaluation of a sub-expression. In both these constructs, E2 is evaluated once for each item in the sequence that results from evaluating E1. Each time E2 is evaluated, it is evaluated with a different focus. The focus for evaluating E2 is referred to below as the inner focus, while the focus for evaluating E1 is referred to as the outer focus. The inner focus exists only while E2 is being evaluated. When this evaluation is complete, evaluation of the containing expression continues with its original focus unchanged. [Ed. Note: See issue 216.]

  • The context item is the item currently being processed. An item is either a simple value or a node. When the context item is a node, it can also be referred to as the context node. The context item is returned by the expression ".". When the expressions E1/E2 or E1[E2] are evaluated, each item in the sequence obtained by evaluating E1 becomes the context item in the inner focus for an evaluation of E2.

  • The context position is the position of the context item within the sequence of items currently being processed. It changes whenever the context item changes. Its value is always an integer greater than zero. The context position is returned by the expression position(). When the expressions E1/E2 or E1[E2] are evaluated, the context position in the inner focus for an evaluation of E2 is the position of the context item in the sequence obtained by evaluating E1. The position of the first item in a sequence is always 1 (one). The context position is always less than or equal to the context size.

  • The context size is the number of items in the sequence of items currently being processed. Its value is always an integer greater than zero. The context size is returned by the expression last(). When the expressions E1/E2 or E1[E2] are evaluated, the context position in the inner focus for an evaluation of E2 is the number of items in the sequence obtained by evaluating E1.

  • The context document is the document currently being processed. Its value is a node, which is always a document node. If there is a context node, and if the tree containing the context node has a document node as its root, then this document node will be the context document. When an inner focus is created and the context item in the inner focus is not a node, or is a node belonging to a tree whose root is not a document node, then the context document in this inner focus will be the same as the context document in the outer focus. The context document is returned by the XPath expression "/", and is used implicitly as the base for any absolute path expression, as well being used as input to certain functions such as xf:id. [Ed. Note: See Issue 217.]

  • Dynamic variables. This is a set of (QName, type, value) triples. It contains the same QNames as the in-scope variables in the static context for the expression. Each QName is associated with the dynamic type and value of the corresponding variable. The dynamic type associated with a variable may be more specific than the static type associated with the same variable. The value of a variable is, in general, a sequence.

    The dynamic types and values of variables are provided by execution of the XQuery expressions in which the variables are bound.

  • Current date and time. This information represents a point in time during processing of a query. It can be retrieved by the xf:currentDateTime function. If invoked multiple times during the execution of a query, this function always returns the same result.

2.1.2 Type Conversions

Certain operators, functions, and syntactic constructs expect a value of a particular type to be supplied: this is referred to as a required type. A required type may be specified in the following ways:

  • In the signature of a function definition

  • In the description of an operator

  • In the description of a syntactic construct, such as the test in a conditional expression

The required type may be specified as a simple type, an optional occurrence of a simple type, a sequence of a simple type, or a sequence of nodes. If no required type is specified, the value may be any sequence. If the value supplied does not conform to the required type, it is converted to the required type by applying the basic conversion rules.

In some cases, the basic conversion rules may invoke a type exception. A type exception may be invoked either statically (during query analysis) or dynamically (during query execution). XQuery treats a type exception as an unrecoverable error.

The basic conversion rules are as follows:

  1. If the required type is a simple type or an optional occurrence of a simple type:

    1. If the given value is a sequence of more than one item, a type exception is invoked. If the given value is a single node, its typed value is extracted by calling its typed value accessor. If the node has no typed value accessor or if its typed value is a sequence containing more than one item, a type exception is invoked.

    2. If the (given or extracted) value has an unknown simple type (as in the case of character data in a schemaless document), an attempt is made to cast it to the required simple type. If the cast fails, a type exception is invoked.

    3. If the (given or extracted) value does not conform to the required type, a type exception is raised. This includes the case in which the (given or extracted) value is an empty sequence and the required type is not an optional occurrence.

  2. If the required type is a sequence of a simple type:

    If the given value is a sequence containing one or more nodes, each such node is replaced by its typed value, resulting in a sequence of simple values. Each of these simple values then is converted to the required type by applying the rules described above for converting values to a required simple type.

  3. If the required type is a sequence of nodes:

    If the given value contains any item that is not a node, a type exception is invoked.

Ed. Note: In order to handle user-defined function signatures, the notion of "required type" must be extended to include the full datatype syntax in 2.13 Datatypes. The basic conversion rules must be extended to deal with complex types. For example, can an element of a given type be used where an element of a supertype is expected? Can an element be used where another element in the same substitution group is expected?

2.2 Primary Expressions

Primary expressions are the basic primitives of the language.

[47]   PrimaryExpr   ::=   Variable
|  Literal
|  ElementNameOrFunctionCall
|  Wildcard
|  KindTest
|  ParenthesizedExpr

Ed. Note: Wildcard and KindTest are used in path expressions and are described in 2.3.1.2 Node Tests. In the current version of the grammar, they are included as forms of PrimaryExpr for technical reasons. This part of the PrimaryExpr grammar is subject to change. We also expect to separate ElementNameOrFunctionCall into two productions: ElementName, which is a form of abbreviated path expression, and FunctionCall, which is a form of primary expression.

2.2.1 Literals

A literal is a direct syntactic representation of a simple value. XQuery supports two kinds of literals: string literals and numeric literals.

[49]   Literal   ::=   NumericLiteral |  StringLiteral
[48]   NumericLiteral   ::=   IntegerLiteral |  DecimalLiteral |  DoubleLiteral
[167]   IntegerLiteral   ::=   [0-9]+
[168]   DecimalLiteral   ::=   ("." [0-9]+) |  ([0-9]+ "." [0-9]*)
[169]   DoubleLiteral   ::=   (("." [0-9]+) |  ([0-9]+ ("." [0-9]*)?)) ([e] | [E]) ([+] | [-])? [0-9]+
[180]   StringLiteral   ::=   (["] [^"]* ["]) |  (['] [^']* ['])

The value of a string literal is a singleton sequence containing an item whose primitive type is xs:string and whose value is the string denoted by the characters between the delimiting quotation marks.

The value of a numeric literal containing no "." and no e or E character is a singleton sequence containing an item whose type is xs:integer and whose value is obtained by parsing the numeric literal according to the rules of the xs:integer datatype. The value of a numeric literal containing "." but no e or E character is a singleton sequence containing an item whose primitive type is xs:decimal and whose value is obtained by parsing the numeric literal according to the rules of the xs:decimal datatype. The value of a numeric literal containing an e or E character is a singleton sequence containing an item whose primitive type is xs:double and whose value is obtained by parsing the numeric literal according to the rules of the xs:double datatype.

Here are some examples of literal expressions:

  • "12.5" denotes the string containing the characters '1', '2', '.', and '5'.

  • 12 denotes the integer value twelve.

  • 12.5 denotes the decimal value twelve and one half.

  • 125E2 denotes the double value twelve thousand, five hundred.

Values of other XML Schema built-in types can be constructed by calling the constructor for the given type. The constructors for XML Schema built-in types are defined in [XQuery 1.0 and XPath 2.0 Functions and Operators]. For example:

  • xf:true() and xf:false() return the boolean values true and false, respectively.

  • xf:integer("12") returns the integer value twelve.

  • xf:date("2001-08-25") returns an item whose simple type is xs:date and whose value represents the date 25th August 2001.

It is also possible to construct values of other built-in types using the cast expression. For example:

  • cast as xs:positiveInteger(12) returns a simple value whose primitive value is the decimal value 12.0 and whose type is the built-in derived type xs:positiveInteger.

2.2.2 Variables

A variable evaluates to the value to which the variable's QName is bound in the evaluation context. It is an error if the variable's QName is not defined in the evaluation context. Variables can be bound by clauses in For expressions and Quantified expressions, and by function calls which bind values to the formal parameters of functions.

[158]   Variable   ::=   "$" QName

Ed. Note: In XQuery this production may end up being constrained to an NCName. See issue 207.

The binding of a variable in an expression always overrides any in-scope binding of a variable with the same name. For example, for $v in (1,2) return for $v in (3,4) return $v evaluates to (3, 4, 3, 4) because the definition of $v in the inner for expression overrides the definition of $v in the outer for expression.

2.2.3 Parenthesized Expressions

Parentheses may be used to enforce a particular evaluation order in expressions that contain multiple operators, as shown in the following example:

  • The expression (2 + 4) * 5 evaluates to thirty; 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.

Parentheses are also used as delimiters in constructing a sequence, as described in 2.4.1 Constructing Sequences.

2.2.4 Function Calls

A function call consists of a QName followed by a parenthesized list of zero or more expressions. The QName must match the name of an in-scope function in the static context (see 2.1.1 Expression Context). The expressions inside the parentheses provide the arguments of the function call. The number of arguments must equal the number of formal arguments in the function's signature; otherwise an error is raised.

A QName not followed by parentheses is interpreted as an element name, which is a form of abbreviated path expression described in 2.3.5 Abbreviated Syntax.

[51]   ElementNameOrFunctionCall   ::=   QName ("(" (Expr ("," Expr)*)? ")")?

A function call expression is evaluated as follows:

  1. Each argument expression is evaluated, producing an argument value.

  2. The basic conversion rules are applied for each argument value and its corresponding required type from the function's signature. These rules produce a value of the required type for each function parameter or raise a type exception.

  3. If all argument values can be converted to their corresponding required types, the function is applied to the converted values, and the result of the function call is the result of the function application.

A very common type conversion rule is the extraction of a simple value from a node. For example, assume that the context node contains an attribute named color that contains a string. The required type of the only argument to xf:upper-case is string. In the function application:

xf:upper-case(@color)

the typed value of the attribute node color is extracted before the function is applied.

A large library of functions is defined in [XQuery 1.0 and XPath 2.0 Functions and Operators]. Although functions in that document have the namespace prefix xf, this prefix is not required if the expression context defines a default namespace for the core library.

The comma operator serves two purposes: it separates actual arguments in a function call, and it separates items in an expression that constructs a sequence (see 2.4.1 Constructing Sequences). To distinguish these two uses, parentheses are used to delimit items in a sequence constructor.

Here are some examples of function calls in which arguments that are literal sequences are delimited with parentheses:

  • three-argument-function(1, 2, 3) denotes a function call with three arguments.

  • two-argument-function((1, 2), 3) denotes a function call with two arguments, the first of which is a sequence of two values.

  • two-argument-function(1, ()) denotes a function call with two arguments, the second of which is an empty sequence.

  • one-argument-function((1, 2, 3)) denotes a function call with one argument that is a sequence of three values.

2.2.5 Comments

Comments can be used to annotate a query with informative information. Comments are lexical constructs only, and have no meaning within the query.

[77]   ExprComment   ::=   "{--" [^}]* "--}"

Comments may be used before and after major tokens within expressions and within element content. See A.3 Lexical structure for the exact lexical states where comments are recognized.

Ed. Note: The EBNF here should disallow "--}" within the comment, rather than "}". Also, within an enclosed expression, a comment immediately after the opening "{" will cause the "{{" to be mistaken for an escaped "{". Thus, <a>{{--comment--}foo}</a> will currently cause an error, and must be disambiguated with a space between the "{" characters. This should be considered an open issue.

2.3 Path Expressions

A path expression locates nodes within a tree, and returns a sequence of distinct nodes in document order. A path expression is always evaluated with respect to an evaluation context. There are two kinds of path expressions: relative and absolute.

[25]   PathExpr   ::=   AbsolutePathExpr |  RelativePathExpr
[31]   AbsolutePathExpr   ::=   ("/" RelativePathExpr?) |  ("//" RelativePathExpr)
[32]   RelativePathExpr   ::=   StepExpr (("/" |  "//") StepExpr)*
[33]   StepExpr   ::=   AxisStep |  GeneralStep

A relative path expression consists of one or more steps separated by / or //. The steps in a relative path expression are composed together from left to right. Each step in turn selects a sequence of nodes. An initial sequence of steps is composed together with a following step as follows: each node selected by the initial sequence is used to provide a focus for the following step, as described in 2.1.1.2 Evaluation Context. The following step is executed for each such focus, and the resulting sequences of nodes are merged, eliminating duplicate node identities and preserving document order. For example, 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 that have div1 parents.

An absolute path expression consists of / or // followed by a relative path expression (if the path begins with /, the relative path expression is optional.) A / by itself selects the root node of the document containing the context node. If it is followed by a relative path expression, then the path expression selects the sequence of nodes that would be selected by the relative path expression relative to the root node of the context document.

The uses of // in path expressions are examples of abbreviated syntax, explained in 2.3.5 Abbreviated Syntax.

The steps in a path expression are of two general kinds, called axis steps and general steps.

2.3.1 Axis Steps

[34]   AxisStep   ::=   (Axis NodeTest StepQualifiers) |  AbbreviatedStep
[35]   Axis   ::=   "child" "::"
|  "descendant" "::"
|  "parent" "::"
|  "attribute" "::"
|  "self" "::"
|  "descendant-or-self" "::"

An axis step begins at the context node, navigates to those nodes that are reachable from the context node via a predefined axis, and selects some subset of the reachable nodes. An axis step has three parts:

  • an axis, which specifies the relationship between the nodes selected by the axis step and the context node. The axis might be thought of as the "direction of movement" of the axis step.

  • a node test, which specifies the node type and expanded-name of the nodes selected by the axis step.

  • zero or more step qualifiers, which further modify the sequence of nodes selected by the axis step.

In the abbreviated syntax for an axis step, the axis can be omitted and other shorthand notations can be used as described in 2.3.5 Abbreviated Syntax.

The unabbreviated syntax for an axis step consists of the axis name and node test separated by a double colon, followed by zero or more step qualifiers. For example, in child::para[position()=1], child is the name of the axis, para is the node test and [position()=1] is a step qualifier.

The node sequence selected by an axis step is found by generating an initial node sequence from the axis and node test, and then applying each of the step qualifiers in turn. The initial node sequence consists of the nodes reachable from the context node via the specified axis that have the node type and expanded-name specified by the node test. For example, a location step descendant::para selects the para element descendants of the context node: descendant specifies that each node in the initial node sequence must be a descendant of the context, and para specifies that each node in the initial node sequence must be an element named para. The available axes are described in 2.3.1.1 Axes. The available node tests are described in 2.3.1.2 Node Tests. Step qualifiers are described in 2.3.3 Step Qualifiers. Examples of axis steps are provided in 2.3.4 Unabbreviated Syntax

2.3.1.1 Axes

XQuery supports the following axes:

  • the child axis contains the children of the context node

  • the descendant axis contains the descendants of the context node; a descendant is a child or a child of a child and so on; thus the descendant axis never contains attribute or namespace nodes

  • the parent axis contains the parent of the context node, if there is one

  • the attribute axis contains the attributes of the context node; the axis will be empty unless the context node is an element

  • the self axis contains just the context node itself

  • the descendant-or-self axis contains the context node and the descendants of the context node

Axes can be categorized as forward axes and reverse axes. An axis that only ever contains the context node or nodes that are after the context node in document order is a forward axis. An axis that only ever contains the context node or nodes that are before the context node in document order is a reverse axis.

In XQuery, the parent axis is a reverse axis; all other axes are forward axes. Since the self axis always contains at most one node, it makes no difference whether it is a forward or reverse axis.

2.3.1.2 Node Tests

A node test is a condition that must be true for each node selected by an axis step. The condition may be based on the type of the node and/or its name.

[36]   NodeTest   ::=   NameTest |  KindTest
[37]   NameTest   ::=   QName |  Wildcard
[38]   Wildcard   ::=   "*" |  ":"? NCName ":" "*" |  "*" ":" NCName
[39]   KindTest   ::=   ProcessingInstructionTest
|  CommentTest
|  TextTest
|  AnyKindTest
[40]   ProcessingInstructionTest   ::=   "processing-instruction" "(" StringLiteral? ")"
[41]   CommentTest   ::=   "comment" "(" ")"
[42]   TextTest   ::=   "text" "(" ")"
[43]   AnyKindTest   ::=   "node" "(" ")"

[Definition: Every axis has a principal node type. If an axis can contain elements, then the principal node type is element; otherwise, it is the type of the nodes that the axis can contain.] Thus:

  • For the attribute axis, the principal node type is attribute.

  • For the namespace axis, the principal node type is namespace.

  • For all other axes, the principal node type is element.

A node test that is a QName is true if and only if the type of the node (see [XQuery 1.0 and XPath 2.0 Data Model]) is the principal node type and the expanded-name of the node is equal to the expanded-name specified by the QName. For example, child::para selects the para element children of the context node; if the context node has no para children, it will select an empty set of nodes. attribute::href selects the href attribute of the context node; if the context node has no href attribute, it will select an empty set of nodes.

A QName in a node test is expanded into an expanded-name using the in-scope namespaces in the expression context. An unprefixed QName used as a nametest has the namespaceURI associated with the default element namespace in the expression context. It is an error if the QName has a prefix that does not correspond to any in-scope namespace.

A node test * is true for any node of the principal node type. For example, child::* will select all element children of the context node, and attribute::* will select all attributes of the context node.

A node test can have the form NCName:*. In this case, the prefix is expanded in the same way as with a QName, using the context namespace declarations. It is an error if there is no namespace declaration for the prefix in the expression context. The node test will be true for any node of the principal type whose expanded-name has the namespace URI to which the prefix expands, regardless of the local part of the name.

A node test can also have the form *:NCName. In this case, the node test is true for any node of the principal node type whose local name matches the given NCName, regardless of its namespace.

The node test text() is true for any text node. For example, child::text() will select the text node children of the context node. Similarly, the node test comment() is true for any comment node, and the node test processing-instruction() is true for any processing instruction. The processing-instruction() test may have an argument that is a StringLiteral; in this case, it is true for any processing instruction that has a name equal to the value of the StringLiteral.

A node test node() is true for any node of any type whatsoever.

2.3.2 General Steps

In addition to the axis step format described above, a step in a path expression may take another form, called a general step.

[44]   GeneralStep   ::=   PrimaryExpr StepQualifiers

A general step is simply a primary expression, possibly followed by one or more step qualifiers. Since a primary expression may in turn contain any expression in parentheses, a general step may contain any expression.

The expression in the general step must evaluate to a sequence of nodes. The result of the general step is this sequence of nodes, modified by any step qualifiers and sorted if necessary into document order. If the expression in the general step returns any values that are not nodes, an error is raised.

As in the case of an axis step, a general step is executed once if it is the first step in the path expression. If it is not the first step, the general step is executed once for each node selected by the preceding step, using the focus provided by each of these nodes in turn, as described in 2.1.1.2 Evaluation Context. The nodes selected by the general step are then used in turn to provide foci for execution of the following step, if any.

Here are some examples of path expressions that contain general steps:

  • The path expression in this example begins with a general step that contains a function call. The document function returns the root node of a document.

    document("book3.xml")/descendant::author

  • This is a three-step path expression in which the second step is a general step that uses the | operator (see 2.4.2 Combining Sequences.)

    child::school/(child::faculty | child::staff)/child::address

2.3.3 Step Qualifiers

Step qualifiers are of two general forms: predicates, which are used to filter a node sequence by applying some test, and dereferences, which are used to map reference-type attribute nodes into the nodes that they reference.

[46]   StepQualifiers   ::=   (("[" Expr "]") |  ("=>" NameTest))*
2.3.3.1 Predicates

A predicate consists of an expression, called a predicate expression, enclosed in square brackets. A predicate serves to filter a node sequence, retaining some nodes and discarding others. For each node in the node sequence to be filtered, the predicate expression is evaluated using a focus derived from that node, as described in 2.1.1.2 Evaluation Context. The result of the predicate expression is coerced to a Boolean value, called the predicate truth value, as described below. Those nodes for which the predicate truth value is true are retained, and those for which the predicate truth value is false are discarded.

The predicate truth value is derived by applying the following rules, in order:

  1. If the value of the predicate expression is an empty sequence, the predicate truth value is false.

  2. If the value of the predicate expression is one simple value of a numeric type, the value is rounded to an integer using the rules of the round function, and the predicate truth value is true if and only if the resulting integer is equal to the value of the context position.

  3. If the value of the predicate expression is one simple value of type Boolean, the predicate truth value is equal to the value of the predicate expression.

  4. If the value of the predicate expression is a sequence containing at least one node, the predicate truth value is true. Note that the predicate truth value in this case does not depend on the content of the node.

  5. In any other case, an error is raised.

In a sequence of nodes selected by an axis step, the context positions of the nodes are determined in a way that depends on the axis. If the axis is a forward axis, context positions are assigned to the nodes in document order. If the axis is a reverse axis, context positions are assigned to the nodes in reverse document order. In either case, the first context position is 1.

Here are some examples of steps that contain predicates:

  • This example selects the second "chapter" element that is a child of the context node:

    child::chapter[2]
  • This example selects all the descendants of the context node whose name is "toy" and whose "color" attribute has the value "red":

    descendant::toy[attribute::color = "red"]
  • This example selects all the "employee" children of the context node that have a "secretary" subelement:

    child::employee[secretary]
2.3.3.2 Dereferences

A dereference operates on a node sequence, mapping element and/or attribute nodes into the nodes that they reference. Every node in the sequence that is input to the dereference must be an element or attribute node whose content is of type IDREF or IDREFS; otherwise an error is raised. The dereference generates a new sequence consisting of the element nodes whose ID-type attribute values match the IDREF values extracted from the elements and attributes in the input sequence. The resulting sequence is filtered by the NameTest that follows the dereference operator, retaining only nodes whose expanded-names match the expanded-name specified in the NameTest. The filtered sequence of element nodes is then sorted into document order.

Here are some examples of steps that contain dereferences:

  • This example selects the figure that is referenced by the first figure reference that is a child of the context node:

    child::figref[1]/attribute::refid=>figure
  • This example selects the manager of the manager of the context node, assuming that the context node is an emp node and that each emp node has a manager attribute that references the emp node of the employee's manager:

    attribute::manager=>emp/attribute::manager=>emp

2.3.4 Unabbreviated Syntax

This section provides a number of examples of path expressions in which the axis is explicitly specified in each step. The syntax used in these examples is called the unabbreviated syntax. In many common cases, it is possible to write path expressions more concisely using an abbreviated syntax, as explained in 2.3.5 Abbreviated Syntax.

  • child::para selects the para element children of the context node

  • child::* selects all element children of the context node

  • child::text() selects all text node children of the context node

  • child::node() selects all the children of the context node, whatever their node type

  • attribute::name selects the name attribute of the context node

  • attribute::* selects all the attributes of the context node

  • descendant::para selects the para element descendants of the context node

  • descendant-or-self::para selects the para element descendants of the context node and, if the context node is a para element, the context node as well

  • self::para selects the context node if it is a para element, and otherwise selects nothing

  • child::chapter/descendant::para selects the para element descendants of the chapter element children of the context node

  • child::*/child::para selects all para grandchildren of the context node

  • / selects the document root (which is always the parent of the document element)

  • /descendant::para selects all the para elements in the same document as the context node

  • /descendant::olist/child:::item selects all the item elements that have an olist parent and that are in the same document as the context node

  • child::para[position()=1] selects the first para child of the context node

  • child::para[position()=last()] selects the last para child of the context node

  • child::para[position()=last()-1] selects the last but one para child of the context node

  • child::para[position()>1] selects all the para children of the context node other than the first para child of the context node

  • /descendant::figure[position()=42] selects the forty-second figure element in the document

  • /child::doc/child::chapter[position()=5]/child::section[position()=2] selects the second section of the fifth chapter of the doc document element

  • child::para[attribute::type="warning"] selects all para children of the context node that have a type attribute with value warning

  • child::para[attribute::type='warning'][position()=5] selects the fifth para child of the context node that has a type attribute with value warning

  • child::para[position()=5][attribute::type="warning"] selects the fifth para child of the context node if that child has a type attribute with value warning

  • child::chapter[child::title='Introduction'] selects the chapter children of the context node that have one or more title children with string-value equal to Introduction

  • child::chapter[child::title] selects the chapter children of the context node that have one or more title children

  • child::*[self::chapter or self::appendix] selects the chapter and appendix children of the context node

  • child::*[self::chapter or self::appendix][position()=last()] selects the last chapter or appendix child of the context node

2.3.5 Abbreviated Syntax

[45]   AbbreviatedStep   ::=   "." |  ".." |  ("@" NameTest StepQualifiers)

The abbreviated syntax permits the following abbreviations:

  1. The most important abbreviation is that child:: can be omitted from a step. In effect, child is the default axis. For example, a path expression section/para is short for child::section/child::para.

  2. There is also an abbreviation for attributes: attribute:: can be abbreviated to @. 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.

  3. // is short for /descendant-or-self::node()/. For example, //para is short for /descendant-or-self::node()/child::para and so will select any para element in the document (even a para element that is a document element will be selected by //para since the document element node is a child of the root node); div1//para is short for div1/descendant-or-self::node()/child::para and so will select all para descendants of div1 children.

    Note that the path expression //para[1] does not mean the same as the path expression /descendant::para[1]. The latter selects the first descendant para element; the former selects all descendant para elements that are the first para children of their parents.

  4. A step consisting of . is short for self::node(). This is particularly useful in conjunction with //. For example, the path expression .//para is short for

    self::node()/descendant-or-self::node()/child::para

    and so will select all para descendant elements of the context node.

  5. A step consisting of .. is short for parent::node(). For example, ../title is short for parent::node()/child::title and so will select the title children of the parent of the context node.

Here are some examples of path expressions that use the abbreviated syntax:

  • para selects the para element children of the context node

  • * selects all element children of the context node

  • text() selects all text node children of the context node

  • @name selects the name attribute of the context node

  • @* selects all the attributes of the context node

  • para[1] selects the first para child of the context node

  • para[last()] selects the last para child of the context node

  • */para selects all para grandchildren of the context node

  • /doc/chapter[5]/section[2] selects the second section of the fifth chapter of the doc

  • chapter//para selects the para element descendants of the chapter element children of the context node

  • //para selects all the para descendants of the document root and thus selects all para elements in the same document as the context node

  • //olist/:item selects all the item elements in the same document as the context node that have an olist parent

  • . selects the context node

  • .//para selects the para element descendants of the context node

  • .. selects the parent of the context node

  • ../@lang selects the lang attribute of the parent of the context node

  • para[@type="warning"] selects all para children of the context node that have a type attribute with value warning

  • para[@type="warning"][5] selects the fifth para child of the context node that has a 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 with string-value equal to Introduction

  • chapter[title] selects the chapter children of the context node that have one or more title children

  • employee[@secretary and @assistant] selects all the employee children of the context node that have both a secretary attribute and an assistant attribute

  • book/(chapter|appendix)/section selects every section element that has a parent that is either a chapter or an appendix element, that in turn is a child of a section element that is a child of the context node.

  • book/xf:ID(publisher)/name returns the same result as xf:ID(book/publisher)/name.

2.4 Sequence Expressions

XQuery supports operators to construct and combine sequences. A sequence is an ordered collection of zero or more items. An item may be a simple value or a node.

2.4.1 Constructing Sequences

[50]   ParenthesizedExpr   ::=   "(" ExprSequence? ")"
[3]   ExprSequence   ::=   Expr ("," Expr)*
[17]   RangeExpr   ::=   Expr  "to"  Expr

One way to construct a sequence is with a ParenthesizedExpr, which is zero or more expressions separated by the comma (",") operator and delimited by parentheses. A parenthesized expression is evaluated by evaluating each of its constituent expressions and concatenating the resulting sequences, in order, into a single result sequence. A sequence may contain duplicate 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.

Here are some examples of expressions that construct sequences:

  • This expression is a sequence of five integers:

    (10, 1, 2, 3, 4)
  • This expression constructs one sequence from the sequences 10, (1, 2), the empty sequence (), and (3, 4):

    (10, (1, 2), (), (3, 4))

    It evaluates to the sequence:

    (10, 1, 2, 3, 4)

  • This expression contains all salary children of the context node followed by all bonus children:

    (salary, bonus)
  • Assuming that $price is bound to the value 10.50, this expression:

    ($price, $price)

    evaluates to the sequence

    (10.50, 10.50)

A RangeExpr can be used to construct a sequence of consecutive integers. The to operator takes two operands, both of which have a required type of integer. A sequence is constructed containing the two integer operands and every integer between the two operands. If the first operand is less than the second, the sequence is in increasing order, otherwise it is in decreasing order.

  • This example uses a range expression inside a sequence expression:

    (10, 1 to 4)

    It evaluates to the sequence:

    (10, 1, 2, 3, 4)

2.4.2 Combining Sequences

[20]   UnionExpr   ::=   Expr  ("union" |  "|")  Expr
[21]   IntersectExceptExpr   ::=   Expr  ("intersect" |  "except")  Expr

XQuery provides several operators for combining sequences. The union and | operators are equivalent. They take two sequences as operands and return a sequence containing all the items that occur in either of the operands. The intersect operator takes two sequences as operands and returns a sequence containing all the items that occur in both operands. The except operator takes two sequences as operands and returns a sequence containing all the items that occur in the first operand but not in the second operand. All of these operators eliminate duplicates from their result sequences. Two nodes are considered to be duplicates if they have the same node identity. Two simple values are considered to be duplicates if they return true when used as operands of the eq operator. In the result sequences returned by these operators, nodes appear in document order, but the order of simple values is implementation-defined.

Here are some examples of expressions that combine sequences. Assume in the following examples that there are three elements, <a/>, <b/>, and <c/>, and three sequences that contain these elements: $seq1 = (<a/>, <b/>), $seq2 = (<a/>, <b/>), and $seq3 = (<b/>, <c/>). Then:

  • $seq1 union $seq1 evaluates to (<a/>, <b/>).

  • $seq2 union $seq3 evaluates to (<a/>, <b/>, <c/>).

  • $seq1 intersect $seq1 evaluates to (<a/>, <b/>).

  • $seq2 intersect $seq3 evaluates to <b/>.

  • $seq1 except $seq2 evaluates to (), the empty sequence.

  • $seq2 except $seq3 evaluates to <a/>.

The following examples illustrate how sequence-combining operators might be used with sequences of simple values.

  • (1, 2, 2, 3) union (2, 3, 4) evaluates to (1, 2, 3, 4)

  • (1, 2, 2, 3) intersect (2, 3, 4) evaluates to (2, 3)

  • (1, 2, 2, 3) except (2, 3, 4) evaluates to (1)

In addition to the sequence operators described here, [XQuery 1.0 and XPath 2.0 Functions and Operators] includes functions for indexed access to items or sub-sequences of a sequence, for indexed insertion or removal of items in a sequence, and for removing duplicate values or nodes from a sequence.

2.5 Arithmetic Expressions

XQuery provides arithmetic operators for addition, subtraction, multiplication, division, and modulus, in their usual binary and unary forms.

[18]   AdditiveExpr   ::=   Expr  ("+" |  "-")  Expr
[19]   MultiplicativeExpr   ::=   Expr  ( "*" |  "div" |  "mod")  Expr
[22]   UnaryExpr   ::=   ("-" |  "+")  Expr

The binary subtraction operator must be preceded by white space if it follows an NCName, in order to distinguish it from a hyphen, which is a valid name character. For example, a-b will be interpreted as a single token.

The operands of an arithmetic expression do not have required types. An arithmetic expression is evaluated by applying the following rules, in order, until an error is raised or a value is computed:

  1. If any operand is a sequence of length greater than one, a type exception is raised.

  2. If any operand is an empty sequence, the result is an empty sequence.

  3. If any operand is a node, its typed-value accessor is applied. If the node has no typed-value accessor, or if the typed-value accessor returns a sequence of more than one value, an error is raised. If the typed-value accessor returns the empty sequence, the result of the expression is the empty sequence.

  4. If any operand is an untyped simple value (such as character data in a schemaless document), it is cast to the type suggested by its lexical form. For example, the untyped value 12 is cast to the type xs:integer.

  5. If the arithmetic expression has two numeric operands of different types, one of the operands is promoted to the type of the other operand, following the promotion rules in [XQuery 1.0 and XPath 2.0 Functions and Operators]. For example, a value of type xs:integer can be promoted to xs:decimal, and a value of type xs:decimal can be promoted to xs:double.

  6. If the operand type(s) are valid for the given operator, the operator is applied to the operand(s), resulting in either a simple value or an error (for example, an error might result from dividing by zero.) The combinations of simple types that are accepted by the various arithmetic operators, and their respective result types, are listed in [XQuery 1.0 and XPath 2.0 Functions and Operators]. If the operand type(s) are not valid for the given operator, a type exception is raised.

Ed. Note: A future version of this document will provide a mapping from the arithmetic operators to the functions that implement these operators for various datatypes. See issue 182.

Here are some examples of arithmetic expressions:

  • In general, arithmetic operations on numeric values result in numeric values:

    ($salary + $bonus) div 12
  • Subtraction of two dateTime values results in a duration:

    $emp/hiredate - $emp/birthdate
  • Subtracting a duration from a dateTime results in a dateTime:

    $paper/deadline - $paper/worktime
  • This example illustrates the difference between a subtraction operator and a hyphen:

    $unit-price - $unit-discount
  • Unary operators have higher precedence than binary operators, subject of course to the use of parentheses:

    -($bellcost + $whistlecost)

2.6 Comparison Expressions

Comparison expressions allow two values to be compared. XQuery provides four kinds of comparison expressions, called value comparisons, general comparisons, node comparisons, and order comparisons.

[13]   ValueComp   ::=   Expr  ("eq" |  "ne" |  "lt" |  "le" |  "gt" |  "ge")  Expr
[12]   GeneralComp   ::=   Expr  ("=" |  "!=" |  "<" S |  "<=" |  ">" |  ">=")  Expr
[14]   NodeComp   ::=   Expr  ("==" |  "!==")  Expr
[15]   OrderComp   ::=   Expr  ("<<" |  ">>" |  "precedes" |  "follows")  Expr

The "<" comparison operator must be followed by white space in order to distinguish it from a tag-open character. [Ed. Note: This rule may be relaxed. This issue is pending some general grammar issues.]

2.6.1 Value Comparisons

Value comparisons are intended for comparing single values. The result of a value comparison is defined by applying the following rules, in order:

  1. If either operand is an empty sequence, the result is an empty sequence.

  2. If either operand is a sequence containing more than one item, an error is raised.

  3. If either operand is a node, its typed value is extracted. If the typed value is an empty sequence, the result of the comparison is an empty sequence. If the typed value is a sequence containing more than one item, an error is raised.

  4. If one of the operands is an untyped simple value (such as character data in a schemaless document) and the other operand is a typed simple value, the untyped operand is cast into the type of the other operand. If both of the operands are untyped values, they are both cast to the type xs:string.

  5. 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. [XQuery 1.0 and XPath 2.0 Functions and Operators] describes which combinations of simple types are comparable, and how comparisons are performed on values of various types. If the value of the first operand is not comparable with the value of the second operand, a type exception is invoked.

Ed. Note: A future version of this document will provide a mapping from the comparison operators to the functions that implement these operators for various datatypes. See issue 182.

Here is an example of a value comparison:

  • The following comparison is true only if $book1 has a single author subelement and its value is "Kennedy":

    $book1/author eq "Kennedy"

2.6.2 General Comparisons

General comparisons are defined by adding existential semantics to value comparisons. The operands of a general comparison may be sequences of any length. The result of a general comparison is always true or false.

The general comparison A = B is true for sequences A and B if the value comparison a eq b is true for some item a in A and some item b in B. Otherwise, A = B is false.

Similarly:

  • A != B is true if and only if a ne b is true for some a in A and some b in B.

  • A < B is true if and only if a lt b is true for some a in A and some b in B.

  • A <= B is true if and only if a le b is true for some a in A and some b in B.

  • A > B is true if and only if a gt b is true for some a in A and some b in B.

  • A >= B is true if and only if a ge b is true for some a in A and some b in B.

Here is an example of a general comparison:

  • The following comparison is true if the value of any author subelement of $book1 is "Kennedy":

    $book1/author = "Kennedy"

2.6.3 Node Comparisons

The result of a node comparison is defined by applying the following rules, in order:

  1. Both operands must be either a single node or an empty sequence; otherwise an error is raised.

  2. If either operand is an empty sequence, the result of the comparison is an empty sequence.

  3. A comparison with the == operator is true if the two operands are nodes that have the same identity; otherwise it is false. A comparison with the !== operator is true if the two operands are nodes that have different identities; otherwise it is false. See [XQuery 1.0 and XPath 2.0 Data Model] for a discussion of node identity.

Here is an example of a node comparison:

  • The following comparison is true only if the left and right sides each evaluate to exactly the same single node:

    //book[isbn="1558604820"] == //book[call="QA76.9 C3845"]

2.6.4 Order Comparisons

The result of an order comparison is defined by applying the following rules, in order:

  1. Both operands must be either a single node or an empty sequence; otherwise an error is raised.

  2. If either operand is an empty sequence, the result of the comparison is an empty sequence.

  3. A comparison with the << operator returns true if the first operand node is earlier than the second operand node in document order, or false if the first operand node is later than the second operand node in document order.

  4. A comparison with the >> operator returns true if the first operand node is later than the second operand node in document order, or false if the first operand node is earlier than the second operand node in document order.

  5. A comparison with the precedes operator returns true if the first operand node is reachable from the second operand node using the preceding axis; otherwise it returns false.

  6. A comparison with the follows operator returns true if the first operand node is reachable from the second operand node using the following axis; otherwise it returns false.

Here is an example of an order comparison:

  • 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:

    //purchase[parcel="28-451"] << //sale[parcel="33-870"]

2.7 Logical Expressions

A logical expression is either an and-expression or an or-expression. The value of a logical expression is always one of the boolean values true or false.

[6]   OrExpr   ::=   Expr  "or"  Expr
[7]   AndExpr   ::=   Expr  "and"  Expr

The first step in evaluating a logical expression is to reduce each of its operands to an effective boolean value by applying the following rules, in order:

  1. If the operand is an empty sequence, its effective boolean value is false.

  2. If the operand is one simple boolean value, the operand serves as its own effective boolean value.

  3. If the operand is a sequence that contains at least one node, its effective boolean value is true.

  4. In any other case, a type exception is invoked.

An and-expression returns the value true if the effective boolean values of both of its operands are true; otherwise it returns the value false.

An or-expression returns the value false if the effective boolean values of both of its operands are false; otherwise it returns the value true.

In addition to and- and or-expressions, XQuery provides a function named not that takes a general sequence as parameter and returns a boolean value. The not function reduces its parameter to an effective boolean value using the same rules that are used for the operands of logical expressions. It then returns true if the effective boolean value of its parameter is false, and false if the effective boolean value of its parameter is true. The not function is described in [XQuery 1.0 and XPath 2.0 Functions and Operators].

Ed. Note: Functions named and3, or3, and not3 may be provided to implement three-valued logic. See Issue 28.

2.8 Constructors

XQuery provides constructors that can create XML structures within a query. There are constructors for elements, attributes, CDATA sections, processing instructions, and comments. A special form of constructor called a computed element or attribute constructor can be used to create an element or attribute with a computed name.

[24]   Constructor   ::=   ElementConstructor |  ComputedElementConstructor |  ComputedAttributeConstructor
[57]   ElementConstructor   ::=   "<" QName AttributeList ("/>" |  (">" ElementContent* "</" QName ">"))
[63]   ElementContent   ::=   Char
|  "{{"
|  "}}"
|  ElementConstructor
|  EnclosedExpr
|  CdataSection
|  CharRef
|  PredefinedEntityRef
|  XmlComment
|  XmlProcessingInstruction
|  ComputedElementConstructor
|  ComputedAttributeConstructor
[64]   AttributeList   ::=   (QName "=" (AttributeValue |  EnclosedExpr))*
[65]   AttributeValue   ::=   (["] AttributeValueContent* ["])
|  (['] AttributeValueContent* ['])
[66]   AttributeValueContent   ::=   Char
|  CharRef
|  "{{"
|  "}}"
|  EnclosedExpr
|  PredefinedEntityRef
[67]   EnclosedExpr   ::=   "{" ExprSequence "}"

2.8.1 Element Constructors

An element constructor creates an XML element. If the name, attributes, and content of the element are all constants, the element constructor uses standard XML notation. For example, the following expression creates a book element that contains attributes, subelements, and text:

<book isbn="isbn-0060229357">
	<title>Harold and the Purple Crayon</title>
	<author>
		<first>Crockett</first>
		<last>Johnson</last>
	</author>
</book>	

In an element constructor, the name used in an end tag must match the name of the corresponding start tag. If namespace prefixes are declared in the query prolog, the prefixes they declare may be used to create qualified names for elements and attributes. It is an error to use a namespace prefix that has not been declared.

Ed. Note: The type of an element created by an element constructor, and the validation or type assertions applied to such an element (if any), are currently open issues.

In an element constructor, curly braces { } delimit enclosed expressions, distinguishing them from literal text. Enclosed expressions are evaluated and replaced by their value, whereas material outside curly braces is simply treated as literal text, as illustrated by the following example:

<example>
   <p> Here is a query. </p>
   <eg> $i//title </eg>
   <p> Here is the result of the above query. </p>
   <eg>{ $i//title }</eg>
</example> 

The above query might generate the following result:

<example>
  <p> Here is a query. </p>
  <eg> $i//title </eg>
  <p> Here is the result of the above query. </p>
  <eg><title>Harold and the Purple Crayon</title></eg>
</example>

In an element constructor, an enclosed expression may evaluate to any sequence of nodes and/or simple values. Attribute nodes occurring in this sequence become the attributes of the constructed element. The remainder of the sequence becomes the content of the constructed element.

Ed. Note: The treatment of simple values and heterogeneous sequences when they occur in the content of a constructed element is an open issue. One approach would be to convert all simple values to CDATA during element construction. Another approach would be to preserve simple values in the data model, and allow an operator such as VALIDATE or CAST to create a normal XML-Schema representation of the data.

Whitespace in element constructors is always preserved, using the same behavior defined in XML 1.0 when xml:space is set to "preserve". Whitespace is also preserved in enclosed expressions.

An enclosed expression may also be used to compute the value of an attribute, as illustrated by the following two examples, which are equivalent:

<book isbn="{ $i/booknum }" />
<book isbn={ $i/booknum } />

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, XQuery adopts the same convention as XSLT: Two adjacent curly braces in an XQuery character string are interpreted as a single curly brace character.

2.8.2 Computed Element and Attribute Constructors

An alternative way to create elements and attributes is by using a computed element constructor or a computed attribute constructor. In these constructors, the keyword element or attribute is followed by the name of the node to be created and then by its content. The name may be specified either by a QName or by an enclosed expression that returns a QName, and the content is specified by an enclosed expression.

[58]   ComputedElementConstructor   ::=   "element" (QName |  EnclosedExpr) "{" ExprSequence? "}"
[59]   ComputedAttributeConstructor   ::=   "attribute" (QName |  EnclosedExpr) "{" ExprSequence? "}"

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 this section:

element book 
{
	attribute isbn { isbn-0060229357 },
	element author 
	{
		element first { "Crockett" },
		element last { "Johnson" }
	}
} 

As the names imply, the primary purpose of computed element and attribute constructors is to allow the name of the constructed 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 sequence of entries in a translation dictionary. Here is an example entry:


<entry word="address">
   <variant lang="German">Adresse</variant>
   <variant lang="Italian">indirizzo</variant>
</entry> 

Suppose further that the variable $e is bound to the following element:

<address>123 Roosevelt Ave. Flushing, NY 11368</address>

Then the following expression generates a new element in which the name of $e has been translated into Italian and the content of $e 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:


  element 
    {$dict/entry[word=name($e)]/variant[lang="Italian"]}
    {$e/node()}

The result of this expression is as follows:

<indirizzo>123 Roosevelt Ave. Flushing, NY 11368</indirizzo>

2.8.3 Other Constructors and Comments

The syntax for a CDATA section constructor, a processing instruction constructor, or an XML comment constructor is the same as the syntax of the equivalent XML construct.

[60]   CdataSection   ::=   "<![CDATA[" Char* "]]>"
[61]   XmlProcessingInstruction   ::=   "<?" PITarget Char* "?>"
[62]   XmlComment   ::=   "<!--" Char* "-->"

The following example illustrates constructors for processing instructions, comments, and CDATA sections.

<address><![CDATA[ 
	<address>123 Roosevelt Ave. Flushing, NY 11368</address>
]]></address>

Ed. Note: It is not clear that the Data Model can represent a CDATA section.

Note that an XML comment actually constructs an XML comment node. An XQuery comment (see 2.2.5 Comments) is simply a comment used in documenting a query, and is not evaluated. Consider the following example.

{-- This is an XQuery comment --}
<!-- This is an XML comment -->

The result of evaluating the above expression is as follows.

<!-- This is an XML comment -->

2.9 FLWR Expressions

XQuery provides a FLWR expression for iteration and for binding 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 "FLWR", pronounced "flower", stands for the keywords for, let, where, and return, the four clauses found in a FLWR expression.

[8]   FLWRExpr   ::=   (ForClause |  LetClause)+ WhereClause? "return"  Expr
[27]   ForClause   ::=   "for" Variable "in" Expr ("," Variable "in" Expr)*
[28]   LetClause   ::=   "let" Variable ":=" Expr ("," Variable ":=" Expr)*
[29]   WhereClause   ::=   "where" Expr

The clauses of a FLWR Expression are interpreted as follows:

  1. A for clause associates one or more variables with expressions, creating tuples of variable bindings drawn from the Cartesian product of the sequences of values to which the expressions evaluate. The variable binding tuples are generated as an ordered sequence as described below.

  2. A let clause binds a variable directly to an entire expression. If for clauses are present, the variable bindings created by let clauses are added to the tuples generated by the for clauses. If there are no for clauses, the let clauses generate one tuple with all variable bindings.

  3. A where clause can be used as a filter for the tuples of variable bindings generated by the for and let clauses. The expression in the where clause, called the where-expression, is evaluated once for each of these tuples. If the effective boolean value of the where-expression is true, the tuple is retained and its variable bindings are used in an execution of the return clause. If the effective boolean value of the where-expression is false, the tuple is discarded. The effective boolean value of the where-expression is computed by applying the following rules, in order:

    1. If the where-expression returns an empty sequence, its effective boolean value is false.

    2. If the where-expression returns one simple boolean value, this value serves as the effective boolean value.

    3. If the where-expression returns a sequence that contains at least one node, its effective boolean value is true.

    4. In any other case, a type exception is invoked.

  4. The return clause contains an expression that is used to construct the result of the FLWR expression. The return clause is invoked once for every tuple generated by the for and let clauses, after eliminating any tuples that do not satisfy the conditions of a