XQuery 1.0: An XML Query Language (Second Edition; Revised 7 September 2015) /**/ code { font-family: monospace; }
div.constraint, div.issue, div.note, div.notice { margin-left: 2em; }
div.issue p.title { margin-left: -2em; }
ol.enumar { list-style-type: decimal; } ol.enumla { list-style-type: lower-alpha; } ol.enumlr { list-style-type: lower-roman; } ol.enumua { list-style-type: upper-alpha; } ol.enumur { list-style-type: upper-roman; }
li p { margin-top: 0.3em; margin-bottom: 0.3em; }
sup small { font-style: italic; color: #8F8F8F; } div.exampleInner pre { margin-left: 1em; margin-top: 0em; margin-bottom: 0em} div.exampleOuter {border: 4px double gray; margin: 0em; padding: 0em} div.exampleInner { background-color: #d5dee3; border-top-width: 4px; border-top-style: double; border-top-color: #d3d3d3; border-bottom-width: 4px; border-bottom-style: double; border-bottom-color: #d3d3d3; padding: 4px; margin: 0em } div.exampleWrapper { margin: 4px } div.exampleHeader { font-weight: bold; margin: 4px}
div.issue { border-bottom-color: black; border-bottom-style: solid; border-bottom-width: 1pt; margin-bottom: 20pt; }
th.issue-toc-head { border-bottom-color: black; border-bottom-style: solid; border-bottom-width: 1pt; }
/**/ (Link errors corrected 3 January 2011; revised 7 September 2015) This version: http://www.w3.org/TR/2010/REC-xquery-20101214/ Latest version: http://www.w3.org/TR/xquery/ Previous versions: http://www.w3.org/TR/2009/PER-xquery-20090421/, http://www.w3.org/TR/2007/REC-xquery-20070123/ Editors: Scott Boag (XSL WG), IBM Research <[email protected]> Don Chamberlin (XML Query WG) <[email protected]> Mary F. Fernández (XML Query WG), AT&T Labs <[email protected]> Daniela Florescu (XML Query WG), Oracle <[email protected]> Jonathan Robie (XML Query WG), Red Hat http://www.ibiblio.org/jwrobie/ Jérôme Siméon (XML Query WG), IBM T.J. Watson Research Center <[email protected]> Please refer to the errata See also translations This document is also available in these non-normative formats: XML Change markings relative to first edition Copyright W3C ® MIT ERCIM Keio liability trademark document use Note: This paragraph is informative. http://www.w3.org/TR/xquery-3/ XML is a versatile markup language, capable of labeling the information content of diverse data sources including structured and semi-structured documents, relational databases, and object repositories. A query language that uses the structure of XML intelligently can express queries across all these kinds of data, whether physically stored in XML or viewed as XML via middleware. This specification describes a query language called XQuery, which is designed to be broadly applicable across many types of XML data sources. This section describes the status of this document at the time of its publication. Other documents may supersede this document. A list of current W3C publications and the latest revision of this technical report can be found in the W3C technical reports index 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 Recommendation Proposed Edited Recommendation has been developed by the W3C XML Query Working Group XML Activity 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. This document incorporates changes made against the Recommendation K Changes since the First Edition first edition An implementation report is available at http://www.w3.org/XML/Query/test-suite/XQTSReport.html This document was produced by a group 5 February 2004 W3C Patent Policy public list of any patent disclosures group; that page also includes Essential Claim(s) section 6 of the W3C Patent Policy 1 Introduction Basics Expression Context Static Context Dynamic Context Processing Model Data Model Generation Schema Import Processing Expression Processing Static Analysis Phase Dynamic Evaluation Phase Serialization Consistency Constraints Error Handling Kinds of Errors Identifying and Reporting Errors Handling Dynamic Errors Errors and Optimization Concepts Document Order Atomization Effective Boolean Value Input Sources URI Literals Types Predefined Schema Types Typed Value and String Value SequenceType Syntax SequenceType Matching Matching a SequenceType and a Value Matching an ItemType and an Item Element Test Schema Element Test Attribute Test Schema Attribute Test Comments Expressions Primary Expressions Literals Variable References Parenthesized Expressions Context Item Expression Function Calls Path Expressions Steps Axes Node Tests Predicates Unabbreviated Syntax Abbreviated Syntax Sequence Expressions Constructing Sequences Filter Expressions Combining Node Sequences Arithmetic Expressions Comparison Expressions Value Comparisons General Comparisons Node Comparisons Logical Expressions Constructors Direct Element Constructors Attributes Namespace Declaration Attributes Content Boundary Whitespace Other Direct Constructors Computed Constructors Computed Element Constructors Computed Attribute Constructors Document Node Constructors Text Node Constructors Computed Processing Instruction Constructors Computed Comment Constructors In-scope Namespaces of a Constructed Element FLWOR Expressions For and Let Clauses Where Clause Order By and Return Clauses Example Ordered and Unordered Expressions Conditional Expressions Quantified Expressions Expressions on SequenceTypes Instance Of Typeswitch Cast Castable Constructor Functions Treat Validate Expressions Extension Expressions Modules and Prologs Version Declaration Module Declaration Boundary-space Declaration Default Collation Declaration Base URI Declaration Construction Declaration Ordering Mode Declaration Empty Order Declaration Copy-Namespaces Declaration Schema Import Module Import Namespace Declaration Default Namespace Declaration Variable Declaration Function Declaration Option Declaration Conformance Minimal Conformance Optional Features Schema Import Feature Schema Validation Feature Static Typing Feature Static Typing Extensions Full Axis Feature Module Feature Serialization Feature Data Model Conformance Syntax Extensions A XQuery Grammar EBNF Notation Extra-grammatical Constraints Grammar Notes Lexical structure Terminal Symbols Terminal Delimitation End-of-Line Handling XML 1.0 End-of-Line Handling XML 1.1 End-of-Line Handling Whitespace Rules Default Whitespace Handling Explicit Whitespace Handling Reserved Function Names Precedence Order Type Promotion and Operator Mapping Type Promotion Operator Mapping Context Components Static Context Components Dynamic Context Components Serialization Parameters Implementation-Defined Items References Normative References Non-normative References Background Material Error Conditions The application/xquery Media Type Introduction Registration of MIME Media Type application/xquery Interoperability Considerations Published specification Applications Using this Media Type File Extensions Intended Usage Author/Change Controller Encoding Considerations Recognizing XQuery Files Charset Default Rules Security Considerations Glossary Example Applications Joins Grouping Queries on Sequence Recursive Transformations Selecting Distinct Combinations Guidance for Handling of Modules Module URIs Multiple Modules with the same Module URI Location URIs Cycles Changes since the First Edition 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] [XML Query Use Cases] [Quilt] [XPath 1.0] [XQL] [XML-QL] [SQL] [ODMG] [ Definition data model [XQuery 1.0 and XPath 2.0 Data Model (Second Edition)] 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: [XQuery 1.0 and XPath 2.0 Data Model (Second Edition)] [XQuery 1.0 and XPath 2.0 Formal Semantics (Second Edition)] The type system of XQuery is based on [XML Schema] The built-in function library and the operators supported by XQuery are defined in [XQuery 1.0 and XPath 2.0 Functions and Operators (Second Edition)] One requirement in [XML Query 1.0 Requirements] [XML Syntax for XQuery 1.0 (XQueryX) (Second Edition)] This document specifies a grammar for XQuery, using the same basic EBNF notation used in [XML 1.0] A.2 Lexical structure queries A XQuery Grammar 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: FunctionCall ::= QName ExprSingle ExprSingle 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 implementation-defined implementation-dependent [ Definition Implementation-defined [ Definition Implementation-dependent This document normatively defines the dynamic semantics of XQuery. The static semantics of XQuery are normatively defined in [XQuery 1.0 and XPath 2.0 Formal Semantics (Second Edition)] The basic building block of XQuery is the expression [Unicode] implementation-defined (However, unlike a pure functional language, it does not allow variable substitution if the variable declaration contains construction of new nodes.) Note: This specification contains no assumptions or requirements regarding the character set encoding of strings of [Unicode] 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 A.3 Reserved Function Names [ Definition data model value sequence Definition sequence items Definition item atomic value node Definition atomic value atomic type [XML Schema] Definition node node kinds [XQuery 1.0 and XPath 2.0 Data Model (Second Edition)] node identity typed value string value name typed value string value xs:string name xs:QName Definition undefined [ Definition singleton Definition empty sequence [ Definition XDM instance value nodes atomic values data model Names in XQuery are called QNames [XML Names] Definition QName expanded QName statically known namespaces err:XPST0081 Definition expanded QName xs:anyURI [XML Schema] 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 4.15 Function Declaration In addition to the prefixes in the above list, this document uses the prefix err http://www.w3.org/2005/xqt-errors 2.3.2 Identifying and Reporting Errors Element nodes have a property called in-scope namespaces Definition in-scope namespaces namespace bindings Note: In [XPath 1.0] namespace nodes namespace axis [XML Path Language (XPath) 2.0 (Second Edition)] [XSLT 2.0 and XQuery 1.0 Serialization (Second Edition)] [ Definition URI [RFC3986] [RFC3987] IRI [ Definition expression context static context dynamic context [ Definition static context static error static context static error err:XPST0001 The individual components of the static context Rules governing the scope and initialization of these components can be found in C.1 Static Context Components [ Definition XPath 1.0 compatibility mode. This component must be set by all host languages that include XPath 2.0 as a subset, indicating whether rules for compatibility with XPath 1.0 are in effect. XQuery sets the value of this component to false [ Definition Statically known namespaces. xs:anyURI [XML Schema] in-scope namespaces statically known namespaces Some namespaces are predefined; additional namespaces can be added to the statically known namespaces by namespace declarations Prolog namespace declaration attributes direct element constructors [ Definition Default element/type namespace. xs:anyURI [XML Schema] [ Definition Default function namespace. xs:anyURI [XML Schema] [ Definition In-scope schema definitions. [ Definition In-scope schema types. expanded QName named type implementation-dependent anonymous type 2.5.1 Predefined Schema Types If the Schema Import Feature [ Definition In-scope element declarations. expanded QName implementation-dependent If the Schema Import Feature substitution group [ Definition Substitution groups [XML Schema] head element [ Definition In-scope attribute declarations. expanded QName implementation-dependent If the Schema Import Feature [ Definition In-scope variables. expanded QName static type Variable declarations in a Prolog in-scope variables let for some every in-scope variables Within a function declaration in-scope variables function parameters The static type of a variable may be either declared in a query or (if the Static Typing Feature [XQuery 1.0 and XPath 2.0 Formal Semantics (Second Edition)] [ Definition Context item static type. static type [ Definition Function signatures. expanded QName static types The function signatures constructor functions 3.12.5 Constructor Functions [ Definition Statically known collations. implementation-defined queries and Definition collation [XQuery 1.0 and XPath 2.0 Functions and Operators (Second Edition)] [ Definition Default collation. statically known collations xs:string xs:anyURI [ Definition Construction mode. preserve xs:anyType strip xs:untyped xs:untyped xs:untypedAtomic [ Definition Ordering mode. ordered unordered path expressions union intersect except order by [ Definition Default order for empty sequences. NaN order by 3.8.3 Order By and Return Clauses greatest least [ Definition Boundary-space policy. boundary whitespace direct element constructors 3.7.1.4 Boundary Whitespace preserve strip [ Definition Copy-namespaces mode. 3.7.1 Direct Element Constructors preserve no-preserve inherit no-inherit [ Definition Base URI. fn:resolve-uri xs:anyURI [XML Schema] [ Definition Statically known documents. fn:doc static type fn:doc fn:doc statically known documents static type fn:doc document-node()? Note: The purpose of the statically known documents statically known documents fn:doc [ Definition Statically known collections. fn:collection fn:collection fn:collection statically known collections static type fn:collection node()* Note: The purpose of the statically known collections statically known collections fn:collection [ Definition Statically known default collection type. fn:collection statically known default collection type node()* [ Definition dynamic context dynamic context dynamic error err:XPDY0002 The individual components of the dynamic context C.2 Dynamic Context Components The dynamic context static context [ Definition dynamic context focus Certain language constructs, notably the path expression E1/E2 predicate E1[E2] E2 E1 E2 E2 inner focus E1 outer focus E2 [ Definition context item Definition context node . E1/E2 E1[E2] E1 E2 [ Definition context position fn:position() E1/E2 E1[E2] E2 E1 [ Definition context size fn:last() E1/E2 E1[E2] E2 E1 [ Definition Variable values expanded QNames in-scope variables static context dynamic type [ Definition Function implementations function signatures For a user-defined function built-in function external function implementation-dependent [ Definition Current dateTime. implementation-dependent a query fn:current-dateTime a query [ Definition Implicit timezone. implementation-defined xs:dayTimeDuration [XML Schema] [ Definition Available documents. data model fn:doc statically known documents If there are one or more URIs in available documents D D Note: This means that given a document node $N fn:doc(fn:document-uri($N)) is $N fn:document-uri($N) [ Definition Available collections. fn:collection statically known collections For every document node D available collections D U available documents U D Note: This means that for any document node $N fn:collection fn:doc(fn:document-uri($N)) is $N fn:document-uri($N) fn:doc fn:collection fn:doc fn:collection fn:doc [ Definition Default collection. fn:collection default collection XQuery is defined in terms of the data model expression context 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 external processing XDM instance 2.2.1 Data Model Generation 2.2.2 Schema Import Processing 2.2.4 Serialization query processing domain 2.2.3 Expression Processing query 2.2.5 Consistency Constraints Before a query XDM instance XDM instance A document may be parsed using an XML parser that generates an XML Information Set [XML Infoset] [XML Schema] Post-Schema Validation Infoset The Information Set or PSVI may be transformed into an XDM instance [XQuery 1.0 and XPath 2.0 Data Model (Second Edition)] The above steps provide an example of how an XDM instance data model [ Definition XDM instance type annotation [XQuery 1.0 and XPath 2.0 Data Model (Second Edition)] type-name schema type string value typed value XDM instance Section 3.3 Construction from a PSVI DM 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 type annotation 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 type annotation xs:untyped xs:anyType xs:untyped xs:untyped xs:anyType type annotation The in-scope schema definitions static context [XQuery 1.0 and XPath 2.0 Formal Semantics (Second Edition)] 2.2.5 Consistency Constraints XQuery defines two phases of processing called the static analysis phase dynamic evaluation phase static errors dynamic errors type errors dynamic errors type errors 2.3.1 Kinds of Errors Within each phase, an implementation is free to use any strategy or algorithm whose result conforms to the specifications in this document. [ Definition static analysis phase static context static analysis phase During the static analysis phase, the query operation tree static error err:XPST0003 static context The static context prolog Schema Import Feature in-scope schema definitions Module Feature static context operation tree static context static error err:XPST0008 err:XPST0017 2.5.4.3 Element Test 2.5.4.5 Attribute Test The operation tree normalized atomization Effective Boolean Values [XQuery 1.0 and XPath 2.0 Formal Semantics (Second Edition)] Each expression is then assigned a static type Definition static type Static Typing Feature static types [XQuery 1.0 and XPath 2.0 Formal Semantics (Second Edition)] Static Typing Feature implementation-dependent During the static analysis phase Static Typing Feature static type type error err:XPTY0004 static type dynamic error The purpose of the Static Typing Feature type errors [ Definition dynamic evaluation phase static analysis phase The dynamic evaluation phase can occur only if no errors were detected during the static analysis phase Static Typing Feature type errors The dynamic evaluation phase depends on the operation tree dynamic context static context dynamic context [ Definition dynamic type static type xs:integer* xs:integer If an operand of an expression is found to have a dynamic type type error err:XPTY0004 Even though static typing can catch many type errors dynamic error static type xs:untypedAtomic static error numeric dynamic error When the Static Typing Feature type error static type type error [ Definition Serialization XDM instance [XSLT 2.0 and XQuery 1.0 Serialization (Second Edition)] An XQuery implementation is not required to provide a serialization interface. For example, an implementation may only provide a DOM interface (see [Document Object Model] [XSLT 2.0 and XQuery 1.0 Serialization (Second Edition)] serialization parameters C.3 Serialization Parameters method = "xml" version = "1.0" Note: The data model in-scope namespaces [XML Names 1.1] [XML Names 1.1] In order for XQuery to be well defined, the input XDM instance static context dynamic context a query Some of the consistency constraints use the term data model schema Definition XDM instance data model schema type annotation data model schema type annotation For every node that has a type annotation, if that type annotation is found in the in-scope schema definitions data model schema data model schema For every element name EN XDM instance in-scope schema definitions data model schema substitution group EN substitution group EN Every element name, attribute name, or schema type name referenced in in-scope variables function signatures in-scope schema definitions ElementTest AttributeTest Any reference to a global element, attribute, or type name in the in-scope schema definitions in-scope schema definitions For each mapping of a string to a document node in available documents statically known documents 2.5.4 SequenceType Matching For each mapping of a string to a sequence of nodes in available collections statically known collections 2.5.4 SequenceType Matching The sequence of nodes in the default collection statically known default collection type 2.5.4 SequenceType Matching The value of the context item context item static type 2.5.4 SequenceType Matching For each (variable, type) pair in in-scope variables variable values 2.5.4 SequenceType Matching For each variable declared as external 2.5.4 SequenceType Matching For each function declared as external: the function implementation 2.5.4 SequenceType Matching implementation-defined For a given query, define a participating ISSD in-scope schema definitions T T E E In the statically known namespaces xml http://www.w3.org/XML/1998/namespace xml As described in 2.2.3 Expression Processing static analysis phase dynamic evaluation phase [ Definition static error static error [ Definition dynamic error [ Definition type error type error static type type error dynamic type The outcome of the static analysis phase type errors static errors dynamic errors dynamic evaluation phase type error dynamic error 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 static analysis phase Static Typing Feature static type () data(()) empty-sequence() static error err:XPST0005 in-scope schema definitions Independently of whether the Static Typing Feature static analysis phase type error dynamic error static analysis phase fn:error() static analysis phase [ Definition static errors dynamic errors type errors warnings static analysis phase dynamic evaluation phase implementation-defined In addition to the errors defined in this specification, an implementation may raise a dynamic error implementation-dependent The errors defined in this specification are identified by QNames that have the form err:XXYYnnnn err http://www.w3.org/2005/xqt-errors err XX XP XQ YY ST DY TY nnnn Note: 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 implementation-defined 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 http://www.w3.org/2005/xqt-errors#XPST0017 Note: 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 implementation-defined Except as noted in this document, if any operand of an expression raises a dynamic error dynamic error expr1 and expr2 false false 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: ($x div $y) + xs:decimal($z) both the sub-expressions ($x div $y) xs:decimal($z) + [ Definition error values A dynamic error may be raised by a built-in function div xs:decimal [XQuery 1.0 and XPath 2.0 Functions and Operators (Second Edition)] A dynamic error can also be raised explicitly by calling the fn:error [XQuery 1.0 and XPath 2.0 Functions and Operators (Second Edition)] app fn:error(xs:QName("app:err057"), "Unexpected value", fn:string($v)) Because different implementations may choose to evaluate or optimize an expression in different ways, certain aspects of the detection and reporting of dynamic errors implementation-dependent 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 filter expressions $s[1] $s position()=1 $s //book[author eq 'Berners-Lee'] book author 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 Q E E Q V V E There is an exception to this rule: If a processor evaluates an operand E E $e eq 0 $e $e true $e These rules apply to all the operands of an expression considered in combination: thus if an expression has two operands E1 E2 The rules cascade: if A B B C B C A B 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 S1 = S2 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 47 true some $expr1 some $x in $expr1 satisfies $x = 47 In the following example, if an implementation can find (for example, by using an index) the product id 47 path expression product id //product[id = 47] 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. Note: 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. Note: 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 implementation-dependent implementation-defined 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 if (doc-available('abc.xml')) then doc('abc.xml') else () As stated earlier, an expression must not be rewritten to dispense with a required cardinality check: for example, string-length(//title) 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 //part[color eq "Red"] //part[color = "Red"][color eq "Red"] = eq 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. 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. $N[@x castable as xs:date][xs:date(@x) gt xs:date("2000-01-01")] To avoid unexpected errors caused by expression rewrite, tests that are designed to prevent dynamic errors should be expressed using conditional or typeswitch $N[if (@x castable as xs:date) then xs:date(@x) gt xs:date("2000-01-01") else false()] This section explains some concepts that are important to the processing of XQuery expressions. An ordering called document order query trees [XQuery 1.0 and XPath 2.0 Data Model (Second Edition)] Definition reverse document order Document order is a total ordering, although the relative order of some nodes is implementation-dependent Definition document order Definition stable query implementation-dependent 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 implementation-dependent The relative order of siblings is the order in which they occur in the children Children and descendants occur before following siblings. The relative order of nodes in distinct trees is stable but implementation-dependent The semantics of some XQuery operators depend on a process called atomization type error Definition Atomization fn:data [XQuery 1.0 and XPath 2.0 Functions and Operators (Second Edition)] The semantics of fn:data fn:data If the item is an atomic value, it is returned. If the item is a node, its typed value 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 Under certain circumstances (listed below), it is necessary to find the effective boolean value Definition effective boolean value fn:boolean [XQuery 1.0 and XPath 2.0 Functions and Operators (Second Edition)] The dynamic semantics of fn:boolean If its operand is an empty sequence, fn:boolean false If its operand is a sequence whose first item is a node, fn:boolean true If its operand is a singleton xs:boolean xs:boolean fn:boolean If its operand is a singleton xs:string xs:anyURI xs:untypedAtomic fn:boolean false true If its operand is a singleton numeric fn:boolean false NaN true In all other cases, fn:boolean Note: The static semantics of fn:boolean Section 7.2.4 The fn:boolean and fn:not functions FS Note: The effective boolean value ordering mode unordered The effective boolean value Logical expressions ( and or The fn:not The where Certain types of predicates a[b] Conditional expressions ( if Quantified expressions ( some every Note: The definition of effective boolean value not xs:boolean cast 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 [XQuery 1.0 and XPath 2.0 Functions and Operators (Second Edition)] An expression can access input data either by calling one of the input functions or by referencing some part of the dynamic context variable context item The input functions supported by XQuery are as follows: The fn:doc available documents fn:doc data model dynamic error [XQuery 1.0 and XPath 2.0 Functions and Operators (Second Edition)] The fn:collection available collections fn:collection dynamic error [XQuery 1.0 and XPath 2.0 Functions and Operators (Second Edition)] fn:collection("http://example.org")//customer customer http://example.org The fn:collection default collection implementation-dependent In certain places in the XQuery grammar, a statically known valid URI is required. These places are denoted by the grammatical symbol URILiteral URILiteral ::= StringLiteral Syntactically, a URILiteral is identical to a StringLiteral MAY static error err:XQST0046 xs:anyURI As in a string literal, any predefined entity reference & character reference • EscapeQuot EscapeApos "" predefined entity reference character reference The URILiteral is subjected to whitespace normalization as defined for the xs:anyURI [XML Schema] character references 
 The URILiteral is not automatically subjected to percent-encoding or decoding as defined in [RFC3986] Note: The xs:anyURI [RFC3987] The following is an example of a valid URILiteral: "http://www.w3.org/2005/xpath-functions/collation/codepoint" The type system of XQuery is based on [XML Schema] [XQuery 1.0 and XPath 2.0 Formal Semantics (Second Edition)] [ Definition sequence type SequenceType sequence type [ Definition schema type [XML Schema] [XML Schema] xs:NOTATION xs:anyAtomicType complex type simple type list types union types atomic types [XML Schema] Atomic types represent the intersection between the categories of sequence type schema type xs:integer my:hatsize sequence type schema type The in-scope schema types static context http://www.w3.org/2001/XMLSchema xs [XML Schema] [XQuery 1.0 and XPath 2.0 Data Model (Second Edition)] xs [XQuery 1.0 and XPath 2.0 Data Model (Second Edition)] [ Definition xs:untyped type annotation skip xs:untyped [ Definition xs:untypedAtomic skip data model type annotation xs:untypedAtomic xs:untypedAtomic [ Definition xs:dayTimeDuration xs:duration xs:dayTimeDuration [ Definition xs:yearMonthDuration xs:duration xs:yearMonthDuration [ Definition xs:anyAtomicType xs:anySimpleType xs:decimal xs:string xs:anyAtomicType Note: xs:anyAtomicType XDM instance The relationships among the schema types in the xs [XQuery 1.0 and XPath 2.0 Functions and Operators (Second Edition)] Figure 2: Hierarchy of Schema Types used in XQuery Every node has a typed value string value Definition typed value fn:data Definition string value fn:string fn:data fn:string [XQuery 1.0 and XPath 2.0 Functions and Operators (Second Edition)] An implementation may store both the typed value string value xs:integer 30 30 0030 The typed value string value type annotation If the node was created by mapping from an Infoset or PSVI, see rules in [XQuery 1.0 and XPath 2.0 Data Model (Second Edition)] If the node was created by an XQuery node constructor, see rules in 3.7.1 Direct Element Constructors 3.7.3.1 Computed Element Constructors 3.7.3.2 Computed Attribute Constructors If the node was created by a validate 3.13 Validate Expressions As a convenience to the reader, the relationship between typed value string value 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 document order 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 type annotation xs:anySimpleType xs:untypedAtomic xs:untypedAtomic [XML Schema] Example: A1 is an attribute having string value "3.14E-2" xs:double xs:double 3.14E-2 Example: A2 is an attribute with type annotation xs:IDREFS xs:IDREF bar baz faz bar baz faz xs:IDREF xs:IDREFS xs:IDREF For an element node, the relationship between typed value and string value depends on the node's type annotation If the type annotation is xs:untyped xs:anySimpleType xs:anyType xs:untypedAtomic nilled true Example: E1 is an element node having type annotation xs:untyped 1999-05-31 1999-05-31 xs:untypedAtomic Example: E2 is an element node with the type annotation formula H subscript 2 O H2O 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 true Example: E3 is an element node with the type annotation cost xs:decimal 74.95 74.95 xs:decimal Example: E4 is an element node with the type annotation hatsizelist hatsize xs:integer 7 8 9 7 8 9 hatsize Example: E5 is an element node with the type annotation my:integer-or-string xs:integer xs:string 47 47 xs:integer xs:integer Note: 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 undefined fn:data type error Example: E6 is an element node with the type annotation weather element-only temperature precipitation undefined fn:data Whenever it is necessary to refer to a type in an XQuery expression, the SequenceType SequenceType ::= ("empty-sequence" "(" ")") ItemType OccurrenceIndicator ItemType ::= KindTest AtomicType OccurrenceIndicator ::= "?" | "*" | "+" AtomicType ::= QName KindTest ::= DocumentTest ElementTest AttributeTest SchemaElementTest SchemaAttributeTest PITest CommentTest TextTest AnyKindTest DocumentTest ::= "document-node" "(" ( ElementTest SchemaElementTest ElementTest ::= "element" "(" ( ElementNameOrWildcard TypeName SchemaElementTest ::= "schema-element" "(" ElementDeclaration ElementDeclaration ::= ElementName AttributeTest ::= "attribute" "(" ( AttribNameOrWildcard TypeName SchemaAttributeTest ::= "schema-attribute" "(" AttributeDeclaration AttributeDeclaration ::= AttributeName ElementNameOrWildcard ::= ElementName ElementName ::= QName AttribNameOrWildcard ::= AttributeName AttributeName ::= QName TypeName ::= QName PITest ::= "processing-instruction" "(" ( NCName StringLiteral CommentTest ::= "comment" "(" ")" TextTest ::= "text" "(" ")" AnyKindTest ::= "node" "(" ")" With the exception of the special type empty-sequence() sequence type item type cardinality item() node types element() atomic types xs:integer Item types representing element and attribute nodes may specify the required type annotations schema type element(*, us:address) us:address Here are some examples of sequence types xs:date xs:date attribute()? element() element(po:shipto, po:address) po:shipto po:address po:address element(*, po:address) po:address po:address element(customer) customer schema-element(customer) customer customer customer in-scope element declarations node()* item()+ [ Definition dynamic type sequence type SequenceType matching instance of true dynamic type sequence type false QNames appearing in a sequence type statically known namespaces default element/type namespace eq The rules for SequenceType matching dynamic type sequence type [XQuery 1.0 and XPath 2.0 Formal Semantics (Second Edition)] SequenceType Some of the rules for SequenceType matching in-scope schema definitions in-scope schema definitions static context implementation-dependent [ Definition dynamic type subtype substitution xs:integer xs:decimal xs:integer The definition of SequenceType matching derives-from( AT, ET ) AT ET type error err:XPTY0004 derives-from [XQuery 1.0 and XPath 2.0 Formal Semantics (Second Edition)] derives-from( AT ET ) true ET AT in-scope schema definitions ET ET AT in-scope schema definitions implementation-dependent AT ET There exists some schema type IT derives-from( IT, ET ) derives-from( AT, IT ) derives-from( AT ET ) false ET AT in-scope schema definitions ET ET AT in-scope schema definitions implementation-dependent AT ET No schema type IT derives-from( IT, ET ) derives-from( AT, IT ) derives-from( AT ET ) type error err:XPTY0004 ET AT AT ET Note: The derives-from The rules for SequenceType matching The sequence type empty-sequence() An ItemType OccurrenceIndicator ItemType 2.5.4.2 Matching an ItemType and an Item An ItemType OccurrenceIndicator OccurrenceIndicator ItemType An OccurrenceIndicator ? * + As a consequence of these rules, any sequence type OccurrenceIndicator * ? An ItemType AtomicType AtomicType AT derives-from( AT, AtomicType ) true AtomicType in-scope schema types static error err:XPST0051 Example: The AtomicType xs:decimal 12.34 xs:decimal shoesize shoesize xs:decimal Note: The names of non-atomic types such as xs:IDREFS xs:IDREF+ item() Example: item() 1 <a/> node() text() processing-instruction() processing-instruction( N ) fn:normalize-space(N) fn:normalize-space(N) err:XPTY0004 Example: processing-instruction(xml-stylesheet) 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() document-node() document-node( E ) E ElementTest SchemaElementTest 2.5.4.3 Element Test 2.5.4.4 Schema Element Test Example: document-node(element(book)) element(book) An ItemType ElementTest SchemaElementTest AttributeTest SchemaAttributeTest An ElementTest type annotation ElementTest ElementName in-scope element declarations TypeName in-scope schema types err:XPST0008 substitution groups ElementTest element() element(*) element( ElementName ) ElementName nilled Example: element(person) person element( ElementName , TypeName ) ElementName derives-from( AT TypeName ) true AT nilled false Example: element(person, surgeon) person surgeon surgeon element( ElementName TypeName ?) ElementName derives-from( AT TypeName ) true AT nilled true false Example: element(person, surgeon?) person surgeon surgeon element(*, TypeName ) derives-from( AT TypeName ) true AT nilled false Example: element(*, surgeon) surgeon surgeon element(*, TypeName ?) derives-from( AT TypeName ) true AT nilled true false Example: element(*, surgeon?) surgeon surgeon A SchemaElementTest in-scope element declarations schema-element( ElementName ) If the ElementName SchemaElementTest in-scope element declarations static error err:XPST0008 A SchemaElementTest The name of the candidate node matches the specified ElementName substitution group ElementName derives-from( AT, ET ) true AT ET ElementName in-scope element declarations If the element declaration for ElementName in-scope element declarations nillable nilled false Example: The SchemaElementTest schema-element(customer) customer in-scope element declarations customer substitution group customer customer nilled customer nillable An AttributeTest type annotation AttributeTest AttributeName in-scope attribute declarations TypeName in-scope schema types err:XPST0008 attribute() attribute(*) attribute( AttributeName ) AttributeName Example: attribute(price) price attribute( AttributeName TypeName ) AttributeName derives-from( AT TypeName ) true AT Example: attribute(price, currency) price currency currency attribute(*, TypeName ) derives-from( AT TypeName ) true AT Example: attribute(*, currency) currency currency A SchemaAttributeTest in-scope attribute declarations schema-attribute( AttributeName ) If the AttributeName SchemaAttributeTest in-scope attribute declarations static error err:XPST0008 A SchemaAttributeTest The name of the candidate node matches the specified AttributeName derives-from( AT, ET ) true AT ET AttributeName in-scope attribute declarations Example: The SchemaAttributeTest schema-attribute(color) color in-scope attribute declarations color color Comment ::= "(:" ( CommentContents Comment CommentContents ::= ( Char Comments may be used to provide informative annotation for a query, either in the Prolog Query Body query Comments are strings, delimited by the symbols (: :) A comment may be used anywhere ignorable whitespace A.2.4.1 Default Whitespace Handling The following is an example of a comment: (: Houston, we have a problem :) This section discusses each of the basic kinds of expression. Each kind of expression has a name such as PathExpr 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 [ A XQuery Grammar [ Definition query modules Query Body Expr Expr ::= ExprSingle ExprSingle ExprSingle ::= FLWORExpr QuantifiedExpr TypeswitchExpr IfExpr OrExpr The XQuery operator that has lowest precedence is the comma operator Expr ExprSingle ExprSingle comma operator ExprSingle The symbol ExprSingle ExprSingle After the comma, the expressions that have next lowest precedence are FLWORExpr QuantifiedExpr TypeswitchExpr IfExpr OrExpr [ Definition Primary expressions constructors, Constructors are described in 3.7 Constructors PrimaryExpr ::= Literal VarRef ParenthesizedExpr ContextItemExpr FunctionCall OrderedExpr UnorderedExpr Constructor [ Definition literal Literal ::= NumericLiteral StringLiteral NumericLiteral ::= IntegerLiteral DecimalLiteral DoubleLiteral IntegerLiteral ::= Digits DecimalLiteral ::= ("." Digits Digits DoubleLiteral ::= (("." Digits Digits Digits StringLiteral ::= ('"' ( PredefinedEntityRef CharRef EscapeQuot PredefinedEntityRef CharRef EscapeApos PredefinedEntityRef ::= "&" ("lt" | "gt" | "amp" | "quot" | "apos") ";" Digits ::= [0-9]+ The value of a numeric literal . e E xs:integer . e E xs:decimal e E xs:double xs:untypedAtomic Section 17.1.1 Casting from xs:string and xs:untypedAtomic FO The value of a string literal xs:string A string literal may contain a predefined entity reference Definition predefined entity reference Entity Reference Character Represented < < > > & & " " ' ' A string literal may also contain a character reference Definition character reference [Unicode] € implementation-defined [XML 1.0] [XML 1.1] static error err:XQST0090 Here are some examples of literal expressions: "12.5" 12 xs:integer 12.5 xs:decimal 125E2 xs:double "He said, ""I don't like it.""" "Ben & Jerry's" xs:string Ben & Jerry's "€99.50" xs:string €99.50 The xs:boolean true false built-in functions fn:true() fn:false() Values of other atomic types can be constructed by calling the constructor function [XQuery 1.0 and XPath 2.0 Functions and Operators (Second Edition)] xs:integer("12") xs:date("2001-08-25") xs:date xs:dayTimeDuration("PT5H") xs:dayTimeDuration Constructor functions can also be used to create special values that have no literal representation, as in the following examples: xs:float("NaN") xs:double("INF") It is also possible to construct values of various types by using a cast 9 cast as hatsize 9 hatsize VarRef ::= "$" VarName VarName ::= QName [ Definition variable reference statically known namespaces Every variable reference must match a name in the in-scope variables A variable may be declared in a Prolog module imported module 4 Modules and Prologs The in-scope variables implementation-defined A variable may be bound by an XQuery expression. The kinds of expressions that can bind variables are FLWOR expressions ( 3.8 FLWOR Expressions 3.11 Quantified Expressions typeswitch 3.12.2 Typeswitch Every variable binding has a static scope. The scope defines where references to the variable can validly occur. It is a static error err:XPST0008 static context A reference to a variable that was declared external err:XPDY0002 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. ParenthesizedExpr ::= "(" Expr Parentheses may be used to enforce a particular evaluation order in expressions that contain multiple operators. For example, the expression (2 + 4) * 5 (2 + 4) 2 + 4 * 5 Empty parentheses are used to denote an empty sequence, as described in 3.3.1 Constructing Sequences ContextItemExpr ::= "." A context item expression context item fn:doc("bib.xml")/books/book[fn:count(./author)>1] (1 to 100)[. mod 5 eq 0] If the context item undefined err:XPDY0002 [ Definition built-in functions [XQuery 1.0 and XPath 2.0 Functions and Operators (Second Edition)] Additional functions may be declared in a Prolog library module static context FunctionCall ::= QName ExprSingle ExprSingle A function call arguments default function namespace. If the expanded QName function signature static context static error err:XPST0017 A function call is evaluated as follows: Argument expressions are evaluated, producing argument values. The order of argument evaluation is implementation-dependent 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 [XQuery 1.0 and XPath 2.0 Functions and Operators (Second Edition)] 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 dynamic type $p xs:decimal xs:integer xs:decimal dynamic type $p xs:integer xs:decimal xs:integer During evaluation of a function body, the static context dynamic context module module focus undefined If the function is a user-declared external function, its function implementation implementation-defined 2.2.5 Consistency Constraints The function conversion rules or a return value parameter or return. sequence type If the expected type is a sequence of an atomic type (possibly with an occurrence indicator * + ? Atomization Each item in the atomic sequence that is of type xs:untypedAtomic built-in functions numeric xs:untypedAtomic xs:double For each numeric promoted B.1 Type Promotion For each item of type xs:anyURI promoted B.1 Type Promotion If, after the above conversions, the resulting value does not match the expected type according to the rules for SequenceType Matching type error err:XPTY0004 If the function call takes place in a module module in-scope schema definitions SequenceType Matching Since the arguments of a function call are separated by commas, any argument expression that contains a top-level comma operator my:three-argument-function(1, 2, 3) my:two-argument-function((1, 2), 3) my:two-argument-function(1, ()) my:one-argument-function((1, 2, 3)) my:one-argument-function(( )) my:zero-argument-function( ) PathExpr ::= ("/" RelativePathExpr RelativePathExpr RelativePathExpr RelativePathExpr ::= StepExpr StepExpr [ Definition path expression steps / // / // / // A path expression consisting of a single step is evaluated as described in 3.2.1 Steps A " / (fn:root(self::node()) treat as document-node()) / / type error err:XPTY0020 dynamic error err:XPDY0050 A " // (fn:root(self::node()) treat as document-node()) // err:XPST0003 type error err:XPTY0020 dynamic error err:XPDY0050 Note: The descendants of a node do not include attribute nodes . Each non-initial occurrence of " // 3.2.4 Abbreviated Syntax / E1/E2 E1 type error err:XPTY0019 E1 inner focus E2 2.1.2 Dynamic Context E2 If every evaluation of E2 If ordering mode ordered document order implementation-dependent If every evaluation of E2 If ordering mode ordered E2 implementation-dependent If the multiple evaluations of E2 type error err:XPTY0018 Note: 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 para div1 para div1 Note: The " / /* * / * leading-lone-slash /* / * /*5 / * 5 / (/) * 5 4 + / * 5 4 + (/) * 5 4 + / / StepExpr ::= FilterExpr AxisStep AxisStep ::= ( ReverseStep ForwardStep PredicateList ForwardStep ::= ( ForwardAxis NodeTest AbbrevForwardStep ReverseStep ::= ( ReverseAxis NodeTest AbbrevReverseStep PredicateList ::= Predicate [ Definition step path expression predicates axis step filter expression 3.3.2 Filter Expressions [ Definition axis step axis node test type annotation type error err:XPTY0020 If ordering mode ordered document order implementation-dependent forward step reverse step predicates In the abbreviated syntax 3.2.4 Abbreviated Syntax 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 type annotation child::para para child para 3.2.1.1 Axes 3.2.1.2 Node Tests 3.2.3 Unabbreviated Syntax 3.2.4 Abbreviated Syntax ForwardAxis ::= ("child" "::") ReverseAxis ::= ("parent" "::") XQuery supports the following axes (subject to limitations as described in 5.2.4 Full Axis Feature The child dm:children [XQuery 1.0 and XPath 2.0 Data Model (Second Edition)] Note: 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 the parent dm:parent [XQuery 1.0 and XPath 2.0 Data Model (Second Edition)] Note: 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 Note: 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 document order following-sibling the preceding-sibling document order preceding-sibling the following document order the preceding document order the attribute dm:attributes [XQuery 1.0 and XPath 2.0 Data Model (Second Edition)] the self the descendant-or-self the ancestor-or-self Axes can be categorized as forward axes reverse axes document order document order The parent ancestor ancestor-or-self preceding preceding-sibling ancestor descendant following preceding self [ Definition principal node kind For the attribute axis, the principal node kind is attribute. For all other axes, the principal node kind is element. [ Definition node test step type annotation NodeTest ::= KindTest NameTest NameTest ::= QName Wildcard Wildcard ::= "*" NCName NCName [ Definition name test kind principal node kind expanded QName eq expanded QName child::para para para attribute::abc:href abc:href A QName in a name test is resolved into an expanded QName statically known namespaces static error err:XPST0081 principal node kind default element/type namespace A name test is not satisfied by an element node whose name does not match the expanded QName substitution group A node test * principal node kind child::* attribute::* A node test can have the form NCName:* statically known namespaces static context static error err:XPST0081 principal node kind expanded QName A node test can also have the form *:NCName principal node kind [ Definition kind test type annotation 2.5.3 SequenceType Syntax 2.5.4 SequenceType Matching node test node() text() comment() element() schema-element(person) person substitution group person person in-scope element declarations element(person) person element(person, surgeon) person surgeon surgeon element(*, surgeon) surgeon surgeon attribute() attribute(price) price attribute(*, xs:decimal) xs:decimal xs:decimal document-node() document-node(element(book)) kind test element(book) Predicate ::= "[" Expr [ Definition predicate predicate expression For each item in the input sequence, the predicate expression is evaluated using an inner focus For each item in the input sequence, the result of the predicate expression is coerced to an xs:boolean predicate truth value true false The predicate truth value is derived by applying the following rules, in order: If the value of the predicate expression is a singleton numeric numeric true eq context position false Definition numeric predicate Note: In a region of a query where ordering mode unordered 3.9 Ordered and Unordered Expressions Otherwise, the predicate truth value is the effective boolean value Here are some examples of axis steps This example selects the second chapter child::chapter[2] This example selects all the descendants of the context node that are elements named "toy" color "red" descendant::toy[attribute::color = "red"] This example selects all the employee secretary assistant child::employee[secretary][assistant] Note: When using predicates reverse axis reverse document order preceding::foo[1] foo reverse document order axis step (preceding::foo)[1] foo document order (preceding::foo) primary expression ancestor::*[1] ancestor (ancestor::*)[1] 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 (when in ordered mode) This section provides a number of examples of path expressions in which the axis is explicitly specified in each step unabbreviated syntax abbreviated syntax 3.2.4 Abbreviated Syntax child::para para child::* child::text() child::node() attribute::name name attribute::* parent::node() descendant::para para ancestor::div div ancestor-or-self::div div div descendant-or-self::para para para self::para para child::chapter/descendant::para para chapter child::*/child::para para / /descendant::para para /descendant::list/child::member member list child::para[fn:position() = 1] para child::para[fn:position() = fn:last()] para child::para[fn:position() = fn:last()-1] para child::para[fn:position() > 1] para para following-sibling::chapter[fn:position() = 1] chapter preceding-sibling::chapter[fn:position() = 1] chapter /descendant::figure[fn:position() = 42] figure /child::book/child::chapter[fn:position() = 5]/child::section[fn:position() = 2] section chapter book child::para[attribute::type eq "warning"] para type warning child::para[attribute::type eq 'warning'][fn:position() = 5] para type warning child::para[fn:position() = 5][attribute::type eq "warning"] para type warning child::chapter[child::title = 'Introduction'] chapter title typed value Introduction child::chapter[child::title] chapter title child::*[self::chapter or self::appendix] chapter appendix child::*[self::chapter or self::appendix][fn:position() = fn:last()] chapter appendix AbbrevForwardStep ::= "@"? NodeTest AbbrevReverseStep ::= ".." The abbreviated syntax permits the following abbreviations: The attribute axis attribute:: @ para[@type="warning"] child::para[attribute::type="warning"] para type warning If the axis name is omitted from an axis step child AttributeTest SchemaAttributeTest attribute section/para child::section/child::para section/@id child::section/attribute::id section/attribute(id) child::section/attribute::attribute(id) node test Each non-initial occurrence of // /descendant-or-self::node()/ div1//para child::div1/descendant-or-self::node()/child::para para div1 Note: The path expression //para[1] not /descendant::para[1] para para para A step consisting of .. parent::node() ../title parent::node()/child::title title Note: The expression . context item expression primary expression 3.1.4 Context Item Expression Here are some examples of path expressions that use the abbreviated syntax: para para * text() @name name @* para[1] para para[fn:last()] para */para para /book/chapter[5]/section[2] section chapter book chapter//para para chapter //para para para //@version version //list/member member list .//para para .. ../@lang lang para[@type="warning"] para type warning para[@type="warning"][5] para type warning para[5][@type="warning"] para type warning chapter[title="Introduction"] chapter title typed value Introduction chapter[title] chapter title employee[@secretary and @assistant] employee secretary assistant book/(chapter|appendix)/section section chapter appendix book If E E/. document order XQuery supports operators to construct, filter, and combine sequences items 1 (2, 3) ( ) (1, 2, 3) Expr ::= ExprSingle ExprSingle RangeExpr ::= AdditiveExpr AdditiveExpr [ Definition comma operator 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. Note: In places where the grammar calls for ExprSingle Here are some examples of expressions that construct sequences: The result of this expression is a sequence of five integers: (10, 1, 2, 3, 4) 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 (10, (1, 2), (), (3, 4)) The result of this expression is a sequence containing all salary bonus (salary, bonus) Assuming that $price 10.50 10.50, 10.50 ($price, $price) A range expression to xs:integer? This example uses a range expression as one operand in constructing a sequence. It evaluates to the sequence 10, 1, 2, 3, 4 (10, 1 to 4) This example constructs a sequence of length one containing the single integer 10 10 to 10 The result of this example is a sequence of length zero. 15 to 10 This example uses the fn:reverse 15, 14, 13, 12, 11, 10 fn:reverse(10 to 15) FilterExpr ::= PrimaryExpr PredicateList PredicateList ::= Predicate [ Definition filter expression primary expression predicates 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. $products[price gt 100] List all the integers from 1 to 100 that are divisible by 5. (See 3.3.1 Constructing Sequences to (1 to 100)[. mod 5 eq 0] The result of the following expression is the integer 25: (21 to 29)[5] The following example returns the fifth through ninth items in the sequence bound to variable $orders $orders[fn:position() = (5 to 9)] The following example illustrates the use of a filter expression as a step path expression $book $book/(chapter | appendix)[fn:last()] The following example also illustrates the use of a filter expression as a step path expression tiger fn:doc("zoo.xml")/fn:id('tiger') UnionExpr ::= IntersectExceptExpr IntersectExceptExpr IntersectExceptExpr ::= InstanceofExpr InstanceofExpr XQuery provides the following operators for combining sequences of nodes: The union | The intersect The except All these operators eliminate duplicate nodes from their result sequences based on node identity. If ordering mode ordered document order implementation-dependent If an operand of union intersect except type error err:XPTY0004 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 $seq3 $seq1 $seq2 $seq3 Then: $seq1 union $seq2 $seq2 union $seq3 $seq1 intersect $seq2 $seq2 intersect $seq3 $seq1 except $seq2 $seq2 except $seq3 In addition to the sequence operators described here, [XQuery 1.0 and XPath 2.0 Functions and Operators (Second Edition)] XQuery provides arithmetic operators for addition, subtraction, multiplication, division, and modulus, in their usual binary and unary forms. AdditiveExpr ::= MultiplicativeExpr MultiplicativeExpr MultiplicativeExpr ::= UnionExpr UnionExpr UnaryExpr ::= ("-" | "+")* ValueExpr ValueExpr ::= ValidateExpr PathExpr ExtensionExpr A subtraction operator must be preceded by whitespace if it could otherwise be interpreted as part of the previous token. For example, a-b a - b a -b A.2.4 Whitespace Rules The first step in evaluating an arithmetic expression is to evaluate its operands. The order in which the operands are evaluated is implementation-dependent Each Atomization atomized operand 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 type error err:XPTY0004 If the atomized operand is of type xs:untypedAtomic xs:double dynamic error 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 dynamic error B.2 Operator Mapping operator functions [XQuery 1.0 and XPath 2.0 Functions and Operators (Second Edition)] If the types of the operands, after evaluation, are not a valid combination for the given operator, according to the rules in B.2 Operator Mapping type error err:XPTY0004 XQuery supports two division operators named div idiv numeric [XQuery 1.0 and XPath 2.0 Functions and Operators (Second Edition)] $arg1 idiv $arg2 ($arg1 div $arg2) cast as xs:integer? Here are some examples of arithmetic expressions: The first expression below returns the xs:decimal -1.5 xs:integer -1 -3 div 2 -3 idiv 2 Subtraction of two date values results in a value of type xs:dayTimeDuration $emp/hiredate - $emp/birthdate 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. Therefore, the following two examples have different meanings: -$bellcost + $whistlecost -($bellcost + $whistlecost) Note: Multiple consecutive unary arithmetic operators are permitted by XQuery for compatibility with [XPath 1.0] Comparison expressions allow two values to be compared. XQuery provides three kinds of comparison expressions, called value comparisons, general comparisons, and node comparisons. ComparisonExpr ::= RangeExpr ValueComp GeneralComp NodeComp RangeExpr ValueComp ::= "eq" | "ne" | "lt" | "le" | "gt" | "ge" GeneralComp ::= "=" | "!=" | "<" | "<=" | ">" | ">=" NodeComp ::= "is" | "<<" | ">>" The value comparison operators are eq ne lt le gt ge The first step in evaluating a value comparison is to evaluate its operands. The order in which the operands are evaluated is implementation-dependent Atomization atomized operand 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 type error err:XPTY0004 If the atomized operand is of type xs:untypedAtomic xs:string Note: 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 xs:integer xs:float xs:float xs:integer Next, if possible, the two operands are converted to their least common type by a combination of type promotion subtype substitution hatsize xs:integer shoesize xs:float 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 B.2 Operator Mapping operator functions [XQuery 1.0 and XPath 2.0 Functions and Operators (Second Edition)] Informally, if both atomized operands consist of exactly one atomic value, then the result of the comparison is true false If the types of the operands, after evaluation, are not a valid combination for the given operator, according to the rules in B.2 Operator Mapping type error err:XPTY0004 Here are some examples of value comparisons: The following comparison atomizes the node(s) that are returned by the expression $book/author xs:string xs:untypedAtomic type error err:XPTY0004 $book1/author eq "Kennedy" The following path expression weight weight //product[weight gt 100] 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: <a>5</a> eq <a>5</a> <a>5</a> eq <b>5</b> The following comparison is true if my:hatsize my:shoesize numeric my:hatsize(5) eq my:shoesize(5) The following comparison is true. The eq fn:QName("http://example.com/ns1", "this:color") eq fn:QName("http://example.com/ns1", "that:color") The general comparison operators are = != < <= > >= true false A Atomization The result of the comparison is true magnitude relationship false magnitude relationship cast Note: The purpose of these rules is to preserve compatibility with XPath 1.0, in which (for example) x < 17 x xs:untypedAtomic If both atomic values are instances of xs:untypedAtomic xs:string If exactly one of the atomic values is an instance of xs:untypedAtomic 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 xs:dayTimeDuration xs:dayTimeDuration If T is xs:yearMonthDuration xs:yearMonthDuration xs:yearMonthDuration In all other cases, V is cast to the primitive base type of T. Note: The special treatment of the duration types is required to avoid errors that may arise when comparing the primitive type xs:duration After performing the conversions described above, the atomic values are compared using one of the value comparison operators eq ne lt le gt ge = != < <= > >= magnitude relationship true When evaluating a general comparison in which either operand is a sequence of items, an implementation may return true magnitude relationship dynamic error Here are some examples of general comparisons: The following comparison is true if the typed value author $book1 xs:string xs:untypedAtomic $book1/author = "Kennedy" The following example contains three general comparisons. The value of the first two comparisons is true false (1, 2) = (2, 3) (2, 3) = (3, 4) (1, 2) = (3, 4) The following example contains two general comparisons, both of which are true = != (1, 2) = (2, 3) (1, 2) != (2, 3) Suppose that $a $b $c xs:untypedAtomic string values 1 2 2.0 ($a, $b) = ($c, 3.0) false $b $c ($a, $b) = ($c, 2.0) true $b 2.0 Node comparisons are used to compare two nodes, by their identity or by their document order The operands of a node comparison are evaluated in implementation-dependent 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 type error err:XPTY0004 A comparison with the is true false [XQuery 1.0 and XPath 2.0 Data Model (Second Edition)] A comparison with the << true document order false A comparison with the >> true document order 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: /books/book[isbn="1558604820"] is /books/book[call="QA76.9 C3845"] The following comparison is false because each constructed node has its own identity: <a>5</a> is <a>5</a> 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: /transactions/purchase[parcel="28-451"] << /transactions/sale[parcel="33-870"] A logical expression and-expression or-expression true false OrExpr ::= AndExpr AndExpr AndExpr ::= ComparisonExpr ComparisonExpr The first step in evaluating a logical expression is to find the effective boolean value 2.4.3 Effective Boolean Value 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: EBV 2 true EBV 2 false error in EBV 2 EBV 1 true true false error EBV 1 false false false either false error in EBV 1 error either false 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: EBV 2 true EBV 2 false error in EBV 2 EBV 1 true true true either true EBV 1 false true false error error in EBV 1 either true error error The order in which the operands of a logical expression are evaluated is implementation-dependent true false Here are some examples of logical expressions: The following expressions return true 1 eq 1 and 2 eq 2 1 eq 1 or 2 eq 3 The following expression may return either false dynamic error 1 eq 2 and 3 idiv 0 = 1 The following expression may return either true dynamic error 1 eq 1 or 3 idiv 0 = 1 The following expression must raise a dynamic error 1 eq 1 and 3 idiv 0 = 1 In addition to and- and or-expressions, XQuery provides a function named fn:not fn:not [XQuery 1.0 and XPath 2.0 Functions and Operators (Second Edition)] fn:not effective boolean value true false false true fn:not 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: direct constructors computed constructors Constructor ::= DirectConstructor ComputedConstructor DirectConstructor ::= DirElemConstructor DirCommentConstructor DirPIConstructor DirElemConstructor ::= "<" QName DirAttributeList DirElemContent QName S DirElemContent ::= DirectConstructor CDataSection CommonContent ElementContentChar ElementContentChar ::= Char CommonContent ::= PredefinedEntityRef CharRef EnclosedExpr CDataSection ::= "<![CDATA[" CDataSectionContents CDataSectionContents ::= ( Char DirAttributeList ::= ( S QName S S DirAttributeValue DirAttributeValue ::= ('"' ( EscapeQuot QuotAttrValueContent EscapeApos AposAttrValueContent QuotAttrValueContent ::= QuotAttrContentChar CommonContent AposAttrValueContent ::= AposAttrContentChar CommonContent QuotAttrContentChar ::= Char AposAttrContentChar ::= Char EscapeQuot ::= '""' EscapeApos ::= "''" EnclosedExpr ::= "{" Expr 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 element constructor Definition direct element constructor book <book isbn="isbn-0060229357"> <title>Harold and the Purple Crayon</title> <author> <first>Crockett</first> <last>Johnson</last> </author> </book> If the element name in a direct element constructor has a namespace prefix, the namespace prefix is resolved to a namespace URI using the statically known namespaces default element/type namespace namespace declaration attributes [XQuery 1.0 and XPath 2.0 Data Model (Second Edition)] expanded QName node-name 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 enclosed expressions <example> <p> Here is a query. </p> <eg> $b/title </eg> <p> Here is the result of the query. </p> <eg>{ $b/title }</eg> </example> The above query might generate the following result (whitespace has been added for readability to this result and other result examples in this document): <example> <p> Here is a query. </p> <eg> $b/title </eg> <p> Here is the result of the query. </p> <eg><title>Harold and the Purple Crayon</title></eg> </example> 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 " {{ { }} } character references { } { } static error err:XPST0003 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 namespace declaration attributes 3.7.1.2 Namespace Declaration Attributes If an attribute name has a namespace prefix, the prefix is resolved to a namespace URI using the statically known namespaces namespace declaration attributes [XQuery 1.0 and XPath 2.0 Data Model (Second Edition)] expanded QName node-name If the attributes in a direct element constructor do not have distinct expanded QNames node-name static error err:XQST0040 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 { { Each occurrence of two consecutive } } Each occurrence of EscapeQuot " Each occurrence of EscapeApos ' Attribute value normalization is then applied to normalize whitespace and expand character references predefined entity references [XML 1.0] [XML 1.1] implementation-defined Each enclosed expression is converted to a string as follows: Atomization 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 type annotation type-name xs:untypedAtomic typed-value string-value xs:untypedAtomic The parent If the attribute name is xml:id xml:id [XML ID] xs:ID xml:id MAY dynamic error err:XQDY0091 If the attribute name is xml:id is-id true is-id false is-idrefs false Example: <shoe size="7"/> The string value of the size 7 Example: <shoe size="{7}"/> The string value of the size 7 Example: <shoe size="{()}"/> The string value of the size Example: <chapter ref="[{1, 5 to 7, 9}]"/> The string value of the ref [1 5 6 7 9] Example: <shoe size="As big as {$hat/@size}"/> The string value of the size As big as $hat/@size The names of a constructed element and its attributes may be QNames namespace prefixes Prolog namespace declaration attributes static error err:XPST0081 [ Definition namespace declaration attribute default element/type namespace xmlns xmlns err:XQST0071 The value of the namespace declaration attribute (a DirAttributeValue DirAttributeValue EnclosedExpr err:XQST0022 3.7.1.1 Attributes err:XQST0046 xs:anyURI If the prefix of the attribute name is xmlns statically known namespaces in-scope namespaces [XML Names 1.1] in-scope namespaces statically known namespaces [XML Names 1.1] err:XQST0085 implementation-defined [XML Names] [XML Names 1.1] If the name of the namespace declaration attribute is xmlns default element/type namespace in-scope namespaces default element/type namespace in-scope namespaces It is a static error err:XQST0070 Bind the prefix xml http://www.w3.org/XML/1998/namespace Bind a prefix other than xml http://www.w3.org/XML/1998/namespace Bind the prefix xmlns Bind a prefix to the 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 default element/type namespace http://example.org/animals <cat xmlns = "http://example.org/animals"> <breed>Persian</breed> </cat> In this element constructor, namespace declaration attributes are used to bind the namespace prefixes metric english <box xmlns:metric = "http://example.org/metric/units" xmlns:english = "http://example.org/english/units"> <height> <metric:meters>3</metric:meters> </height> <width> <english:feet>6</english:feet> </width> <depth> <english:inches>18</english:inches> </depth> </box> The part of a direct element constructor between the start tag and the end tag is called the content ElementContentChar CdataSections predefined entity references Conceptually, the content of an element constructor is processed as follows: The content is evaluated to produce a sequence of nodes called the content sequence If the boundary-space policy static context strip boundary whitespace 3.7.1.4 Boundary Whitespace Predefined entity references character references 3.1.1 Literals 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 3.7.1 Direct Element Constructors 3.7.2 Other Direct Constructors The parent The base-uri xml:base base-uri base-uri 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. Note: 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 copied nodes Each copied node receives a new node identity. The parent children attributes parent If construction mode static context strip If the copied node is an element node, its type-name xs:untyped nilled is-id is-idrefs false If the copied node is an attribute node, its type-name xs:untypedAtomic is-idrefs false is-id true xml:id false The string-value typed-value string-value xs:untypedAtomic Note: Implementations that store only the typed value On the other hand, if construction mode static context preserve type-name nilled string-value typed-value is-id is-idrefs The in-scope-namespaces If copy-namespaces mode preserve copy-namespaces mode no-preserve If copy-namespaces mode inherit copy-namespaces mode no-inherit An enclosed expression in the content of an element constructor may cause one or more existing nodes to be copied. Type error [ err:XQTY0086 An element node is copied, and the typed value namespace-sensitive construction mode preserve copy-namespaces mode no-preserve An attribute node is copied but its parent element node is not copied, and the typed value namespace-sensitive construction mode preserve [ Definition namespace-sensitive dynamic type xs:QName xs:NOTATION xs:QName xs:NOTATION Note: The rationale for error [ err:XQTY0086 When an element or processing instruction node is copied, its base-uri xml:base base-uri base-uri 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 type error err:XQTY0024 The properties of the newly constructed element node are determined as follows: node-name expanded QName 3.7.1 Direct Element Constructors parent attributes 3.7.1.1 Attributes implementation-dependent parent node-name dynamic error err:XQDY0025 xml:space preserve default MAY err:XQDY0092 children parent base-uri If the constructed node has an attribute named xml:base base URI static context xml:base [XML Base] Otherwise, the value of the base URI static context in-scope-namespaces 3.7.1.2 Namespace Declaration Attributes 3.7.4 In-scope Namespaces of a Constructed Element The nilled false The string-value string-value The typed-value string-value xs:untypedAtomic If construction mode static context strip type-name xs:untyped preserve type-name xs:anyType The is-id is-idrefs false Example: <a>{1}</a> The constructed element node has one child, a text node containing the value " 1 Example: <a>{1, 2, 3}</a> The constructed element node has one child, a text node containing the value " 1 2 3 Example: <c>{1}{2}{3}</c> The constructed element node has one child, a text node containing the value " 123 Example: <b>{1, "2", "3"}</b> The constructed element node has one child, a text node containing the value " 1 2 3 Example: <fact>I saw 8 cats.</fact> The constructed element node has one child, a text node containing the value " I saw 8 cats. Example: <fact>I saw {5 + 3} cats.</fact> The constructed element node has one child, a text node containing the value " I saw 8 cats. Example: <fact>I saw <howmany>{5 + 3}</howmany> cats.</fact> The constructed element node has three children: a text node containing " I saw howmany cats. 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> <author> <book isbn="isbn-0060229357"> <title>Harold and the Purple Crayon</title> <author> <first>Crockett</first> <last>Johnson</last> </author> </book> [ Definition Boundary whitespace direct element constructor DirectConstructor EnclosedExpr character references   CdataSections The boundary-space policy static context strip preserve Example: <cat> <breed>{$b}</breed> <color>{$c}</color> </cat> The constructed cat breed color strip Example: <a> {"abc"} </a> If boundary-space policy is strip <a>abc</a> preserve <a> abc </a> Example: <a> z {"abc"}</a> Since the whitespace surrounding the z <a> z abc</a> Example: <a> {"abc"}</a> This example is equivalent to <a> abc</a> character reference Example: <a>{" "}</a> 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. Note: Element constructors treat attributes named xml:space xml:space XQuery allows an expression to generate a processing instruction node or a comment node. This can be accomplished by using a direct processing instruction constructor direct comment constructor DirPIConstructor ::= "<?" PITarget S DirPIContents DirPIContents ::= ( Char DirCommentConstructor ::= "<!--" DirCommentContents DirCommentContents ::= (( Char Char A direct processing instruction constructor creates a processing instruction node whose target PITarget content DirPIContents base-uri parent The PITarget DirPIContents ?> The following example illustrates a direct processing instruction constructor: <?format role="output" ?> A direct comment constructor creates a comment node whose content DirCommentContents parent The DirCommentContents The following example illustrates a direct comment constructor: <!-- Tags are ignored in the following section --> Note: A direct comment constructor is different from a comment comment ComputedConstructor ::= CompDocConstructor CompElemConstructor CompAttrConstructor CompTextConstructor CompCommentConstructor CompPIConstructor An alternative way to create nodes is by using a computed constructor element attribute document text processing-instruction 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. [ Definition name expression [ Definition content expression 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 3.7.1 Direct Element Constructors element book { attribute isbn {"isbn-0060229357" }, element title { "Harold and the Purple Crayon"}, element author { element first { "Crockett" }, element last {"Johnson" } } } CompElemConstructor ::= "element" ( QName Expr ContentExpr ContentExpr ::= Expr [ Definition computed element constructor If the keyword element statically known namespaces expanded QName node-name static error err:XPST0081 If the keyword element name expression Atomization name expression xs:QName xs:string xs:untypedAtomic type error err:XPTY0004 If the atomized value of the name expression xs:QName expanded QName node-name If the atomized value of the name expression xs:string xs:untypedAtomic expanded QName statically known namespaces default element/type namespace expanded QName node-name name expression dynamic error err:XQDY0074 A dynamic error err:XQDY0096 Its namespace prefix is xmlns Its namespace URI is http://www.w3.org/2000/xmlns/ Its namespace prefix is xml http://www.w3.org/XML/1998/namespace Its namespace prefix is other than xml http://www.w3.org/XML/1998/namespace The content expression direct element constructor 3.7.1.3 Content content sequence content expression 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 type error err:XQTY0024 The properties of the newly constructed element node are determined as follows: node-name expanded QName name expression parent attributes implementation-dependent parent node-name dynamic error err:XQDY0025 xml:space preserve default MAY err:XQDY0092 children parent base-uri If the constructed node has an attribute named xml:base base URI static context xml:base [XML Base] Otherwise, the value of the base URI static context in-scope-namespaces 3.7.4 In-scope Namespaces of a Constructed Element The nilled false The string-value The typed-value string-value xs:untypedAtomic If construction mode static context strip type-name xs:untyped preserve type-name xs:anyType The is-id is-idrefs false A computed element constructor might be used to make a modified copy of an existing element. For example, if the variable $e numeric $e $e element {fn:node-name($e)} {$e/@*, 2 * fn:data($e)} In this example, if $e let $e := <length units="inches">{5}</length> <length units="inches">10</length> Note: The static type fn:node-name($e) xs:QName? Static Typing Feature fn:node-name($e) fn:exactly-one(fn:node-name($e)) Static Typing Feature $e 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 dictionary entry <entry word="address"> <variant xml:lang="de">Adresse</variant> <variant xml:lang="it">indirizzo</variant> </entry> Suppose further that the variable $e <address>123 Roosevelt Ave. Flushing, NY 11368</address> Then the following expression generates a new element in which the name of $e $e element element {$dict/entry[@word=name($e)]/variant[@xml:lang="it"]} {$e/@*, $e/node()} The result of this expression is as follows: <indirizzo>123 Roosevelt Ave. Flushing, NY 11368</indirizzo> Note: As in the previous example, if the Static Typing Feature fn:exactly-one Additional examples of computed element constructors can be found in I.4 Recursive Transformations CompAttrConstructor ::= "attribute" ( QName Expr Expr A computed attribute constructor creates a new attribute node, with its own node identity. If the keyword attribute statically known namespaces expanded QName node-name static error err:XPST0081 If the keyword attribute name expression Atomization name expression atomization xs:QName xs:string xs:untypedAtomic type error err:XPTY0004 If the atomized value of the name expression xs:QName If the expanded QName implementation-dependent Note: 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 expanded QName node-name If the atomized value of the name expression xs:string xs:untypedAtomic expanded QName statically known namespaces expanded QName node-name name expression expanded QName dynamic error err:XQDY0074 A dynamic error err:XQDY0044 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 http://www.w3.org/XML/1998/namespace Its namespace prefix is other than xml http://www.w3.org/XML/1998/namespace The content expression Atomization content expression content expression 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 type annotation type-name xs:untypedAtomic typed-value string-value xs:untypedAtomic The parent If the attribute name is xml:id xml:id [XML ID] xs:ID xml:id MAY dynamic error err:XQDY0091 If the attribute name is xml:id is-id true is-id false is-idrefs false If the attribute name is xml:space preserve default MAY err:XQDY0092 Example: attribute size {4 + 3} The string value size 7 xs:untypedAtomic Example: attribute { if ($sex = "M") then "husband" else "wife" } { <a>Hello</a>, 1 to 3, <b>Goodbye</b> } The name of the constructed attribute is either husband wife string value Hello 1 2 3 Goodbye CompDocConstructor ::= "document" "{" Expr 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 document { <author-list> {fn:doc("bib.xml")/bib/book/author} </author-list> } The content expression direct element constructor 3.7.1.3 Content content sequence 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 type error err:XPTY0004 The properties of the newly constructed document node are determined as follows: base-uri base URI static context base-uri children parent The unparsed-entities document-uri The string-value The typed-value string-value xs:untypedAtomic No validation is performed on the constructed document node. The [XML 1.0] CompTextConstructor ::= "text" "{" Expr 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 content expression Atomization content expression 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 The parent Note: 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: text {"Hello"} CompPIConstructor ::= "processing-instruction" ( NCName Expr Expr A computed processing instruction constructor ( CompPIConstructor If the keyword processing-instruction target processing-instruction name expression Atomization name expression atomization xs:NCName xs:string xs:untypedAtomic type error err:XPTY0004 If the atomized value of the name expression xs:string xs:untypedAtomic xs:NCName xs:NCName dynamic error err:XQDY0041 The resulting NCName is then used as the target dynamic error XML err:XQDY0064 The content expression Atomization content expression content expression 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 " ?> dynamic error err:XQDY0026 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 The remaining properties of the new processing instruction node are determined as follows: The parent The base-uri The following example illustrates a computed processing instruction constructor: let $target := "audio-output", $content := "beep" return processing-instruction {$target} {$content} The processing instruction node constructed by this example might be serialized as follows: <?audio-output beep?> CompCommentConstructor ::= "comment" "{" Expr A computed comment constructor ( CompCommentConstructor content expression Atomization content expression 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 It is a dynamic error err:XQDY0072 content expression The parent The following example illustrates a computed comment constructor: let $homebase := "Houston" return comment {fn:concat($homebase, ", we have a problem.")} The comment node constructed by this example might be serialized as follows: <!--Houston, we have a problem.--> An element node constructed by a direct or computed element constructor has an in-scope namespaces namespace bindings 2.2.4 Serialization fn:name in-scope namespaces statically known namespaces A namespace binding is created for each namespace declared in the current element constructor by a namespace declaration attribute A namespace binding is created for each namespace that is declared in a namespace declaration attribute direct element constructor A namespace binding is always created to bind the prefix xml 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 implementation-dependent Note: Copy-namespaces mode The following query serves as an example: declare namespace p="http://example.com/ns/p"; declare namespace q="http://example.com/ns/q"; declare namespace f="http://example.com/ns/f";
<p:a q:b="{f:func(2)}" xmlns:r="http://example.com/ns/r"/> The in-scope namespaces p:a namespace bindings p = "http://example.com/ns/p" q = "http://example.com/ns/q" r = "http://example.com/ns/r" xml = "http://www.w3.org/XML/1998/namespace" The namespace bindings for p q r="http://example.com/ns/r" namespace declaration attribute No namespace binding corresponding to f="http://example.com/ns/f" f statically known namespaces Note that the following constructed element, if nested within a validate <p xsi:type="xs:integer">3</p> The constructed element will have namespace bindings for the prefixes xsi xml xs namespace declaration attribute <p xmlns:xs="http://www.w3.org/2001/XMLSchema" xsi:type="xs:integer">3</p> 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 return FLWORExpr ::= ( ForClause LetClause WhereClause OrderByClause ExprSingle ForClause ::= "for" "$" VarName TypeDeclaration PositionalVar ExprSingle VarName TypeDeclaration PositionalVar ExprSingle LetClause ::= "let" "$" VarName TypeDeclaration ExprSingle VarName TypeDeclaration ExprSingle TypeDeclaration ::= "as" SequenceType PositionalVar ::= "at" "$" VarName WhereClause ::= "where" ExprSingle OrderByClause ::= (("order" "by") | ("stable" "order" "by")) OrderSpecList OrderSpecList ::= OrderSpec OrderSpec OrderSpec ::= ExprSingle OrderModifier OrderModifier ::= ("ascending" | "descending")? ("empty" ("greatest" | "least"))? ("collation" URILiteral The for let tuple stream where order by return return where comma operator The following example of a FLWOR expression includes all of the possible clauses. The for $d $d let $e for let $d $e $d $e where order by return big-dept for $d in fn:doc("depts.xml")/depts/deptno let $e := fn:doc("emps.xml")/emps/emp[deptno = $d] where fn:count($e) >= 10 order by fn:avg($e/salary) descending return <big-dept> { $d, <headcount>{fn:count($e)}</headcount>, <avgsal>{fn:avg($e/salary)}</avgsal> } </big-dept> The clauses in a FLWOR expression are described in more detail below. The purpose of the for let The simplest example of a for Definition for binding sequence for ordering mode ordered implementation-dependent A for for ordering mode ordered implementation-dependent A let for let let for for let Although for let let let $s := (<one/>, <two/>, <three/>) return <out>{$s}</out> The variable $s (<one/>, <two/>, <three/>) for let $s return <out> <one/> <two/> <three/> </out> The next example is a similar query that contains a for let for $s in (<one/>, <two/>, <three/>) return <out>{$s}</out> In this example, the variable $s ordering mode ordered $s <one/> <two/> <three/> return <out> <one/> </out> <out> <two/> </out> <out> <three/> </out> The following example illustrates how binding tuples are generated by a for ordering mode ordered for $i in (1, 2), $j in (3, 4) The tuple stream generated by the above for ($i = 1, $j = 3) ($i = 1, $j = 4) ($i = 2, $j = 3) ($i = 2, $j = 4) If ordering mode unordered for implementation-dependent The scope of a variable bound in a for let for let for $x in $w, $a in f($x) let $y := g($a) for $z in p($x, $y) return q($x, $y, $z) The for let Each variable bound in a for let type declaration 2.5.3 SequenceType Syntax SequenceType matching type error err:XPTY0004 type error $salary let $salary as xs:decimal := "cat" return $salary * 2 Each variable bound in a for positional variable at xs:integer binding sequence err:XQST0089 Positional variables are illustrated by the following for for $car at $i in ("Ford", "Chevy"), $pet at $j in ("Cat", "Dog") If ordering mode ordered for ($i = 1, $car = "Ford", $j = 1, $pet = "Cat") ($i = 1, $car = "Ford", $j = 2, $pet = "Dog") ($i = 2, $car = "Chevy", $j = 1, $pet = "Cat") ($i = 2, $car = "Chevy", $j = 2, $pet = "Dog") If ordering mode unordered implementation-dependent for ordering mode implementation-dependent ordering mode unordered The optional where for let where where-expression effective boolean value true return effective boolean value false effective boolean value 2.4.3 Effective Boolean Value The following expression illustrates how a where positional variable fn:avg(for $x at $i in $inputvalues where $i mod 100 = 0 return $x) The return comma operator If no order by for let ordering mode order by return ordering mode order by order by ordering mode An order by orderspecs where collation xs:string xs:anyURI default collation base URI static context statically known collations err:XQST0076 The process of evaluating and comparing the orderspecs is based on the following rules: Atomization type error err:XPTY0004 If the value of an orderspec has the dynamic type xs:untypedAtomic xs:string Note: 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 subtype substitution type promotion gt gt type error err:XPTY0004 Example: The orderspec values include a value of type hatsize xs:integer shoesize xs:decimal xs:decimal Example: The orderspec values include a value of type xs:string xs:anyURI xs:string For the purpose of determining their relative position in the ordering sequence, the greater-than W V When the orderspec specifies empty least If V W W greater-than V If V NaN W NaN W greater-than V If a specific collation C V W xs:string xs:string subtype substitution type promotion If fn:compare(V, W, C) W greater-than V W greater-than V If none of the above rules apply, then: If W gt V W greater-than V W greater-than V When the orderspec specifies empty greatest If W V W greater-than V If W NaN V NaN W greater-than V If a specific collation C V W xs:string xs:string subtype substitution type promotion If fn:compare(V, W, C) W greater-than V W greater-than V If none of the above rules apply, then: If W gt V W greater-than V W greater-than V When the orderspec specifies neither empty least empty greatest default order for empty sequences static context empty least empty greatest 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 greater-than If V1 is greater-than descending If V2 is greater-than descending If neither V1 nor V2 is greater-than If stable If stable implementation-dependent Note: If two orderspecs return the special floating-point values positive and negative zero, neither of these values is greater-than +0.0 gt -0.0 -0.0 gt +0.0 false An order by for $e in $employees order by $e/salary descending return $e/name Note: Since the order by path expression $books/book[price < 100] for $b in $books/book[price < 100] order by $b/title return $b The following example illustrates an order by collation stable for $b in $books/book stable order by $b/title collation "http://www.example.org/collations/fr-ca", $b/price descending empty least return $b Note: Parentheses are helpful in return $j undefined let $i := 5, $j := 20 * $i return $i, $j Parentheses can be used to bring $j return let $i := 5, $j := 20 * $i return ($i, $j) 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 bib <bib> <book> <title>TCP/IP Illustrated</title> <author>Stevens</author> <publisher>Addison-Wesley</publisher> </book> <book> <title>Advanced Programming in the Unix Environment</title> <author>Stevens</author> <publisher>Addison-Wesley</publisher> </book> <book> <title>Data on the Web</title> <author>Abiteboul</author> <author>Buneman</author> <author>Suciu</author> </book> </bib> 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 default collation <authlist> { for $a in fn:distinct-values($bib/book/author) order by $a return <author> <name> {$a} </name> <books> { for $b in $bib/book[author = $a] order by $b/title return $b/title } </books> </author> } </authlist> The result of the above expression is as follows: <authlist> <author> <name>Abiteboul</name> <books> <title>Data on the Web</title> </books> </author> <author> <name>Buneman</name> <books> <title>Data on the Web</title> </books> </author> <author> <name>Stevens</name> <books> <title>Advanced Programming in the Unix Environment</title> <title>TCP/IP Illustrated</title> </books> </author> <author> <name>Suciu</name> <books> <title>Data on the Web</title> </books> </author> </authlist> OrderedExpr ::= "ordered" "{" Expr UnorderedExpr ::= "unordered" "{" Expr The purpose of ordered unordered ordering mode static context ordered unordered unordered Ordering mode path expressions / // axis step union intersect except fn:id fn:idref order by ordered union intersect except fn:id fn:idref document order implementation-dependent 3.8 FLWOR Expressions Note: In a region of a query where ordering mode is unordered fn:position fn:last fn:index-of fn:insert-before fn:remove fn:reverse fn:subsequence path expression numeric predicates (//a/b)[5] b document order implementation-dependent b Note: The fn:id fn:idref [XQuery 1.0 and XPath 2.0 Functions and Operators (Second Edition)] document order unordered The use of an unordered parts.xml suppliers.xml unordered document order parts.xml document order suppliers.xml suppliers.xml parts.xml unordered unordered { for $p in fn:doc("parts.xml")/parts/part[color = "Red"], $s in fn:doc("suppliers.xml")/suppliers/supplier where $p/suppno = $s/suppno return <ps> { $p/partno, $s/suppno } </ps> } In addition to ordered unordered fn:unordered fn:unordered fn:unordered unordered ordering mode XQuery supports a conditional expression based on the keywords if then else IfExpr ::= "if" "(" Expr ExprSingle ExprSingle The expression following the if test expression then else then-expression else-expression The first step in processing a conditional expression is to find the effective boolean value 2.4.3 Effective Boolean Value The value of a conditional expression is defined as follows: If the effective boolean value of the test expression is true false Conditional expressions have a special rule for propagating dynamic errors true false dynamic errors Here are some examples of conditional expressions: In this example, the test expression is a comparison expression: if ($widget1/unit-cost < $widget2/unit-cost) then $widget1 else $widget2 In this example, the test expression tests for the existence of an attribute named discounted if ($part/@discounted) then $part/wholesale else $part/retail Quantified expressions support existential and universal quantification. The value of a quantified expression is always true false QuantifiedExpr ::= ("some" | "every") "$" VarName TypeDeclaration ExprSingle VarName TypeDeclaration ExprSingle ExprSingle TypeDeclaration ::= "as" SequenceType A quantified expression quantifier some every satisfies binding sequence effective boolean value 2.4.3 Effective Boolean Value If the quantifier is some true effective boolean value true false false If the quantifier is every true effective boolean value true false 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 type declaration SequenceType matching type error err:XPTY0004 The order in which test expressions are evaluated for the various binding tuples is implementation-dependent some true effective boolean value true dynamic error every false effective boolean value false dynamic error Here are some examples of quantified expressions: This expression is true part discounted every $part in /parts/part satisfies $part/@discounted This expression is true employee some $emp in /emps/employee satisfies ($emp/bonus > 0.25 * $emp/salary) 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) (2, 3, 4) some true every false some $x in (1, 2, 3), $y in (2, 3, 4) satisfies $x + $y = 4 every $x in (1, 2, 3), $y in (2, 3, 4) satisfies $x + $y = 4 This quantified expression may either return true type error true type error some $x in (1, 2, "cat") satisfies $x * 2 = 4 This quantified expression may either return false type error false type error every $x in (1, 2, "cat") satisfies $x * 2 = 4 This quantified expression contains a type declaration Static Typing Feature type error static analysis phase true type error dynamic evaluation phase some $x as xs:integer in (1, 2, "cat") satisfies $x * 2 = 4 In addition to their use in function parameters and results, sequence types instance of typeswitch cast castable treat InstanceofExpr ::= TreatExpr SequenceType The boolean operator instance of true SequenceType SequenceType matching false 5 instance of xs:integer This example returns true 5 instance of xs:decimal This example returns true xs:integer xs:decimal <a>{5}</a> instance of xs:integer This example returns false (5, 6) instance of xs:integer+ This example returns true . instance of element() This example returns true false undefined dynamic error err:XPDY0002 TypeswitchExpr ::= "typeswitch" "(" Expr CaseClause VarName ExprSingle CaseClause ::= "case" ("$" VarName SequenceType ExprSingle The typeswitch dynamic type In a typeswitch typeswitch operand expression typeswitch case default Each case SequenceType return Definition effective case typeswitch case SequenceType case SequenceType matching typeswitch return SequenceType case typeswitch return default In a case default return case default case static type SequenceType case default case default The scope of a variable binding in a case default case default typeswitch A special rule applies to propagation of dynamic errors typeswitch typeswitch case effective case default effective case The following example shows how a typeswitch dynamic type typeswitch($customer/billing-address) case $a as element(*, USAddress) return $a/state case $a as element(*, CanadaAddress) return $a/province case $a as element(*, JapanAddress) return $a/prefecture default return "unknown" CastExpr ::= UnaryExpr SingleType SingleType ::= AtomicType Occasionally it is necessary to convert a value to a specific datatype. For this purpose, XQuery provides a cast cast input expression target type input type in-scope schema types err:XPST0051 xs:NOTATION xs:anyAtomicType err:XPST0080 ? default element/type namespace cast Atomization If the result of atomization is a sequence of more than one atomic value, a type error err:XPTY0004 If the result of atomization is an empty sequence: If ? cast If ? type error err:XPTY0004 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 [XQuery 1.0 and XPath 2.0 Functions and Operators (Second Edition)] in-scope schema definitions implementation-dependent cast Section 17.1 Casting from primitive types to primitive types FO schema types xs:string xs:decimal [XQuery 1.0 and XPath 2.0 Functions and Operators (Second Edition)] If the target type of a cast xs:QName xs:QName xs:NOTATION err:XPTY0004 Note: 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 statically known namespaces cast shoesize xs:integer shoesize xs:integer cast xs:string xs:untypedAtomic [XML Schema] dynamic error [XQuery 1.0 and XPath 2.0 Functions and Operators (Second Edition)] cast xs:string dynamic type 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 type error err:XPTY0004 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 dynamic error "2003-02-31" cast as xs:date dynamic error CastableExpr ::= CastExpr SingleType SingleType ::= AtomicType 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 in-scope schema types err:XPST0051 xs:NOTATION xs:anyAtomicType err:XPST0080 ? The expression E castable as T true E T cast false E castable castable predicate if ($x castable as hatsize) then $x cast as hatsize else if ($x castable as IQ) then $x cast as IQ else $x cast as xs:string Note: If the target type of a castable xs:QName xs:QName xs:NOTATION xs:string castable false For every atomic type in the in-scope schema types xs:NOTATION xs:anyAtomicType constructor function T T T? [ Definition constructor function T($arg) (($arg) cast as T?) The constructor functions for xs:QName xs:QName xs:NOTATION err:XPTY0004 cast 3.12.3 Cast The following examples illustrate the use of constructor functions: This example is equivalent to ("2000-01-01" cast as xs:date?) xs:date("2000-01-01") This example is equivalent to (($floatvalue * 0.2E-5) cast as xs:decimal?) xs:decimal($floatvalue * 0.2E-5) This example returns a xs:dayTimeDuration ("P21D" cast as xs:dayTimeDuration?) xs:dayTimeDuration("P21D") If usa:zipcode in-scope schema types ("12345" cast as usa:zipcode?) usa:zipcode("12345") Note: 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 default element/type namespace (See 4.13 Default Namespace Declaration default element/type namespace 17 cast as apple By using a constructor function, if the default function namespace (See 4.13 Default Namespace Declaration default function namespace apple(17) TreatExpr ::= CastableExpr SequenceType XQuery provides an expression called treat static type Like cast treat SequenceType cast treat dynamic type treat The semantics of expr1 treat as type1 During static analysis: The static type treat type1 type1 During expression evaluation: If expr1 type1 SequenceType matching treat expr1 dynamic error err:XPDY0050 expr1 treat Example: $myaddress treat as element(*, USAddress) The static type $myaddress element(*, Address) element(*, USAddress) $myaddress element(*, USAddress) SequenceType matching dynamic error err:XPDY0050 ValidateExpr ::= "validate" ValidationMode Expr ValidationMode ::= "lax" | "strict" A validate in-scope schema definitions [XML Schema] validate type error err:XQTY0030 validate operand node A validate type annotations A validate validation mode validation mode strict validate 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 dynamic error err:XQDY0061 The operand node is converted to an XML Information Set ( [XML Infoset] [XQuery 1.0 and XPath 2.0 Data Model (Second Edition)] type annotations Validity assessment is carried out on the root element information item of the resulting Infoset, using the in-scope schema definitions If validation mode strict in-scope element declarations [XML Schema] dynamic error err:XQDY0084 If validation mode lax [XML Schema] If validation mode lax xsi:type [XML Schema] validate 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 xs:ENTITIES There is no check that the document contains notations whose names match the values of nodes of type xs:NOTATION Note: Validity assessment is affected by the presence or absence of xsi:type The next step depends on validation mode validity If the validity valid validation mode validation mode lax validity notKnown XDM instance [XQuery 1.0 and XPath 2.0 Data Model (Second Edition)] validate Otherwise, a dynamic error err:XQDY0027 Note: The effect of these rules is as follows: If validation mode strict validation mode lax validation mode lax xsi:type xsi:type Note: During conversion of the PSVI into an XDM instance notKnown type annotation xs:anyType notKnown type annotation xs:untypedAtomic Section 3.3.1.1 Element and Attribute Node Type Names DM [ Definition extension expression implementation-defined ExtensionExpr ::= Pragma Expr Pragma ::= "(#" S QName S PragmaContents PragmaContents ::= ( Char An extension expression consists of one or more pragmas Definition pragma (# #) implementation-defined #) statically known namespaces err:XPST0081 Note: Since there is no default namespace for pragmas, a pragma QName must include a namespace prefix. Each implementation recognizes an implementation-defined 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 ExtensionExpr ExtensionExpr static error err:XQST0079 If an implementation recognizes the namespace of one or more pragmas in an ExtensionExpr ExtensionExpr implementation-defined It is a static error err:XQST0013 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 Static Typing Feature Note: 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: declare namespace exq = "http://example.org/XQueryImplementation"; (# exq:use-index #) { $bib/book/author[name='Berners-Lee'] } An implementation that recognizes the exq:use-index 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 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: declare namespace exq = "http://example.org/XQueryImplementation"; for $x in (# exq:distinct //city by @country #) { //city[not(@country = preceding::city/@country)] } return f:show-city($x) Here an implementation that recognizes the pragma will return the result of evaluating the proprietary syntax exq:distinct //city by @country //city[not(@country = preceding::city/@country)] static error Module ::= VersionDecl LibraryModule MainModule MainModule ::= Prolog QueryBody LibraryModule ::= ModuleDecl Prolog Prolog ::= (( DefaultNamespaceDecl Setter NamespaceDecl Import Separator VarDecl FunctionDecl OptionDecl Separator Setter ::= BoundarySpaceDecl DefaultCollationDecl BaseURIDecl ConstructionDecl OrderingModeDecl EmptyOrderDecl CopyNamespacesDecl Import ::= SchemaImport ModuleImport Separator ::= ";" QueryBody ::= Expr A query can be assembled from one or more fragments called modules Definition module Module static analysis phase 2.2.3 Expression Processing main module library module [ Definition main module Prolog Query Body Query Body [ Definition Query Body library module module declaration Prolog The XQuery syntax does not allow a module module declaration Query Body [ Definition Prolog module The first part of the Prolog consists of setters, imports, namespace declarations, and default namespace declarations. [ Definition Setters Definition target namespace 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. [ Definition Query Body 3 Expressions VersionDecl ::= "xquery" "version" StringLiteral StringLiteral Separator [ Definition module version declaration module module module static error err:XQST0031 module [ Definition encoding declaration encoding EncName [XML 1.0] err:XQST0087 UTF-8 UTF-16 US-ASCII The handling of an encoding declaration is implementation-dependent a priori If a version declaration is present, no Comment Comment implementation-dependent Note: 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: xquery version "1.0"; xquery version "1.0" encoding "utf-8"; ModuleDecl ::= "module" "namespace" NCName URILiteral Separator [ Definition module declaration module library module module URILiteral err:XQST0088 target namespace static error err:XQST0048 statically known namespaces The namespace prefix specified in a module declaration must not be xml xmlns err:XQST0070 schema import namespace declaration module import err:XQST0033 Any module module import static context dynamic context The following is an example of a module declaration: module namespace math = "http://example.org/math-functions"; BoundarySpaceDecl ::= "declare" "boundary-space" ("preserve" | "strip") [ Definition boundary-space declaration boundary-space policy static context boundary whitespace preserve strip 3.7.1.4 Boundary Whitespace The following example illustrates a boundary-space declaration: declare boundary-space preserve; If a Prolog contains more than one boundary-space declaration, a static error err:XQST0068 DefaultCollationDecl ::= "declare" "default" "collation" URILiteral [ Definition default collation declaration default collation static context gt fn:compare gt fn:compare gt If neither the implementation nor the Prolog specifies a default collation, the Unicode codepoint collation ( http://www.w3.org/2005/xpath-functions/collation/codepoint The following example illustrates a default collation declaration: declare default collation "http://example.org/languages/Icelandic"; If a default collation declaration specifies a collation by a relative URI, that relative URI is resolved to an absolute URI using the base URI static context statically known collations static error err:XQST0038 BaseURIDecl ::= "declare" "base-uri" URILiteral [ Definition base URI declaration base URI static context base URI module fn:doc The following is an example of a base URI declaration: declare base-uri "http://example.org"; If a Prolog contains more than one base URI declaration, a static error err:XQST0032 In the terminology of [RFC3986] base URI static context [RFC3986] ../data/ file:///C:/temp/queries/query.xq base URI static context file:///C:/temp/data/ It is not intrinsically an error if this process fails to establish an absolute base URI; however, the base URI static context undefined err:XPST0001 undefined err:XPST0001 undefined ConstructionDecl ::= "declare" "construction" ("strip" | "preserve") [ Definition construction declaration construction mode static context preserve xs:anyType strip xs:untyped xs:untyped xs:untypedAtomic The following example illustrates a construction declaration: declare construction strip; If a Prolog specifies more than one construction declaration, a static error err:XQST0067 OrderingModeDecl ::= "declare" "ordering" ("ordered" | "unordered") [ Definition ordering mode declaration ordering mode static context module Prolog Query Body ordered unordered Ordering mode path expressions / // axis step union intersect except order by ordered union intersect except document order implementation-dependent 3.8 FLWOR Expressions The following example illustrates an ordering mode declaration: declare ordering unordered; If a Prolog contains more than one ordering mode declaration, a static error err:XQST0065 EmptyOrderDecl ::= "declare" "default" "order" "empty" ("greatest" | "least") [ Definition empty order declaration default order for empty sequences static context, NaN order by order by empty greatest empty least The following example illustrates an empty order declaration: declare default order empty least; If a Prolog contains more than one empty order declaration, a static error err:XQST0069 Note: It is important to distinguish an empty order declaration ordering mode declaration empty order declaration order by order by ordering mode declaration order by CopyNamespacesDecl ::= "declare" "copy-namespaces" PreserveMode InheritMode PreserveMode ::= "preserve" | "no-preserve" InheritMode ::= "inherit" | "no-inherit" [ Definition copy-namespaces declaration copy-namespaces mode static context 3.7.1 Direct Element Constructors The following example illustrates a copy-namespaces declaration: declare copy-namespaces preserve, no-inherit; If a Prolog contains more than one copy-namespaces declaration, a static error err:XQST0055 SchemaImport ::= "import" "schema" SchemaPrefix URILiteral URILiteral URILiteral SchemaPrefix ::= ("namespace" NCName [ Definition schema import in-scope schema definitions For each user-defined atomic type in the schema, schema import also adds a corresponding constructor function target namespace default element/type namespace The namespace prefix specified in a schema import must not be xml xmlns err:XQST0070 module import namespace declaration module declaration err:XQST0033 The first URILiteral at 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 [ err:XQST0057 It is a static error err:XQST0058 Prolog static error err:XQST0059 static error err:XQST0035 http://www.w3.org/2001/XMLSchema xs in-scope schema types. It is a static error err:XQST0012 [XML Schema] The following example imports a schema, specifying both its target namespace and its location, and binding the prefix soap import schema namespace soap="http://www.w3.org/2003/05/soap-envelope" at "http://www.w3.org/2003/05/soap-envelope/"; The following example imports a schema by specifying only its target namespace, and makes it the default element/type namespace: import schema default element namespace "http://example.org/abc"; 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: import schema default element namespace "" at "http://example.org/xyz.xsd"; 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. import schema default element namespace ""; ModuleImport ::= "import" "module" ("namespace" NCName URILiteral URILiteral URILiteral [ Definition module import library modules function signatures in-scope variables module target namespace implementation-defined The namespace prefix specified in a module import must not be xml xmlns err:XQST0070 schema import namespace declaration module declaration err:XQST0033 The first URILiteral err:XQST0088 at implementation-defined It is a static error err:XQST0047 Prolog static error err:XQST0059 static error expanded QName expanded QName err:XQST0034 static error expanded QName eq expanded QName err:XQST0049 Each module static context module import in-scope schema definitions statically known namespaces A module may import its own target namespace (this is interpreted as importing an implementation-defined It is a static error err:XQST0036 in-scope schema definitions An in-scope schema type 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 in-scope element declaration EN schema-element(EN) schema-element(EN) An in-scope attribute declaration AN schema-attribute(AN) schema-attribute(AN) To illustrate the above rules, suppose that a certain schema defines a type named triangle geometry function signature math:area($t as geometry:triangle) as xs:double both geometry:triangle area [ Definition 1 directly depends 2 1 1 depends 2 static error err:XQST0093 1 1 i 1 directly depends 1 The following example illustrates a module import: import module namespace math = "http://example.org/math-functions"; NamespaceDecl ::= "declare" "namespace" NCName URILiteral [ Definition namespace declaration statically known namespaces namespace declaration attribute direct element constructor 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 statically known namespaces local The following query illustrates a namespace declaration: declare namespace foo = "http://example.org"; <foo:bar> Lentils </foo:bar> 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 xmlns err:XQST0070 http://www.w3.org/XML/1998/namespace http://www.w3.org/2000/xmlns/ err:XQST0070 module import schema import module declaration err:XQST0033 It is a static error err:XPST0081 statically known namespaces XQuery has several predeclared namespace prefixes that are present in the statically known namespaces namespace declarations Prolog namespace declaration attributes xml xml err:XQST0070 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 4.15 Function Declaration Additional predeclared namespace prefixes may be added to the statically known namespaces 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: declare namespace xx = "http://example.org";
let $i := <foo:bar xmlns:foo = "http://example.org"> <foo:bing> Lentils </foo:bing> </foo:bar> return $i/xx:bing Although the namespace prefixes xx foo "http://example.org" xx:bing foo:bing <foo:bing xmlns:foo = "http://example.org"> Lentils </foo:bing> DefaultNamespaceDecl ::= "declare" "default" ("element" | "function") "namespace" URILiteral Default namespace declarations Prolog A default element/type namespace declaration default element/type namespace static context Prolog err:XQST0066 URILiteral default element/type namespace declare default element namespace "http://example.org/names"; A default element/type namespace declaration may be overridden by a namespace declaration attribute direct element constructor 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 C.1 Static Context Components A default function namespace declaration default function namespace static context Prolog err:XQST0066 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 C.1 Static Context Components The following example illustrates the declaration of a default function namespace: declare default function namespace "http://example.org/math-functions"; The effect of declaring a default function namespace is that all functions in the default function namespace, including implicitly-declared constructor functions constructor functions err:XPST0017 Note: Only constructor functions Unprefixed attribute names and variable names are in no namespace. VarDecl ::= "declare" "variable" "$" QName TypeDeclaration ExprSingle VarName ::= QName TypeDeclaration ::= "as" SequenceType A variable declaration static type in-scope variables variable values expanded QName eq in-scope variables static error err:XQST0049 If a variable declaration includes a type, that type is added to the static context static context SequenceType matching type error err:XPTY0004 [ Definition initializing expression static context Prolog dynamic context C.2 Dynamic Context Components [ Definition $x depends $y f2 $y f2 $x $z f3 $x depends $z f3 $z f3 depends $y f2 [ Definition f1 depends $y f2 $y f2 f1 $z f3 f1 depends $z f3 $z f3 depends $y f2 If a variable depends static error err:XQST0054 If the variable declaration includes the keyword external SequenceType matching 2.2.5 Consistency Constraints static type item()* external err:XPDY0002 All variable names declared in a library module target namespace err:XQST0048 in-scope variables 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 variable declaration Prolog variable binding 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 $x static context 7 $x dynamic context declare variable $x as xs:integer := 7; The following declaration specifies a value but not a type. The static type $x xs:decimal declare variable $x := 7.5; The following declaration specifies a type but not a value. The keyword external $x dynamic context xs:integer declare variable $x as xs:integer external; 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 $x item()* dynamic context $x declare variable $x external; The following declaration, which might appear in a library module, declares a variable whose name includes a namespace prefix: declare variable $math:pi as xs:double := 3.14159E0; In addition to the built-in functions described in [XQuery 1.0 and XPath 2.0 Functions and Operators (Second Edition)] 2.5 Types function signatures module FunctionDecl ::= "declare" "function" QName ParamList SequenceType EnclosedExpr ParamList ::= Param Param Param ::= "$" QName TypeDeclaration TypeDeclaration ::= "as" SequenceType A function declaration specifies whether a function is user-defined external Definition user-defined function function body static context Prolog [ Definition External functions [XQuery 1.0 and XPath 2.0 Functions and Operators (Second Edition)] external 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 implementation-defined [XQuery 1.0 and XPath 2.0 Data Model (Second Edition)] 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 [ err:XQST0060 default function namespace library module target namespace err:XQST0048 static error err:XQST0045 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 static error err:XQST0034 expanded QName eq expanded QName function signatures 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 http://www.w3.org/2005/xquery-local-functions If a function parameter is declared using a name but no type, its default type is item()* item()* The parameters of a function declaration are considered to be variables whose scope is the function body. It is an static error err:XQST0039 sequence type The following example illustrates the declaration and use of a local function that accepts a sequence of employee dept Using a function, prepare a summary of employees that are located in Denver. declare function local:summary($emps as element(employee)*) as element(dept)* { for $d in fn:distinct-values($emps/deptno) let $e := $emps[deptno = $d] return <dept> <deptno>{$d}</deptno> <headcount> {fn:count($e)} </headcount> <payroll> {fn:sum($e/salary)} </payroll> </dept> };
local:summary(fn:doc("acme_corp.xml")//employee[location = "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 3.1.5 Function Calls 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 empty max Find the maximum depth of the document named partlist.xml declare function local:depth($e as node()) as xs:integer { (: A node with no children has depth 1 :) (: Otherwise, add 1 to max depth of children :) if (fn:empty($e/*)) then 1 else fn:max(for $c in $e/* return local:depth($c)) + 1 };
local:depth(fn:doc("partlist.xml")) Since a constructor function in-scope schema types static error err:XQST0034 expanded QName [ Definition option declaration OptionDecl ::= "declare" "option" QName StringLiteral 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 statically known namespaces err:XPST0081 Note: There is no default namespace for options. Each implementation recognizes an implementation-defined 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 implementation-defined 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 implementation-defined The following examples illustrate several possible uses for option declarations: This option declaration might be used to set a serialization parameter: declare namespace exq = "http://example.org/XQueryImplementation"; declare option exq:output "encoding = iso-8859-1"; This option declaration might be used to specify how comments in source documents returned by the fn:doc() declare option exq:strip-comments "true"; This option declaration might be used to associate a namespace used in function names with a Java class: declare namespace math = "http://example.org/MathLibrary"; declare option exq:java-class "math = java.lang.Math"; 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 [RFC 2119] Definition MUST Definition MAY Definition SHOULD An XQuery processor that claims to conform to this specification MUST 5.1 Minimal Conformance MAY 5.2 Optional Features Minimal Conformance to this specification MUST Support for everything specified in this document except those features specified in 5.2 Optional Features MUST 5.2 Optional Features A definition of every item specified to be implementation-defined implementation-defined D Implementation-Defined Items Note: Implementations are not required to define items specified to be implementation-dependent Support for [XQuery 1.0 and XPath 2.0 Data Model (Second Edition)] 5.3 Data Model Conformance Support for all functions defined in [XQuery 1.0 and XPath 2.0 Functions and Operators (Second Edition)] [ Definition Schema Import Feature schema import If an XQuery implementation does not support the Schema Import Feature, it MUST err:XQST0009 Note: If an implementation does not support the Schema Import Feature, the in-scope schema types implementation-defined C.1 Static Context Components [ Definition Schema Validation Feature validate 3.13 Validate Expressions If an XQuery implementation does not support the Schema Validation Feature, it MUST err:XQST0075 validate [ Definition Static Typing Feature [XQuery 1.0 and XPath 2.0 Formal Semantics (Second Edition)] type errors static analysis phase If an implementation does not support the Static Typing Feature MAY implementation dependent Note: An implementation that does not support the Static Typing Feature MUST In some cases, the static typing rules defined in [XQuery 1.0 and XPath 2.0 Formal Semantics (Second Edition)] fn:root A conforming implementation that implements the Static Typing Feature MAY static typing extensions Definition static typing extension implementation-defined [XQuery 1.0 and XPath 2.0 Formal Semantics (Second Edition)] Section 6.1.1 Static Typing Extensions FS [ Definition optional axes ancestor ancestor-or-self following following-sibling preceding preceding-sibling [ Definition Full Axis Feature MUST optional axes Conforming XQuery implementations that do not support the Full Axis Feature MAY implementation-defined MUST static error err:XPST0010 Note: XQuery does not recognize the namespace [ Definition Module Feature Module Import library modules A conforming implementation that does not support the Module Feature MUST static error err:XQST0016 module declaration module import module declaration library module library module Note: In the absence of the Module Feature, each query consists of a single main module [ Definition Serialization Feature MUST 2.2.4 Serialization A conforming XQuery implementation that supports the Serialization Feature MUST C.3 Serialization Parameters implementation-defined If an error is raised during the serialization process as specified in [XSLT 2.0 and XQuery 1.0 Serialization (Second Edition)] MUST Note: 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 data model [XQuery 1.0 and XPath 2.0 Data Model (Second Edition)] Support for normative construction from an infoset. MAY Section 3.2 Construction from an Infoset DM XDM instance Support for normative construction from a PSVI. MAY Section 3.3 Construction from a PSVI DM XDM instance Support for XML 1.0 and XML 1.1. [XQuery 1.0 and XPath 2.0 Data Model (Second Edition)] [XML 1.0] [XML 1.1] implementation-defined 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 xs:ID Note: For suggestions on processing XML 1.1 documents, see [XML 1.1 and Schema 1.0] Ranges of data values. implementation-defined For the xs:decimal totalDigits For the types xs:date xs:time xs:dateTime xs:gYear xs:gYearMonth For the xs:duration type For the xs:yearMonthDuration For the xs:dayTimeDuration For the types xs:string xs:hexBinary xs:base64Binary xs:QName xs:anyURI xs:NOTATION 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 Any syntactic extensions to XQuery are implementation-defined implementation-defined The grammar of XQuery uses the same simple Extended Backus-Naur Form (EBNF) notation as [XML 1.0] 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.1.2 Extra-grammatical Constraints A 'ws:' prefix explains the whitespace rules for the production, the details of which are explained in A.2.4 Whitespace Rules A 'gn:' prefix means a 'Grammar Note', and is meant as a clarification for parsing rules, and is explained in A.1.3 Grammar Notes The terminal symbols for this grammar include the quoted strings used in the production rules below, and the terminal symbols defined in section A.2.1 Terminal Symbols The EBNF notation is described in more detail in A.1.1 Notation 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. Module ::= VersionDecl LibraryModule MainModule VersionDecl ::= "xquery" "version" StringLiteral StringLiteral Separator MainModule ::= Prolog QueryBody LibraryModule ::= ModuleDecl Prolog ModuleDecl ::= "module" "namespace" NCName URILiteral Separator Prolog ::= (( DefaultNamespaceDecl Setter NamespaceDecl Import Separator VarDecl FunctionDecl OptionDecl Separator Setter ::= BoundarySpaceDecl DefaultCollationDecl BaseURIDecl ConstructionDecl OrderingModeDecl EmptyOrderDecl CopyNamespacesDecl Import ::= SchemaImport ModuleImport Separator ::= ";" NamespaceDecl ::= "declare" "namespace" NCName URILiteral BoundarySpaceDecl ::= "declare" "boundary-space" ("preserve" | "strip") DefaultNamespaceDecl ::= "declare" "default" ("element" | "function") "namespace" URILiteral OptionDecl ::= "declare" "option" QName StringLiteral OrderingModeDecl ::= "declare" "ordering" ("ordered" | "unordered") EmptyOrderDecl ::= "declare" "default" "order" "empty" ("greatest" | "least") CopyNamespacesDecl ::= "declare" "copy-namespaces" PreserveMode InheritMode PreserveMode ::= "preserve" | "no-preserve" InheritMode ::= "inherit" | "no-inherit" DefaultCollationDecl ::= "declare" "default" "collation" URILiteral BaseURIDecl ::= "declare" "base-uri" URILiteral SchemaImport ::= "import" "schema" SchemaPrefix URILiteral URILiteral URILiteral SchemaPrefix ::= ("namespace" NCName ModuleImport ::= "import" "module" ("namespace" NCName URILiteral URILiteral URILiteral VarDecl ::= "declare" "variable" "$" QName TypeDeclaration ExprSingle ConstructionDecl ::= "declare" "construction" ("strip" | "preserve") FunctionDecl ::= "declare" "function" QName ParamList SequenceType EnclosedExpr ParamList ::= Param Param Param ::= "$" QName TypeDeclaration EnclosedExpr ::= "{" Expr QueryBody ::= Expr Expr ::= ExprSingle ExprSingle ExprSingle ::= FLWORExpr QuantifiedExpr TypeswitchExpr IfExpr OrExpr FLWORExpr ::= ( ForClause LetClause WhereClause OrderByClause ExprSingle ForClause ::= "for" "$" VarName TypeDeclaration PositionalVar ExprSingle VarName TypeDeclaration PositionalVar ExprSingle PositionalVar ::= "at" "$" VarName LetClause ::= "let" "$" VarName TypeDeclaration ExprSingle VarName TypeDeclaration ExprSingle WhereClause ::= "where" ExprSingle OrderByClause ::= (("order" "by") | ("stable" "order" "by")) OrderSpecList OrderSpecList ::= OrderSpec OrderSpec OrderSpec ::= ExprSingle OrderModifier OrderModifier ::= ("ascending" | "descending")? ("empty" ("greatest" | "least"))? ("collation" URILiteral QuantifiedExpr ::= ("some" | "every") "$" VarName TypeDeclaration ExprSingle VarName TypeDeclaration ExprSingle ExprSingle TypeswitchExpr ::= "typeswitch" "(" Expr CaseClause VarName ExprSingle CaseClause ::= "case" ("$" VarName SequenceType ExprSingle IfExpr ::= "if" "(" Expr ExprSingle ExprSingle OrExpr ::= AndExpr AndExpr AndExpr ::= ComparisonExpr ComparisonExpr ComparisonExpr ::= RangeExpr ValueComp GeneralComp NodeComp RangeExpr RangeExpr ::= AdditiveExpr AdditiveExpr AdditiveExpr ::= MultiplicativeExpr MultiplicativeExpr MultiplicativeExpr ::= UnionExpr UnionExpr UnionExpr ::= IntersectExceptExpr IntersectExceptExpr IntersectExceptExpr ::= InstanceofExpr InstanceofExpr InstanceofExpr ::= TreatExpr SequenceType TreatExpr ::= CastableExpr SequenceType CastableExpr ::= CastExpr SingleType CastExpr ::= UnaryExpr SingleType UnaryExpr ::= ("-" | "+")* ValueExpr ValueExpr ::= ValidateExpr PathExpr ExtensionExpr GeneralComp ::= "=" | "!=" | "<" | "<=" | ">" | ">=" ValueComp ::= "eq" | "ne" | "lt" | "le" | "gt" | "ge" NodeComp ::= "is" | "<<" | ">>" ValidateExpr ::= "validate" ValidationMode Expr ValidationMode ::= "lax" | "strict" ExtensionExpr ::= Pragma Expr Pragma ::= "(#" S QName S PragmaContents /* ws: explicit PragmaContents ::= ( Char PathExpr ::= ("/" RelativePathExpr RelativePathExpr RelativePathExpr /* xgs: leading-lone-slash RelativePathExpr ::= StepExpr StepExpr StepExpr ::= FilterExpr AxisStep AxisStep ::= ( ReverseStep ForwardStep PredicateList ForwardStep ::= ( ForwardAxis NodeTest AbbrevForwardStep ForwardAxis ::= ("child" "::") AbbrevForwardStep ::= "@"? NodeTest ReverseStep ::= ( ReverseAxis NodeTest AbbrevReverseStep ReverseAxis ::= ("parent" "::") AbbrevReverseStep ::= ".." NodeTest ::= KindTest NameTest NameTest ::= QName Wildcard Wildcard ::= "*" NCName NCName /* ws: explicit FilterExpr ::= PrimaryExpr PredicateList PredicateList ::= Predicate Predicate ::= "[" Expr PrimaryExpr ::= Literal VarRef ParenthesizedExpr ContextItemExpr FunctionCall OrderedExpr UnorderedExpr Constructor Literal ::= NumericLiteral StringLiteral NumericLiteral ::= IntegerLiteral DecimalLiteral DoubleLiteral VarRef ::= "$" VarName VarName ::= QName ParenthesizedExpr ::= "(" Expr ContextItemExpr ::= "." OrderedExpr ::= "ordered" "{" Expr UnorderedExpr ::= "unordered" "{" Expr FunctionCall ::= QName ExprSingle ExprSingle /* xgs: reserved-function-names /* gn: parens Constructor ::= DirectConstructor ComputedConstructor DirectConstructor ::= DirElemConstructor DirCommentConstructor DirPIConstructor DirElemConstructor ::= "<" QName DirAttributeList DirElemContent QName S /* ws: explicit DirAttributeList ::= ( S QName S S DirAttributeValue /* ws: explicit DirAttributeValue ::= ('"' ( EscapeQuot QuotAttrValueContent EscapeApos AposAttrValueContent /* ws: explicit QuotAttrValueContent ::= QuotAttrContentChar CommonContent AposAttrValueContent ::= AposAttrContentChar CommonContent DirElemContent ::= DirectConstructor CDataSection CommonContent ElementContentChar CommonContent ::= PredefinedEntityRef CharRef EnclosedExpr DirCommentConstructor ::= "<!--" DirCommentContents /* ws: explicit DirCommentContents ::= (( Char Char /* ws: explicit DirPIConstructor ::= "<?" PITarget S DirPIContents /* ws: explicit DirPIContents ::= ( Char /* ws: explicit CDataSection ::= "<![CDATA[" CDataSectionContents /* ws: explicit CDataSectionContents ::= ( Char /* ws: explicit ComputedConstructor ::= CompDocConstructor CompElemConstructor CompAttrConstructor CompTextConstructor CompCommentConstructor CompPIConstructor CompDocConstructor ::= "document" "{" Expr CompElemConstructor ::= "element" ( QName Expr ContentExpr ContentExpr ::= Expr CompAttrConstructor ::= "attribute" ( QName Expr Expr CompTextConstructor ::= "text" "{" Expr CompCommentConstructor ::= "comment" "{" Expr CompPIConstructor ::= "processing-instruction" ( NCName Expr Expr SingleType ::= AtomicType TypeDeclaration ::= "as" SequenceType SequenceType ::= ("empty-sequence" "(" ")") ItemType OccurrenceIndicator OccurrenceIndicator ::= "?" | "*" | "+" /* xgs: occurrence-indicators ItemType ::= KindTest AtomicType AtomicType ::= QName KindTest ::= DocumentTest ElementTest AttributeTest SchemaElementTest SchemaAttributeTest PITest CommentTest TextTest AnyKindTest AnyKindTest ::= "node" "(" ")" DocumentTest ::= "document-node" "(" ( ElementTest SchemaElementTest TextTest ::= "text" "(" ")" CommentTest ::= "comment" "(" ")" PITest ::= "processing-instruction" "(" ( NCName StringLiteral AttributeTest ::= "attribute" "(" ( AttribNameOrWildcard TypeName AttribNameOrWildcard ::= AttributeName SchemaAttributeTest ::= "schema-attribute" "(" AttributeDeclaration AttributeDeclaration ::= AttributeName ElementTest ::= "element" "(" ( ElementNameOrWildcard TypeName ElementNameOrWildcard ::= ElementName SchemaElementTest ::= "schema-element" "(" ElementDeclaration ElementDeclaration ::= ElementName AttributeName ::= QName ElementName ::= QName TypeName ::= QName URILiteral ::= StringLiteral The following definitions will be helpful in defining precisely this exposition. [ Definition symbol symbol ::= expression ] [ Definition terminal [a-zA-Z] matches any Char [abc] matches any Char [^abc] matches any Char "string" matches the sequence of characters that appear inside the double quotes. 'string' matches the sequence of characters that appear inside the single quotes. [http://www.w3.org/TR/REC-example/#NT-Example] 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) A A? matches A A A B matches A B A B | C D (A B) | (C D) A | B matches A B A - B matches any string that matches A B A+ matches one or more occurrences of A A+ | B+ (A+) | (B+) A* matches zero or more occurrences of A A* | B* (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: /* xgc: <id> */ Constraint: leading-lone-slash 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 RelativePathExpr * union NameTest , and the < DirectConstructor / * 5 / * / Therefore to reduce the need for lookahead, if the token immediately following a slash can form the start of a RelativePathExpr PathExpr A single slash may be used as the left-hand argument of an operator by parenthesizing it: (/) * 5 5 * / Constraint: xml-version An implementation's choice to support the [XML 1.0] [XML Names] [XML 1.1] [XML Names 1.1] A.2.4.1 Default Whitespace Handling prefix : localname Constraint: reserved-function-names Unprefixed function names spelled the same way as language keywords could make the language harder to recognize. For instance, if(foo) FunctionCall IfExpr A.3 Reserved Function Names 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)". Constraint: occurrence-indicators As written, the grammar in A XQuery Grammar SequenceType ItemType OccurrenceIndicator 4 treat as item() + - 5 (4 treat as item()+) - 5 (4 treat as item()) + -5 SequenceType 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 OccurrenceIndicator 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: /* gn: <id> */ Note: Look-ahead is required to distinguish FunctionCall Pragma Comment address (: this may be empty :) for (: whom the bell :) $tolls in 3 return $tolls Comments are allowed everywhere that ignorable whitespace Comment A.2.4.1 Default Whitespace Handling Note that comments are not allowed in direct constructor content, though they are allowed in nested EnclosedExprs A comment can contain nested comments, as long as all "(:" and ":)" patterns are balanced, no matter where they occur within the outer comment. Note: 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 :) "this is just a string :)" (: "this is just a string :)" :) "this is another string (:" (: "this is another string (:" :) for (: set up loop :) $i in $x return $i 5 instance (: strange place for a comment :) of xs:integer <eg (: an example:)>{$i//title}</eg> <eg> (: an example:) </eg> 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 A.2.1 Terminal Symbols It is implementation-defined [XML 1.0] [XML Names] [XML 1.1] [XML Names 1.1] [XML 1.1] SHOULD [XML 1.0] [XML Names] 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 A.3 Reserved Function Names IntegerLiteral ::= Digits DecimalLiteral ::= ("." Digits Digits /* ws: explicit DoubleLiteral ::= (("." Digits Digits Digits /* ws: explicit StringLiteral ::= ('"' ( PredefinedEntityRef CharRef EscapeQuot PredefinedEntityRef CharRef EscapeApos /* ws: explicit PredefinedEntityRef ::= "&" ("lt" | "gt" | "amp" | "quot" | "apos") ";" /* ws: explicit EscapeQuot ::= '""' EscapeApos ::= "''" ElementContentChar ::= Char QuotAttrContentChar ::= Char AposAttrContentChar ::= Char Comment ::= "(:" ( CommentContents Comment /* ws: explicit /* gn: comments PITarget ::= [http://www.w3.org/TR/REC-xml#NT-PITarget] XML /* xgs: xml-version CharRef ::= [http://www.w3.org/TR/REC-xml#NT-CharRef] XML /* xgs: xml-version QName ::= [http://www.w3.org/TR/REC-xml-names/#NT-QName] Names /* xgs: xml-version NCName ::= [http://www.w3.org/TR/REC-xml-names/#NT-NCName] Names /* xgs: xml-version S ::= [http://www.w3.org/TR/REC-xml#NT-S] XML /* xgs: xml-version Char ::= [http://www.w3.org/TR/REC-xml#NT-Char] XML /* xgs: xml-version The following symbols are used only in the definition of terminal symbols; they are not terminal symbols in the grammar of A.1 EBNF Digits ::= [0-9]+ CommentContents ::= ( Char XQuery 1.0 expressions consist of terminal symbols symbol separators Terminal symbols that are not used exclusively in /* ws: explicit */ [ Definition delimiting terminal symbols S StringLiteral [ Definition non-delimiting terminal symbols IntegerLiteral NCName DecimalLiteral DoubleLiteral QName [ Definition Whitespace Comments symbol separators /* ws: explicit */ /* xgs: xml-version */ It is customary to separate consecutive terminal symbols by whitespace Comments symbol separator 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 [XML 1.0] [XML 1.1] For [XML 1.0] the two-character sequence #xD #xA any #xD character that is not immediately followed by #xA. For [XML 1.1] 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 VersionDecl [ Definition whitespace [http://www.w3.org/TR/REC-xml/#NT-S] [ Definition Ignorable whitespace whitespace terminals ws:explicit A.2.4.2 Explicit Whitespace Handling terminals Comments foo- foo foo -foo foo - foo foo(: This is a comment :)- foo foo - foo foo-foo 10div 3 10 div3 10div3 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 whitespace characters A.2.4.1 Default Whitespace Handling Comments 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 A.1 EBNF # Operator Associativity 1 , (comma) left-to-right 2 := (assignment) right-to-left 3 for some, every typeswitch if left-to-right 4 or left-to-right 5 and left-to-right 6 eq, ne, lt, le, gt, ge =, !=, <, <=, >, >= is <<, >> left-to-right 7 to left-to-right 8 +, - left-to-right 9 *, div, idiv, mod left-to-right 10 union, | left-to-right 11 intersect, except left-to-right 12 instance of left-to-right 13 treat left-to-right 14 castable left-to-right 15 cast left-to-right 16 -(unary), +(unary) right-to-left 17 ?, *(OccurrenceIndicator), +(OccurrenceIndicator) left-to-right 18 /, // left-to-right 19 [ ] left-to-right Note: 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. [ Definition Type promotion 3.1.5 Function Calls , order by 3.8.3 Order By and Return Clauses B.2 Operator Mapping Numeric type promotion: A value of type xs:float xs:float xs:double xs:double A value of type xs:decimal xs:decimal xs:float xs:double URI type promotion: A value of type xs:anyURI xs:anyURI xs:string xs:string Note: Since xs:anyURI xs:string default collation xs:anyURI default collation xs:anyURI Note that type promotion subtype substitution A function that expects a parameter $p xs:float xs:decimal type promotion $p instance of xs:decimal false A function that expects a parameter $p xs:decimal xs:integer subtype substitution $p instance of xs:integer true The operator mapping tables in this section list the combinations of types for which the various operators of XQuery are defined. [ Definition operator function [XQuery 1.0 and XPath 2.0 Functions and Operators (Second Edition)] [XQuery 1.0 and XPath 2.0 Functions and Operators (Second Edition)] The and or If an operator in the operator mapping tables expects an operand of type ET AT AT ET type promotion subtype substitution gt xs:date xs:boolean gt xs:date xs:boolean [ Definition numeric xs:integer xs:decimal xs:float xs:double numeric + 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 AT AT type promotion subtype substitution (xs:integer, xs:decimal, xs:float, xs:double) subtype substitution type promotion hatsize xs:integer shoesize xs:float + hatsize shoesize xs:float + hatsize xs:integer [ Definition Gregorian xs:gYearMonth xs:gYear xs:gMonthDay xs:gDay xs:gMonth xs:gDay xs:gDay Binary Operators 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()* Unary Operators 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 static context Default initial value: Can be overwritten or augmented by implementation: implementation-defined implementation-defined Can be overwritten or augmented by a query: Scope: module Prolog Consistency Rules: 2.2.5 Consistency Constraints Static Context Components 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 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 strip Ordering mode ordered overwriteable overwriteable by prolog or expression lexical Value must be ordered unordered Default order for empty sequences implementation-defined overwriteable overwriteable by prolog module Value must be greatest least Boundary-space policy strip overwriteable overwriteable by prolog module Value must be preserve strip Copy-namespaces mode inherit, preserve overwriteable overwriteable by prolog module Value consists of inherit no-inherit preserve no-preserve Base URI See rules in 4.5 Base URI Declaration 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 dynamic context Default initial value: Can be overwritten or augmented by implementation: implementation-defined implementation-defined Can be overwritten or augmented by a query: Scope: Consistency Rules: 2.2.5 Consistency Constraints Dynamic Context Components 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 undefined 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 undefined 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 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 XDM instance method = "xml" [XSLT 2.0 and XQuery 1.0 Serialization (Second Edition)] Serialization Parameters 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 implementation-defined The version of Unicode that is used to construct expressions. The statically-known collations The implicit timezone The circumstances in which warnings The method by which errors are reported to the external processing environment. Whether the implementation is based on the rules of [XML 1.0] [XML Names] [XML 1.1] [XML Names 1.1] [XML 1.0] implementation-defined Any components of the static context dynamic context Which of the optional axes Full-Axis Feature The default handling of empty sequences returned by an ordering key (sortspec) in an order by empty least empty greatest The names and semantics of any extension expressions pragmas The names and semantics of any option declarations 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 module import Module Feature Any static typing extensions Static Typing Feature The means by which serialization is invoked, if the Serialization Feature The default values for the byte-order-mark encoding media-type normalization-form omit-xml-declaration standalone version Serialization Feature 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 5.3 Data Model Conformance Syntactic extensions to XQuery, including both their syntax and semantics, as discussed in 5.4 Syntax Extensions Note: Additional implementation-defined [XQuery 1.0 and XPath 2.0 Data Model (Second Edition)] [XQuery 1.0 and XPath 2.0 Functions and Operators (Second Edition)] S. Bradner. Key Words for use in RFCs to Indicate Requirement Levels. http://www.ietf.org/rfc/rfc2119.txt T. Berners-Lee, R. Fielding, and L. Masinter. Uniform Resource Identifiers (URI): Generic Syntax http://www.ietf.org/rfc/rfc3986.txt M. Duerst and M. Suignard. Internationalized Resource Identifiers (IRIs) http://www.ietf.org/rfc/rfc3987.txt ISO (International Organization for Standardization). ISO/IEC 10646:2003. Information technology—Universal Multiple-Octet Coded Character Set (UCS) http://www.iso.org The Unicode Consortium. The Unicode Standard http://www.unicode.org/standard/versions/ implementation-defined World Wide Web Consortium. Extensible Markup Language (XML) 1.0. http://www.w3.org/TR/REC-xml/ implementation-defined World Wide Web Consortium. Extensible Markup Language (XML) 1.1. http://www.w3.org/TR/xml11/ World Wide Web Consortium. XML Base. http://www.w3.org/TR/xmlbase/ World Wide Web Consortium. Namespaces in XML. http://www.w3.org/TR/REC-xml-names/ World Wide Web Consortium. Namespaces in XML 1.1. http://www.w3.org/TR/xml-names11/ World Wide Web Consortium. xml:id Version 1.0. http://www.w3.org/TR/xml-id/ World Wide Web Consortium. XML Schema, Parts 0, 1, and 2 (Second Edition) http://www.w3.org/TR/xmlschema-0/ http://www.w3.org/TR/xmlschema-1/ http://www.w3.org/TR/xmlschema-2/ World Wide Web Consortium. XQuery 1.0 and XPath 2.0 Data Model (XDM) (Second Edition) http://www.w3.org/TR/xpath-datamodel/ World Wide Web Consortium. XQuery 1.0 and XPath 2.0 Formal Semantics (Second Edition) http://www.w3.org/TR/xquery-semantics/ World Wide Web Consortium. XQuery 1.0 and XPath 2.0 Functions and Operators (Second Edition) http://www.w3.org/TR/xpath-functions/ World Wide Web Consortium. XSLT 2.0 and XQuery 1.0 Serialization (Second Edition) http://www.w3.org/TR/xslt-xquery-serialization/ World Wide Web Consortium. XML Query 1.0 Requirements http://www.w3.org/TR/xquery-requirements/ World Wide Web Consortium. XML Path Language (XPath) Version 2.0 (Second Edition) http://www.w3.org/TR/xpath20/ World Wide Web Consortium. XQueryX, Version 1.0 (Second Edition) http://www.w3.org/TR/xqueryx/ World Wide Web Consortium. XSL Transformations (XSLT) 2.0 (Second Edition) http://www.w3.org/TR/xslt20/ World Wide Web Consortium. Document Object Model (DOM) Level 3 Core Specification. http://www.w3.org/TR/DOM-Level-3-Core/ World Wide Web Consortium. XML Information Set. http://www.w3.org/TR/xml-infoset/ World Wide Web Consortium. XML Path Language (XPath) Version 1.0 http://www.w3.org/TR/xpath/ World Wide Web Consortium. XML Pointer Language (XPointer). http://www.w3.org/TR/WD-xptr World Wide Web Consortium. XML Query Use Cases http://www.w3.org/TR/xquery-use-cases/ World Wide Web Consortium. Processing XML 1.0 Documents with XML Schema 1.0 Processors http://www.w3.org/TR/xml11schema10/ Internet Engineering Task Force (IETF). Uniform Resource Locators (URL) http://www.ietf.org/rfc/rfc1738.txt Rick Cattell et al. The Object Database Standard: ODMG-93, Release 1.2 Don Chamberlin, Jonathan Robie, and Daniela Florescu. Quilt: an XML Query Language for Heterogeneous Data Sources Lecture Notes in Computer Science http://www.almaden.ibm.com/cs/people/chamberlin/quilt_lncs.pdf http://www.almaden.ibm.com/cs/people/chamberlin/quilt.html Alin Deutsch, Mary Fernandez, Daniela Florescu, Alon Levy, and Dan Suciu. A Query Language for XML International Organization for Standardization (ISO). Information Technology-Database Language SQL J. Robie, J. Lapp, D. Schach. XML Query Language (XQL) http://www.w3.org/TandS/QL/QL98/pp/xql.html World Wide Web Consortium. Character Model for the World Wide Web. http://www.w3.org/TR/charmod/ World Wide Web Consortium. XSL Transformations (XSLT) 1.0. http://www.w3.org/TR/xslt Queries from the XQuery 1.0 Use Cases, presented in a single file. See http://www.w3.org/TR/xquery-use-cases/xquery-use-case-queries.txt Queries from this document, presented in a single file. See http://www.w3.org/TR/xquery-use-cases/xquery-wd-queries.txt It is a static error static context It is a dynamic error dynamic context It is a static error A.1 EBNF It is a type error static analysis phase static type dynamic evaluation phase dynamic type 2.5.4 SequenceType Matching During the analysis phase, it is a static error static type () data(()) empty-sequence() (Not currently used.) (Not currently used.) It is a static error static context ElementTest AttributeTest An implementation that does not support the Schema Import Feature must raise a static error An implementation must raise a static error It is a static error [XML Schema] It is a static error (Not currently used.) (Not currently used.) An implementation that does not support the Module Feature raises a static error module declaration module import It is a static error function signature static context It is a type error It is a type error It is a type error (Not currently used.) It is a static error namespace declaration attribute URILiteral (Not currently used.) It is a type error It is a dynamic error It is a dynamic error ?> In a validate expression, it is a dynamic error valid strict valid notKnown lax (Not currently used.) (Not currently used.) It is a type error validate It is a static error A static error base URI declaration It is a static error It is a static error module same eq It is a static error It is a static error in-scope schema definitions An in-scope schema type 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 in-scope element declaration EN schema-element(EN) schema-element(EN) An in-scope attribute declaration AN schema-attribute(AN) schema-attribute(AN) (Not currently used.) It is a static error default collation declaration statically known collations It is a static error It is a static error It is a dynamic error xs:NCName (Not currently used.) (Not currently used.) It is a dynamic error 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 http://www.w3.org/XML/1998/namespace Its namespace prefix is other than xml http://www.w3.org/XML/1998/namespace It is a static error 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 MAY static error URILiteral xs:anyURI It is a static error It is a static error It is a static error module eq It is a dynamic error dynamic type treat sequence type treat / // / // treat as document-node() It is a static error AtomicType SequenceType in-scope schema types (Not currently used.) (Not currently used.) It is a static error depends It is a static error copy-namespaces declaration (Not currently used.) It is a static error It is a static error It is a static error It is a static error It is a dynamic error (Not currently used.) (Not currently used.) It is a dynamic error A static error ordering mode declaration A static error A static error construction declaration A static error boundary-space declaration A static error empty order declaration A static error xml xmlns The prefix xml http://www.w3.org/XML/1998/namespace A prefix other than xml http://www.w3.org/XML/1998/namespace The prefix xmlns A prefix other than xmlns http://www.w3.org/2000/xmlns/ A static error It is a dynamic error (Not currently used.) It is a dynamic error expanded QName statically known namespaces An implementation that does not support the Validation Feature must raise a static error validate It is a static error collation order by statically known collations (Not currently used.) (Not currently used.) It is a static error pragma It is a static error cast castable xs:NOTATION xs:anyAtomicType It is a static error a query statically known namespaces (Not currently used.) (Not currently used.) It is a dynamic error validate in-scope element declarations strict It is a static error [XML Names 1.1] It is a type error namespace-sensitive construction mode preserve copy-namespaces mode no-preserve It is a static error EncName [XML 1.0] It is a static error module import module declaration It is a static error It is a static error character reference An implementation MAY dynamic error xml:id [XML ID] xml:id An implementation MAY dynamic error xml:space preserve default It is a static error 1 1 i 1 directly depends 1 It is a dynamic error Its namespace prefix is xmlns Its namespace URI is http://www.w3.org/2000/xmlns/ Its namespace prefix is xml http://www.w3.org/XML/1998/namespace Its namespace prefix is other than xml http://www.w3.org/XML/1998/namespace application/xquery This 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 http://www.w3.org/TR/xquery/ application/xquery This document was prepared by members of the W3C XML Query Working Group. Please send comments to [email protected], a public mailing list with archives at http://lists.w3.org/Archives/Public/public-qt-comments 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 ෝ None known. This media type registration is for XQuery queries as described by the XQuery 1.0 specification, which is located at http://www.w3.org/TR/xquery/ The public XQuery Web page 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 .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 encoding declaration version declaration xquery version "1.0" encoding "utf-8"; An XQuery file may have the string xquery version "V.V" "V.V" "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 [RFC3987] file: [XQuery 1.0 and XPath 2.0 Functions and Operators (Second Edition)] fn:doc() fn:doc-available() 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 A conforming XQuery implementation that supports the Full Axis Feature MUST optional axes In the operator mapping tables, the term Gregorian xs:gYearMonth xs:gYear xs:gMonthDay xs:gDay xs:gMonth A Prolog module Lexically, a QName During evaluation of an expression, it is sometimes necessary to determine whether a value with a known dynamic type sequence type SequenceType matching Within this specification, the term URI [RFC3986] [RFC3987] IRI The term XDM instance value nodes atomic values data model XPath 1.0 compatibility mode. This component must be set by all host languages that include XPath 2.0 as a subset, indicating whether rules for compatibility with XPath 1.0 are in effect. XQuery sets the value of this component to false An atomic value atomic type [XML Schema] Atomization fn:data [XQuery 1.0 and XPath 2.0 Functions and Operators (Second Edition)] Available collections. fn:collection Available documents. data model fn:doc An axis step axis node test type annotation Base URI. fn:resolve-uri A base URI declaration base URI static context base URI module The value of the expression associated with a variable in a for binding sequence Boundary whitespace direct element constructor DirectConstructor EnclosedExpr character references   CdataSections A boundary-space declaration boundary-space policy static context boundary whitespace Boundary-space policy. boundary whitespace direct element constructors 3.7.1.4 Boundary Whitespace The built-in functions [XQuery 1.0 and XPath 2.0 Functions and Operators (Second Edition)] A character reference [Unicode] A collation [XQuery 1.0 and XPath 2.0 Functions and Operators (Second Edition)] One way to construct a sequence is by using the comma operator A computed element constructor A construction declaration construction mode static context Construction mode. preserve xs:anyType strip xs:untyped xs:untyped xs:untypedAtomic The constructor function T($arg) (($arg) cast as T?) The final part of a computed constructor is an expression enclosed in braces, called the content expression The context item Context item static type. static type When the context item is a node, it can also be referred to as the context node The context position The context size A copy-namespaces declaration copy-namespaces mode static context Copy-namespaces mode. 3.7.1 Direct Element Constructors preserve no-preserve inherit no-inherit Current dateTime. implementation-dependent a query fn:current-dateTime a query XQuery operates on the abstract, logical structure of an XML document, rather than its surface syntax. This logical structure, known as the data model [XQuery 1.0 and XPath 2.0 Data Model (Second Edition)] For a given node in an XDM instance data model schema type annotation Default collation. statically known collations xs:string xs:anyURI A default collation declaration default collation static context Default collection. fn:collection Default element/type namespace. Default function namespace. Default order for empty sequences. NaN order by 3.8.3 Order By and Return Clauses The delimiting terminal symbols S StringLiteral A direct element constructor Informally, document order The dynamic context A dynamic error The dynamic evaluation phase A dynamic type static type xs:integer* xs:integer The effective boolean value fn:boolean [XQuery 1.0 and XPath 2.0 Functions and Operators (Second Edition)] The effective case typeswitch case SequenceType case SequenceType matching An empty order declaration default order for empty sequences static context, NaN order by A sequence containing zero items is called an empty sequence If present, a version declaration may optionally include an encoding declaration encoding EncName [XML 1.0] err:XQST0087 UTF-8 UTF-16 US-ASCII In addition to its identifying QName, a dynamic error may also carry a descriptive string and one or more additional values called error values An expanded QName The expression context An extension expression implementation-defined External functions A filter expression primary expression predicates The first three components of the dynamic context focus A function f1 depends $y f2 $y f2 f1 $z f3 f1 depends $z f3 $z f3 depends $y f2 Function implementations function signatures For a user-defined function built-in function external function implementation-dependent Function signatures. expanded QName Ignorable whitespace whitespace terminals ws:explicit A.2.4.2 Explicit Whitespace Handling Implementation-dependent Implementation-defined Implicit timezone. implementation-defined xs:dayTimeDuration [XML Schema] In-scope attribute declarations. expanded QName implementation-dependent If the Schema Import Feature In-scope element declarations. expanded QName implementation-dependent If the Schema Import Feature The in-scope namespaces namespace bindings In-scope schema definitions. In-scope schema types. expanded QName named type implementation-dependent anonymous type 2.5.1 Predefined Schema Types If the Schema Import Feature In-scope variables. expanded QName static type If a variable declaration includes an expression, the expression is called an initializing expression An item atomic value node An alternative form of a node test called a kind test type annotation A module that does not contain a Query Body library module module declaration Prolog A literal A main module Prolog Query Body MAY A module Module static analysis phase 2.2.3 Expression Processing main module library module A module declaration module library module module URILiteral A module M 1 directly depends 2 1 1 depends 2 A conforming XQuery implementation that supports the Module Feature Module Import library modules A module import library modules function signatures in-scope variables module MUST When an expression is used to specify the name of a constructed node, that expression is called the name expression A node test that consists only of a QName or a Wildcard is called a name test A namespace declaration statically known namespaces A namespace declaration attribute default element/type namespace A value is namespace-sensitive dynamic type xs:QName xs:NOTATION xs:QName xs:NOTATION A node node kinds [XQuery 1.0 and XPath 2.0 Data Model (Second Edition)] A node test step The non-delimiting terminal symbols IntegerLiteral NCName DecimalLiteral DoubleLiteral QName When referring to a type, the term numeric xs:integer xs:decimal xs:float xs:double A predicate whose predicate expression returns a numeric type is called a numeric predicate For each operator and valid combination of operand types, the operator mapping tables specify a result type and an operator function An option declaration The following axes are designated as optional axes ancestor ancestor-or-self following following-sibling preceding preceding-sibling Ordering mode. ordered unordered path expressions union intersect except order by An ordering mode declaration ordering mode static context A path expression steps / // / // A pragma (# #) implementation-defined A predefined entity reference A predicate predicate expression Primary expressions constructors, Every axis has a principal node kind A query modules The Query Body The node ordering that is the reverse of document order is called reverse document order A schema import in-scope schema definitions For each user-defined atomic type in the schema, schema import also adds a corresponding constructor function The Schema Import Feature schema import A schema type [XML Schema] [XML Schema] The Schema Validation Feature validate 3.13 Validate Expressions A sequence items A sequence type SequenceType sequence type Serialization XDM instance A conforming XQuery implementation that supports the Serialization Feature MUST 2.2.4 Serialization Setters SHOULD A sequence containing exactly one item is called a singleton Document order is stable query implementation-dependent The static analysis phase static context static analysis phase The static context A static error static error The static type A static typing extension implementation-defined [XQuery 1.0 and XPath 2.0 Formal Semantics (Second Edition)] The Static Typing Feature [XQuery 1.0 and XPath 2.0 Formal Semantics (Second Edition)] type errors static analysis phase Statically known collections. fn:collection fn:collection Statically known documents. fn:doc static type fn:doc Statically known collations. implementation-defined queries and Statically known default collection type. fn:collection Statically known namespaces. A step path expression predicates axis step filter expression The string value fn:string Substitution groups [XML Schema] head element The use of a value whose dynamic type subtype substitution Each rule in the grammar defines one symbol symbol ::= expression Whitespace Comments symbol separators /* ws: explicit */ /* xgs: xml-version */ Each imported schema or module is identified by its target namespace A terminal Each element node and attribute node in an XDM instance type annotation [XQuery 1.0 and XPath 2.0 Data Model (Second Edition)] type-name schema type string value typed value A type error type error static type type error dynamic type Under certain circumstances, an atomic value can be promoted from one type to another. Type promotion 3.1.5 Function Calls , order by 3.8.3 Order By and Return Clauses B.2 Operator Mapping The typed value fn:data In certain situations a value is said to be undefined For a user-defined function function body In the data model value sequence A variable $x depends $y f2 $y f2 $x $z f3 $x depends $z f3 $z f3 depends $y f2 A variable reference Variable values expanded QNames in-scope variables static context dynamic type Any module version declaration module module In addition to static errors dynamic errors type errors warnings static analysis phase dynamic evaluation phase implementation-defined A whitespace [http://www.w3.org/TR/REC-xml/#NT-S] xs:anyAtomicType xs:anySimpleType xs:decimal xs:string xs:anyAtomicType xs:dayTimeDuration xs:duration xs:dayTimeDuration xs:untyped type annotation skip xs:untypedAtomic xs:yearMonthDuration xs:duration xs:yearMonthDuration 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 part part partno description A document named suppliers.xml supplier supplier suppno suppname A document named catalog.xml item partno suppno price 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. <descriptive-catalog> { for $i in fn:doc("catalog.xml")/items/item, $p in fn:doc("parts.xml")/parts/part[partno = $i/partno], $s in fn:doc("suppliers.xml")/suppliers /supplier[suppno = $i/suppno] order by $p/description, $s/suppname return <item> { $p/description, $s/suppname, $i/price } </item> } </descriptive-catalog> The previous query returns information only about parts that have suppliers and suppliers that have parts. An outer join left outer join 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. for $s in fn:doc("suppliers.xml")/suppliers/supplier order by $s/suppname return <supplier> { $s/suppname, for $i in fn:doc("catalog.xml")/items/item [suppno = $s/suppno], $p in fn:doc("parts.xml")/parts/part [partno = $i/pno] order by $p/description return $p/description } </supplier> The previous query preserves information about suppliers that supply no parts. Another type of join, called a full outer join supplier part part <master-list> { for $s in fn:doc("suppliers.xml")/suppliers/supplier order by $s/suppname return <supplier> { $s/suppname, for $i in fn:doc("catalog.xml")/items/item [suppno = $s/suppno], $p in fn:doc("parts.xml")/parts/part [partno = $i/partno] order by $p/description return <part> { $p/description, $i/price } </part> } </supplier> , (: parts that have no supplier :) <orphan-parts> { for $p in fn:doc("parts.xml")/parts/part where fn:empty(fn:doc("catalog.xml")/items/item [partno = $p/partno] ) order by $p/description return $p/description } </orphan-parts> } </master-list> The previous query uses an element constructor to enclose its output inside a master-list supplier orphan-parts Many queries involve forming data into groups and applying some aggregation function such as fn:count fn:avg This query finds the part number and average price for parts that have at least 3 suppliers. for $pn in fn:distinct-values( fn:doc("catalog.xml")/items/item/partno) let $i := fn:doc("catalog.xml")/items/item[partno = $pn] where fn:count($i) >= 3 order by $pn return <well-supplied-item> <partno> {$pn} </partno> <avgprice> {fn:avg($i/price)} </avgprice> </well-supplied-item> The fn:distinct-values fn:distinct-values Note that $pn $i fn:count($i) fn:avg($i/price) 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 state job income income state job for $s in fn:distinct-values( fn:doc("census.xml")/census/person/state), $j in fn:distinct-values( fn:doc("census.xml")/census/person/job) let $p := fn:doc("census.xml")/census/person [state = $s and job = $j] order by $s, $j return if (fn:exists($p)) then <group> <state> {$s} </state> <job> {$j} </job> <avgincome> {fn:avg($p/income)} </avgincome> </group> else () The if-then-else if-then-else <group> <state>Nebraska</state> <job>Deep Sea Fisherman</job> <avgincome/> </group> XQuery uses the << >> procedure incision instrument action anesthesia The following query returns all the action incision let $proc := /report/procedure[1] for $i in $proc//action where $i >> ($proc//incision)[1] and $i << ($proc//incision)[2] return $i 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 incision instrument >> $i >> ($proc//incision)[1] instrument incision 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 false declare function local:precedes($a as node(), $b as node()) as boolean { $a << $b and fn:empty($a//node() intersect $b) }; Similarly, a local:follows declare function local:follows($a as node(), $b as node()) as boolean { $a >> $b and fn:empty($b//node() intersect $a) }; Using the local:precedes instrument instrument incision let $proc := /report/procedure[1] for $i in $proc//instrument where local:precedes(($proc//incision)[1], $i) and local:precedes($i, ($proc//incision)[2]) return $i The following query reports incisions for which no prior anesthesia was recorded in the surgical report. Since an anesthesia incision << local:precedes for $proc in /report/procedure where some $i in $proc//incision satisfies fn:empty($proc//anesthesia[. << $i]) return $proc 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 h2 h2 h1 let $intro := //h2[text()="Introduction"], $next-h := //(h1|h2)[. >> $intro][1] return <div> { $intro, if (fn:empty($next-h)) then //node()[. >> $intro] else //node()[. >> $intro and . << $next-h] } </div> Note that the above query makes explicit the hierarchy that was implicit in the original document. In this example, we assume that the h2 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 title section section title title declare function local:sections-and-titles($n as node()) as node()? { if (fn:local-name($n) = "section") then element { fn:local-name($n) } { for $c in $n/* return local:sections-and-titles($c) } else if (fn:local-name($n) = "title") then $n else ( ) }; The "skeleton" of a given document, containing only its sections and titles, can then be obtained by invoking the local:sections-and-titles local:sections-and-titles(fn:doc("cookbook.xml")) As another example of a recursive transformation, suppose that we wish to scan over a document, transforming every attribute named color color size size $e declare function local:swizzle($n as node()) as node() { typeswitch($n) case $a as attribute(color) return element color { fn:string($a) } case $es as element(size) return attribute size { fn:string($es) } case $e as element() return element { fn:local-name($e) } { for $c in ($e/@* except $e/@color, (: attr -> attr :) $e/size, (: elem -> attr :) $e/@color, (: attr -> elem :) $e/node() except $e/size ) (: elem -> elem :) return local:swizzle($c) } case $d as document-node() return document { for $c in $d/* return local:swizzle($c) } default return $n }; The transformation can be applied to a whole document by invoking the local:swizzle local:swizzle(fn:doc("plans.xml")) 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 <order> <date>2003-10-15</date> <product>Dress Shirt</product> <size>M</size> <color>Blue</color> <supplier>Fashion Trends</supplier> <quantity>50</quantity> </order> From this data set, a user might wish to find all the distinct combinations of product size color order option for $p in fn:distinct-values(/orders/order/product), $s in fn:distinct-values(/orders/order/size), $c in fn:distinct-values(/orders/order/color) order by $p, $s, $c return if (fn:exists(/orders/order[product eq $p and size eq $s and color eq $c])) then <option> <product>{$p}</product> <size>{$s}</size> <color>{$c}</color> </option> else () 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 Errata for XQuery 1.0: An XML Query Language XQuery 1.0 Recommendation Erratum Bugzilla Category Description XQ.E1 4151 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. XQ.E2 3637 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. XQ.E3 4868 editorial For valid syntax, adds parentheses to the expansion for leading "/" and leading "//" in a path expression. XQ.E4 4446 substantive Adds more details to the rules defining permissible expression rewrites for optimization and other purposes. XQ.E5 4873 substantive Clarifies the conditions under which a castable expression may raise an error. XQ.E6 4321 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. XQ.E7 4353 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. XQ.E8 4418 substantive Deletes error code XQST0073, because it is redundant to error code XQST0093. XQ.E9 4443 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. XQ.E10 5035 editorial Clarifies that the default initial static type of the context item is undefined. XQ.E11 5207 editorial Clarifies behavior of node constructors when base-URI in static context is undefined. XQ.E12 5351 6559 substantive Specifies that an error results if the PITarget specified in a SequenceType of form processing-instruction(PITarget) is not a syntactically valid NCName. XQ.E13 5083 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. XQ.E14 5224 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. XQ.E15 5261 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. XQ.E16 5471 editorial Deletes unnecessary reference to RFC2396 from Normative References. This item is never referenced in the normative text. XQ.E17 5290 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. XQ.E18 5223 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. XQ.E19 4463 substantive Specifies rules that prevent the redefinition of certain predefined namespace prefixes. XQ.E20 5984 editorial Corrects a list of examples of primitive atomic types. XQ.E21 5347 substantive Allows (and encourages) the use of XML 1.0 editions newer than the Third Edition. XQ.E22 6027 substantive Specifies conformance criteria for syntax extensions. XQ.E23 6287 editorial Defines the meaning of "undefined" for Data Model properties. XQ.E24 5727 substantive Clarifications on parsing leading / in XPath expressions. XQ.E25 6557 editorial Adds a missing word to an error description. XQ.E26 5876 substantive Corrects the description of precedence with respect to parentheses and square brackets. XQ.E27 5351 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. XQ.E28 6716 substantive A new non-normative appendix designed to give guidance on the handling of modules. XQ.E29 6693 6717 editorial State more explicitly that user-defined types in an imported schema add constructors for these types to the set of known function signatures. XQ.E30 6737 editorial Fixes an example by replacing the undefined variable <partno> {$p} </partno> with <partno> {$pn} </partno>). (None.) (None.) editorial In G The application/xquery Media Type G.2.2 Published specification (None.) (None.) Editorial In G.2.5 Intended Usage