Copyright © 2002 W3C® (MIT, INRIA, Keio), All Rights Reserved. W3C liability, trademark, document use, and software licensing rules apply.
XPath is a language for addressing parts of an XML document.
This is a public W3C Working Draft for review by W3C Members and other interested parties. This section describes the status of this document at the time of its publication. It is a draft document and may be updated, replaced, or made obsolete by other documents at any time. It is inappropriate to use W3C Working Drafts as reference material or to cite them as other than "work in progress." A list of current public W3C technical reports can be found at http://www.w3.org/TR/.
This document is the result of joint work by the XSL and XML Query Working Groups, which are jointly responsible for XPath 2.0, a language derived from both XPath 1.0 and XQuery. The XPath 2.0 and XQuery 1.0 Working Drafts are generated from a common source. These languages are closely related, sharing much of the same expression syntax and semantics, and much of the text found in the two Working Drafts is identical.
This version of the document contains new details about error handling and conformance. It contains a new grammar in which the precedence of operators is explicitly represented. It introduces two new operators (unordered
and idiv
), and deletes four operators (assert
, precedes
, follows
, and =>
). It also describes changes to the detailed semantics of cast
expressions and other operators, as summarized in H Revision
Log.
This document is a work in progress. It contains many open issues, and should not be considered to be fully stable. Vendors who wish to create preview implementations based on this document do so at their own risk. While this document reflects the general consensus of the working groups, there are still controversial areas that may be subject to change.
Public comments on this document and its open issues are welcome. Comments should be sent to the W3C XPath/XQuery mailing list, public-qt-comments@w3.org (archived at http://lists.w3.org/Archives/Public/public-qt-comments/).
XPath 2.0 has been defined jointly by the XML Query Working Group (part of the XML Activity) and the XSL Working Group (part of the Style Activity).
Patent disclosures relevant to this specification may be found on the XSL Working Group's patent disclosure page at http://www.w3.org/Style/XSL/Disclosures.
1 Introduction
2 Basics
2.1 Expression Context
2.1.1 Static Context
2.1.2 Evaluation Context
2.2 Input Functions
2.3 Expression Processing
2.3.1 Document Order
2.3.2 Typed Value and String Value
2.4 Types
2.4.1 Type Checking
2.4.2 SequenceType
2.4.3 Type Conversions
2.4.3.1 Atomization
2.4.3.2 Effective Boolean Value
2.4.3.3 Fallback Conversions
2.5 Errors and Conformance
2.5.1 Errors
2.5.2 Conformance
2.5.2.1 Basic XPath
2.5.2.2 Schema Import Feature
2.5.2.3 Static Typing Feature
2.5.3 Handling Dynamic Errors
3 Expressions
3.1 Primary Expressions
3.1.1 Literals
3.1.2 Variables
3.1.3 Parenthesized Expressions
3.1.4 Function Calls
3.1.5 Comments
3.2 Path Expressions
3.2.1 Steps
3.2.1.1 Axes
3.2.1.2 Node Tests
3.2.2 Predicates
3.2.3 Unabbreviated Syntax
3.2.4 Abbreviated Syntax
3.3 Sequence Expressions
3.3.1 Constructing Sequences
3.3.2 Combining Sequences
3.4 Arithmetic Expressions
3.5 Comparison Expressions
3.5.1 Value Comparisons
3.5.2 General Comparisons
3.5.3 Node Comparisons
3.5.4 Order Comparisons
3.6 Logical Expressions
3.7 For Expressions
3.8 Conditional Expressions
3.9 Quantified Expressions
3.10 Expressions on SequenceTypes
3.10.1 Instance Of
3.10.2 Cast and Treat
3.11 Validate Expressions
A Grammar
A.1 Lexical structure
A.1.1 Syntactic Constructs
A.1.2 Lexical Rules
A.2 BNF
A.3 Precedence Order
B Type Promotion and Operator Mapping
B.1 Type Promotion
B.2 Operator Mapping
C References
C.1 Normative References
C.2 Non-normative References
C.3 Background References
C.4 Informative Material
D Glossary
E Conformance
F Backwards Compatibility with
XPath 1.0 (Non-Normative)
G XPath 2.0 and XQuery 1.0
Issues (Non-Normative)
H Revision
Log (Non-Normative)
H.1 16 Aug 2002
H.2 10 Apr 2002
H.3 20 Dec
2001
The primary purpose of XPath is to address parts of an [XML] document. XPath uses a compact, non-XML syntax to facilitate use of XPath within URIs and XML attribute values. XPath operates on the abstract, logical structure of an XML document, rather than its surface syntax. This logical structure is known as the data model, and is described in the [XQuery 1.0 and XPath 2.0 Data Model] document. XPath gets its name from its use of a path notation as in URLs for navigating through the hierarchical structure of an XML document.
XPath is designed to be embedded in a host language such as [XSLT 2.0] or [XQuery]. XPath has a natural subset that can be used for matching (testing whether or not a node matches a pattern); this use of XPath is described in [XSLT 2.0].
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.
XPath also depends on and is closely related to the following specifications:
The XPath data model defines the information in an XML document that is available to an XPath processor. The data model is defined in [XQuery 1.0 and XPath 2.0 Data Model].
The static and dynamic semantics of XPath are formally defined in [XQuery 1.0 Formal Semantics]. This is done by mapping the full XPath language into a "core" subset for which the semantics is defined. This document is useful for implementors and others who require a rigorous definition of XPath.
The library of functions and operators supported by XPath is defined in [XQuery 1.0 and XPath 2.0 Functions and Operators].
This document specifies a grammar for XPath, using the same Basic EBNF notation used in [XML], except that grammar symbols always have initial capital letters. Unless otherwise noted, whitespace is not significant in the grammar. Grammar productions are introduced together with the features that they describe, and a complete grammar is also presented in the appendix [A Grammar].
In the grammar productions in this document, nonterminal symbols are underlined and literal text is enclosed in double quotes. Angle brackets are used to enclose tokens that must be recognized by using lexical look-ahead, as described in A.1 Lexical structure. For example, the following production describes the syntax of a function call:
[47] | FunctionCall | ::= | <QName "("> (Expr ("," Expr)*)? ")" |
The production should be read as follows: A function call consists of a QName followed by an open-parenthesis (these tokens must be recognized together using lexical lookahead.) The open-parenthesis is followed by an optional argument list. The argument list (if present) consists of one or more expressions, separated by commas. The optional argument list is followed by a close-parenthesis.
[Ed. Note: A future version of this document will include links between terms (in bold font) and their definitions.]
The basic building block of XPath is the expression. The language provides several kinds of expressions which may be constructed from keywords, symbols, and operands. In general, the operands of an expression are other expressions. XPath is a functional language which allows various kinds of expressions to be nested with full generality. It is also a strongly-typed language in which the operands of various expressions, operators, and functions must conform to designated types.
Like XML, XPath is a case-sensitive language. All keywords in XPath use lower-case characters.
The value of an expression is always a sequence, which is an ordered collection of zero or more items. An
item is either an atomic value or a node. An atomic
value is a value in the value space of an XML Schema atomic
type, as defined in [XML Schema] (that is, a simple type that is
not a list type or a union type). A node conforms to one of the
seven node kinds described in [XQuery 1.0 and XPath 2.0 Data Model]. Each node has a unique node identity. Some
kinds of nodes have typed values, string values, and names, which can be
extracted from the node. The typed value of a node is a sequence
of zero or more atomic values. The string value of a node is a
value of type xs:string
. The name of a node is a value of type xs:QName
.
A sequence containing exactly one item is called a singleton sequence. An item is identical to a singleton sequence containing that item. Sequences are never nested--for example, combining the values 1, (2, 3), and ( ) into a single sequence results in the sequence (1, 2, 3). A sequence containing zero items is called an empty sequence.
In this document, the namespace prefixes xs:
and xsi:
are considered to be bound to the XML Schema namespaces http://www.w3.org/2001/XMLSchema
and http://www.w3.org/2001/XMLSchema-instance
, respectively (as described in [XML Schema]), and the prefix xf:
is considered to be bound to the namespace of XPath/XQuery functions, http://www.w3.org/2002/08/xquery-functions
(described in [XQuery 1.0 and XPath 2.0 Functions and Operators]). In some cases, where the meaning is clear and namespaces are not important to the discussion, built-in XML Schema typenames such as integer
and string
will be used without a namespace prefix.
The expression context for a given expression consists of all the information that can affect the result of the expression. This information is organized into two categories called the static context and the evaluation context.
This section describes the context information used by XPath expressions, including the functions in the core function library. Other functions, outside the core function library, may require additional context information.
The static context of an expression is the information that is available during static analysis of the expression, prior to its evaluation. This information can be used to decide whether the expression contains a static error.
XPath requires the information in the static context to be provided by the language environment in which the expression is being processed. Static context consists of the following components:
Type exception policy. This is one of the values strict
or flexible
. The value indicates the action that should be taken when a type
exception is raised. If the policy is strict
, the type exception is treated as an error. If the policy is flexible
, then a fallback conversion will be invoked; an error will be raised only if the fallback conversion fails.
In-scope namespaces. This is a set of (prefix, URI) pairs. The in-scope namespaces are used for resolving prefixes used in QNames within the expression.
Default namespace for element and type names. This is a namespace URI. This namespace is used for any unprefixed QName appearing in a position where an element or type name is expected.
Default namespace for function names. This is a namespace URI. This namespace is used for any unprefixed QName appearing as the function name in a function call.
In-scope schema definitions. This is a set of (QName, type definition) pairs. It defines the set of types that are available for reference within the expression. It includes the built-in schema types and all globally-declared types in imported schemas. It may also include types declared in schemas associated with documents retrieved by input functions, as described in 2.2 Input Functions.
Ed. Note: The importing of type definitions from input documents is still under discussion. The idea that the static context should be affected by run-time functions in an implementation-defined way remains controversial (see Issue 307.)
In-scope variables. This is a set of (QName, type) pairs. It defines the set of variables that have been declared and are available for reference within the expression. The QName represents the name of the variable, and the type represents its static data type.
In-scope functions. This part of the static context defines the set of functions that are available to be called from within an expression. Each function is uniquely identified by its QName and its arity (number of parameters). The static context maps QName and arity into a function signature, which specifies the static types of the function parameters and function result.
In-scope collations. This is a set of (URI, collation) pairs. It defines the names of the collations that are available for use in function calls that take a collation name as an argument. A collation may be regarded as an object that supports two functions: a function that given a set of strings, returns a sequence containing those strings in sorted order; and a function that given two strings, returns true if they are considered equal, and false if not.
Default collation. This is a collation. This collation is used by string comparison functions when no explicit collation is specified.
Base URI. This is an absolute URI, used by the xf:document
function when resolving the relative URI of a document to be loaded, if
no explicit base URI is supplied in the function call.
The evaluation context of an expression is defined as information that is available at the time the expression is evaluated. The evaluation context consists of all the components of the static context, and the additional components listed below.
The first three components of the dynamic context (context item, context position, and context size) are called the focus of the expression. The focus enables the processor to keep track of which nodes are being processed by the expression.
The focus for the outermost expression is supplied by the
environment in which the expression is evaluated. Certain language constructs,
notably the path expression E1/E2
, and the predicate expression E1[E2]
, create a new focus for the evaluation of a sub-expression. In these constructs, E2
is evaluated once for each item in the sequence that results from
evaluating E1
. Each time E2
is evaluated, it is evaluated with a different focus. The focus for
evaluating E2
is referred to below as the inner focus, while the focus
for evaluating E1
is referred to as the outer focus. The inner focus exists
only while E2
is being evaluated. When this evaluation is complete, evaluation of the
containing expression continues with its original focus unchanged.
[Ed. Note: See issue 216.]
The context item is the item currently being
processed. An item is either an atomic value or a node. When the context item
is a node, it can also be referred to as the context node. The
context item is returned by the expression ".
". When an expression E1/E2
, or E1[E2]
is evaluated, each item in the sequence obtained by evaluating E1
becomes the context item in the inner focus for an evaluation of E2
.
The context position is the position of the context
item within the sequence of items currently being processed. It changes
whenever the context item changes. Its value is always an integer greater than
zero. The context position is returned by the expression xf:position()
. When an expression E1/E2
, or E1[E2]
is evaluated, the context position in the inner focus for an
evaluation of E2
is the position of the context item in the sequence obtained by
evaluating E1
. The position of the first item in a sequence is always 1 (one). The
context position is always less than or equal to the context size.
The context size is the number of items in the
sequence of items currently being processed. Its value is always an integer
greater than zero. The context size is returned by the expression last()
. When an expression E1/E2
, or E1[E2]
is evaluated, the context size in the inner focus for an
evaluation of E2
is the number of items in the sequence obtained by evaluating E1
.
Dynamic variables. This is a set of (QName, type, value) triples. It contains the same QNames as the in-scope variables in the static context for the expression. Each QName is associated with the dynamic type and value of the corresponding variable. The dynamic type associated with the value of a variable may be more specific than the static type associated with the same variable. The value of a variable is, in general, a sequence.
The dynamic types and values of variables are provided by the host language environment in which an XPath expression is being evaluated.
Current date and time. This information represents
an implementation-defined point in time during processing of a query or transformation. It can be retrieved by the xf:current-date
, xf:current-time
, and xf:current-dateTime
functions. If invoked multiple times during the execution of a query or transformation,
these functions always returns a consistent result.
Implicit timezone. This is the timezone to be used when a date, time, or dateTime value that does not have a timezone is used in a comparison or in any other operation. This value is an instance of dayTimeDuration that is implementation-defined. See [ISO 8601] for the range of legal values of a timezone.
Input sequence. The input sequence is sequence of nodes that can be accessed by the input
function. It might be thought of as an "implicit input". The content of the input sequence is determined in an implementation-defined way.
XPath has three functions that provide access to input data. These functions are of particular importance because they provide a way in which an expression can reference a document or a collection of documents. The three input functions are described informally here, and in more detail in [XQuery 1.0 and XPath 2.0 Functions and Operators].
The input sequence is a part of the evaluation context for an expression. The way in which nodes are assigned to the input sequence is implementation-defined. For instance, one implementation might provide a fixed mapping from a directory system to the input sequence, another implementation might provide a graphical user interface that allows users to choose a data source for the input sequence, and a third implementation might support UNIX-style pipes, allowing the output of one query to become the input sequence for another query.
The input
function, which takes no parameters, returns the input
sequence. For example, the expression
input()//customer
returns
all the customer
elements that are descendants of
nodes in the input sequence. If no input sequence has been bound,
the input
function raises a dynamic error.
The collection
function returns the nodes
found in a collection. A collection may be any sequence of nodes. A collection is identified by a
string, which must be a valid URI. For example, the expression
collection("http://example.org")//customer
identifies all the customer
elements that are
descendants of nodes found in the collection whose URI is
http://example.org
.
The document
function, when its first argument
is a string containing a single URI that refers to an
XML document, returns the root of that document. The
document
function can also be used to address
multiple documents or document fragments; see
[XQuery 1.0 and XPath 2.0 Functions and Operators] for details.
The input functions described in this section provide access to input documents or document fragments. If these documents or document fragments are associated with schemas, the type definitions contained in these schemas may be added to the in-scope schema definitions, in an implementation-defined way.
Ed. Note: The importing of type definitions from input documents is still under discussion. The idea that the static context should be affected by run-time functions in an implementation-defined way remains controversial (see Issue 307).
XPath is defined in terms of the [XQuery 1.0 and XPath 2.0 Data Model] (referred to in this document simply as the Data Model), which represents information in the form of nodes and atomic values. Before an XPath expression can be processed, the input documents to be operated on by the expression must be represented in the Data Model. For example, an XML document can be converted to the Data Model by the following steps:
The document can be parsed using an XML parser.
The parsed document can be validated against one or more schemas. This process, which is described in [XML Schema], results in an abstract information structure called the Post-Schema Validation Infoset (PSVI). If a document has no associated schema, it can be validated against a permissive default schema that accepts any well-formed document.
The PSVI can be transformed into the Data Model by a process described in [XQuery 1.0 and XPath 2.0 Data Model].
The above steps provide an example of how a Data Model instance might be constructed. A Data Model instance might also be synthesized directly from a relational database, or constructed in some other way. XPath is defined in terms of operations on the Data Model, but it does not place any constraints on how the input Data Model instance is constructed.
Each element or attribute node in the Data Model has an annotation that indicates its dynamic type. If the Data Model was derived from an input XML document, the dynamic types of the elements and attributes are derived from schema validation. The dynamic type of an element or attribute indicates its range of values--for example, an attribute named version
might have the dynamic type xs:decimal
, indicating that it contains a decimal value.
The value of an attribute is represented directly within the attribute node. An attribute node whose type is unknown (such as might occur in a schemaless document) is annotated with the dynamic type xs:anySimpleType
.
The value of an element is represented by the children of the element node, which may include text nodes and other element nodes. The dynamic type of an element node indicates how the values in its child text nodes are to be interpreted. An element whose type is unknown (such as might occur in a schemaless document) is annotated with the type xs:anyType
.
Atomic values in the Data Model also carry dynamic type annotations. An atomic value of unknown type is annotated with the type xs:anySimpleType
. Under certain circumstances (such as during processing of an arithmetic operator), an atomic value of xs:anySimpleType
may be cast into a more specific type (such as xs:double
).
This document provides a description of how each kind of expression is processed. For each expression, the operands and result are instances of the Data Model. The details of transforming XML documents into the Data Model are described in [XQuery 1.0 and XPath 2.0 Data Model]. Transformation of a Data Model instance into an XML document is currently an open issue.
The terms document order, typed value, and string value are described here because they are of particular importance for the processing of expressions.
Document order defines a total ordering among all the nodes seen by the language processor. Within a given document, the document node is the first node, followed by element nodes, text nodes, comment nodes, and processing instruction nodes in the order of their representation in the XML form of the document (after expansion of entities). Element nodes occur before their children. The namespace nodes of an element immediately follow the element node, in implementation-defined order. The attribute nodes of an element immediately follow its namespace nodes, and are also in implementation-defined order.
The relative order of nodes in distinct documents is implementation-defined but stable within a given query or transformation. In other words, given two distinct documents A and B, if a node in document A is before a node in document B, then every node in document A is before every node in document B. The relative order among free-floating nodes (those not in a document) is implementation-defined.
Element, attribute, and text nodes have a typed value and a string value that can be extracted by calling the data
function and the string
function, respectively. The typed value of a node is a sequence of atomic values, and the string value of a node is a string. Element and attribute nodes also have a type annotation, which is a QName that is defined in the in-scope schema definitions.
The typed value and string value for each kind of node are defined by the dm:typed-value
and dm:string-value
accessors in [XQuery 1.0 and XPath 2.0 Data Model]. Specifically:
The typed value of a text node is the same as its string value, as an instance of xs:anySimpleType
.
If the type annotation of an attribute node is xs:anySimpleType
, its typed value is equal to its string value, as an instance of xs:anySimpleType
. Otherwise, its typed value is derived from its string value and type annotation in a way that is consistent with schema validation, as described in [XQuery 1.0 and XPath 2.0 Data Model].
Example: A2 is a validated attribute with type annotation IDREFS
, which is a list type derived from IDREF
. Its string value is "bar baz faz
". The typed value of A2 is a sequence of three atomic values ("bar
", "baz
", "faz
"), each of type IDREF
.
If the type annotation of an element node is xs:anyType
, its typed value is equal to its string value, as an instance of xs:anySimpleType
. Otherwise, its typed value is derived from its string value and type annotation in a way that is consistent with schema validation, as described in [XQuery 1.0 and XPath 2.0 Data Model]. If the type annotation of an element denotes a type with complex content (i.e., a type that permits subelements), its typed value is undefined, and the data
function raises an error when applied to such an element.
Example: E2 is a validated element node with the type annotation hatsizelist
, which is a complex type whose content is defined as a sequence of items of type hatsize
, which in turn is derived from xs:integer
. The string value of E2 is "7 8 9
". The typed value of E2 is a sequence of three values (7
, 8
, 9
), each of type hatsize
.
Example: E3 is a validated element node with the type annotation weather
, which is a complex type that permits subelements. The string value of E3 is "hot
". Even though E3 does not happen to contain any subelements, its typed value is undefined because its type permits subelements.
XPath is a strongly typed language with a type system based on
[XML Schema]. The built-in types of XPath include the node kinds
of XML (such as element, attribute, and text nodes), the built-in atomic types of [XML Schema] (such as xs:integer
and xs:string
), and the following special derived types: xf:dayTimeDuration
and xf:yearMonthDuration
(described in [XQuery 1.0 and XPath 2.0 Functions and Operators]). Additional type definitions may be imported from the language environment via the in-scope schema definitions.
When the type of a value is not appropriate for the context in which it is used, a type exception is raised. Languages that are based on XPath 2.0 may handle type exceptions with either a strict
or a flexible
policy, as described in 2.4.3.3 Fallback Conversions.
Like XML Schema, XPath distinguishes named types from anonymous types. The set of named types includes all the built-in types and all user-defined simple or complex types for which the type declaration contains a name. For example, named types may be associated with values in one of the following ways:
A literal value has a named type; for example, the type of the value 47
is xs:integer
.
The constructor functions described in [XQuery 1.0 and XPath 2.0 Functions and Operators] return values with named types; for example, xs:date("2002-5-31")
returns a value of type xs:date
.
When an instance of the Data Model is constructed from a validated document, type names assigned by a schema processor are preserved in the Data Model.
The validate
expression invokes schema validation within a query, assigning type
names in the same way that a schema processor would.
The cast
expression creates an atomic value with a specific named type.
Some functions, such as data()
, extract typed values from the nodes of a document, preserving the named types of these values.
The XPath type system is formally defined in [XQuery 1.0 Formal Semantics]. This section presents a summary of types from a user's perspective.
XPath defines two phases of processing called the analysis phase and the evaluation phase.
The analysis phase depends on the query expression itself and on the static context. The analysis phase does not depend on any input data. The purpose of type-checking during the analysis phase is to provide early detection of type errors and to compute the type of a query result.
During the analysis phase, each expression is assigned a static type. In some cases, the static type is derived from the lexical form of the expression; for example, the static type of the literal 5
is xs:integer
. In other cases, the static type of an expression is inferred according to rules based on the static types of its operands; for example, the static type of the expression size < 5
is xs:boolean
. The static type of an expression may be either a named type or a structural description--for example, xs:boolean?
denotes an optional occurrence of the xs:boolean
type. The rules for inferring the static types of various expressions are described in [XQuery 1.0 Formal Semantics]. During the analysis phase, if an operand of an expression is found to have a static type that is not appropriate for that operand, a static type error is raised. If static type checking raises no errors and assigns a static type T to an expression, then execution of the expression on valid input data is guaranteed to produce either a value of type T or to raise a dynamic type error.
The evaluation phase is performed only after successful completion of the analysis phase. The evaluation phase depends on input data, on the expression being evaluated, and on the evaluation context. During the evaluation phase, a dynamic type is associated with each value as it is computed. The dynamic type of a value may be either a structural type (such as "sequence of integers") or a named type. The dynamic type of a value may be more specific than the static type of the expression that computed it (for example, the static type of an expression might be "zero or more integers or strings," but at run time its value may have the dynamic type "integer.") If an operand of an expression is found to have a dynamic type that is not appropriate for that operand, a type exception is raised.
It is possible for analysis of an expression to raise a static type error, even though the expression might evaluate successfully on some valid input data. For example, an expression might contain a function that requires an element as its parameter, and the analysis phase might infer the static type of the function parameter to be an optional element. In this case, a static type error would result, even though the function call would be successful for input data in which the optional element is present.
It is also possible for an expression to raise a dynamic error, even though analysis of the expression raised no static error. For example, an expression may contain a cast of a string into an integer, which is statically valid. However, if the actual value of the string at run time cannot be cast into an integer, a dynamic error will result. Similarly, an expression may apply an arithmetic operator to a value extracted from a schemaless document. This is not a static error, but at run time, if the value cannot be successfully cast to a numeric type, a dynamic error will be raised.
If an implementation can determine by static analysis that an expression will necessarily raise a dynamic error (for example, because it attempts to construct a decimal value from a constrant string that is not a valid decimal value), the implementation is allowed to report this error during the analysis phase (as well as during the evaluation phase).
When it is necessary to refer to a type in an XPath expression, the syntax shown below is used. This syntax production is called "SequenceType", since it describes the type of an XPath value, which is a sequence.
[51] | SequenceType | ::= | (ItemType OccurrenceIndicator) | "empty" |
[52] | ItemType | ::= | (("element" | "attribute") ElemOrAttrType?) |
[53] | ElemOrAttrType | ::= | (QName (SchemaType | SchemaContext?)) | SchemaType |
[54] | SchemaType | ::= | <"of" "type"> QName |
[48] | SchemaContext | ::= | "in" SchemaGlobalContext ("/" SchemaContextStep)* |
[49] | SchemaGlobalContext | ::= | QName | <"type" QName> |
[50] | SchemaContextStep | ::= | QName |
[55] | AtomicType | ::= | QName |
[56] | OccurrenceIndicator | ::= | ("*" | "*" | "+" | "?")? |
Here are some examples of SequenceTypes that might be used in XPath expressions:
xs:date
refers to the built-in Schema type date
attribute?
refers to an optional attribute
element
refers to any element
element office:letter
refers to an element that has a specific name and that has been validated as conforming to the schema definition for that name
element of type
po:address+
refers to one or more elements that have been validated as conforming to the schema definition of the given type
node*
refers to a sequence of zero or more nodes of any type
item*
refers to a sequence of zero or more nodes or atomic values
During processing of a query, it is sometimes necessary to determine whether a given value matches a type that was declared using the SequenceType syntax. This process is known as SequenceType matching. For example, an instance of
expression returns true
if a given value matches a given type, or false
if
it does not.
SequenceType matching between a given value and a given SequenceType is performed as follows:
If the SequenceType is empty
, the match succeeds only if the value is an empty sequence. If the
SequenceType is an ItemType with no OccurrenceIndicator, the match succeeds only if the value contains precisely one item and that item matches the ItemType (see below).
If the SequenceType contains an ItemType and an OccurrenceIndicator, the match succeeds only if the number of items in the value matches the OccurrenceIndicator and each
of these items matches the ItemType. As a consequence of these rules, a value that is an empty sequence matches any SequenceType whose occurrence indicator is *
or ?
.
An OccurrenceIndicator indicates the number of items in a sequence, as follows:
?
indicates zero or one items
*
indicates zero or more items
+
indicates one or more items
The process of matching a given item against a given ItemType is performed as follows (remember that an item may be a node or an atomic value):
The ItemType item
matches any item. For example, item
matches the atomic value 1
or the element <a/>
.
The following ItemTypes match atomic values:
atomic value
matches any atomic value.
A named atomic type matches a value if the dynamic type of the value is the same as the named atomic type or is derived from the named atomic type by restriction. For example, the ItemType xs:decimal
matches the value 12.34
(a decimal literal); it also matches a value whose dynamic type is shoesize
, if shoesize
is an atomic type derived from xs:decimal
.
untyped
matches an atomic value whose
most specific type is xs:anySimpleType
.
The following ItemTypes match nodes:
node
matches any node.
text
matches any text node.
processing-instruction
matches any processing instruction node.
comment
matches any comment node.
document
matches any document node.
element
matches an element node. Optionally, element
may be followed by ElemOrAttrType,which places further constraints on the node (see below).
attribute
matches an attribute node. Optionally, attribute
may be followed by ElemOrAttrType,which places further constraints on the node (see below).
An ElemOrAttrType may be used to place a constraint on the name or type of an element or attribute, as follows:
One form of ElemOrAttrType, denoted by the phrase "of type
", specifies the required type of the element or attribute node. The required type must be the QName of a simple or complex type that is found in the in-scope schema definitions. The match is successful only if the given element or attribute has a type annotation that is the same as the required type or is known (in the in-scope schema definitions) to be derived from the required type. For example, element of type Employee
matches an element node that has been validated and has received the type annotation Employee
. Similarly, attribute of type xs:integer
matches an attribute node that has been validated and has received the type annotation xs:integer
.
Another form of ElemOrAttrType is simply a QName, which is interpreted as the required name of the element or attribute. The QName must be an element or attribute name that is found in the in-scope schema definitions. The match is successful only if the given element or attribute has the required name and also conforms to the schema definition for the required name. This can be verified in either of the following ways:
If the schema definition for the required name has a named type, the given element or attribute must have a type annotation that is the same as that named type or is known (in the in-scope schema definitions) to be derived from that named type. For example, suppose that a schema declares the element named location
to have the type State
. Then the SequenceType element location
will match a given element only if its name is location
and its type annotation is State
or some named type that is derived from State
.
If the schema definition for the required name has an anonymous (unnamed) type definition, the actual content of the given element or attribute must structurally comply with this type definition. For example, suppose that a schema declares the element named shippingAddress
to have an anonymous complex type consisting of a street
element followed by a city
element. Then the SequenceType element shippingAddress
will match a given element only if its name is shippingAddress
and its content is a street
element followed by a city
element.
The constraint that an element must have a required name is considered to be satisfied if the element has been validated and found to be a member of a substitution group whose head element has the required name. Substitution groups are described in [XML Schema].
The above two forms of ElemOrAttrType may be combined to specify both the required name and the required type of an element or attribute node, as in element person of type Employee
or attribute color of type xs:integer
. This form might be used, for example, to specify a required type that is more specific than the schema type associated with the required name.
In some cases, the required name of an element or attribute node may be locally declared (that is, declared inside a complex type in some schema.) In this case, the ElemOrAttrType may specify the SchemaContext in which the required name is to be interpreted. For example, element shippingAddress in invoice/customer
matches an element node that conforms to the schema definition of the element name shippingAddress
, as it would be interpreted inside a customer
element that is inside an invoice
element. The first QName in the SchemaContext must be found in the in-scope schema definitions.
Some expressions do not require their operands to exactly match the expected type. For example, function parameters and returns expect a value of a particular type, but automatically perform certain type conversions, such as extraction of atomic values from nodes, promotion of numeric values, and implicit casting of untyped values. The conversion rules for function parameters and returns are discussed in 3.1.4 Function Calls. Other operators that provide special conversion rules include arithmetic operators, which are discussed in 3.4 Arithmetic Expressions, and value comparisons, which are discussed in 3.5.1 Value Comparisons.
Type conversions sometimes depend on a process called atomization, which is used when an optional atomic value is expected. When atomization is applied to a given value, the result is either a single atomic value, an empty sequence, or a type exception. Atomization is defined as follows:
If the value is a single atomic value or an empty sequence, atomization simply returns the value.
If the value is a single node, the typed value of the node is extracted and returned; however, if the typed value is a sequence containing more than one item, a type exception is raised.
In any other case, atomization raises a type exception.
Atomization may be used in processing the following types of expressions:
Arithmetic expressions
Comparison expressions
Function calls and returns
Cast expressions
If a sequence of items is encountered where a boolean value is expected, it is necessary to find its effective boolean value. The effective boolean value of a sequence is defined as follows:
If the sequence is empty, its effective boolean value is false
.
If the sequence contains a single atomic value of type xs:boolean
, this value is the effective boolean value of the sequence.
If the sequence contains at least one node, its effective
boolean value is true
.
In any other case, a type exception is raised.
The effective boolean value of a sequence may be computed during the processing of the following types of expressions:
Logical expressions (and
, or
)
The xf:not
function
Conditional expressions (if
)
Quantified expressions (some
, every
)
The action taken when a type exception is
raised depends on the language environment in which the XPath expression is
being evaluated. A language environment may choose either a strict
or a flexible
type exception policy. If the policy is strict
, a type exception is treated as
a dynamic error. If the policy is flexible
, the language environment must handle type exceptions by applying a fixed set of
rules called fallback conversions. The purpose of fallback conversions is to provide backward compatibility with the behavior of XPath Version 1.0.
This means that some language environments may be more permissive than others about type conversions. In general, XPath expressions will be portable from one language environment to another only if they make no reliance on fallback conversions. However, if an expression evaluates without raising an error in two different language environments, it will always return the same result.
A type exception is raised when a given value does not conform to its required type. A language environment that implements fallback conversions must resolve this conflict by applying the following rules, in order:
If the required type is anything other than an atomic type or a single node, a dynamic error is raised.
If the required type is boolean
, and the given value is an empty
sequence, the given value is converted to boolean false
.
If the required type is boolean
, and the given value is a
sequence containing at least one node, the given value is converted to boolean true
.
If the required type is a node, and the first item in the sequence is a node, only the first item is retained. If the required type is a node, and the first item in the sequence is not a node, a dynamic error is raised.
Otherwise if the given value is a sequence containing more than one item, only the first item is retained. If this item is a node, its typed value is extracted. If the typed value of the node is a sequence of more than one atomic value, only the first of these atomic values is retained. The resulting (supplied or extracted) atomic value is converted to the required type according to the rules in the following table:
boolean type | string type | number type | other atomic type | |
---|---|---|---|---|
boolean value | N/A | Boolean false value is converted to the string false . The boolean true value is converted to the string true . | Boolean true is converted to 1 ; boolean false is converted to 0 . | Dynamic error |
string value | 'true' or '1' goes to true, 'false' or '0' goes to false. Otherwise, if the string is empty, return false; otherwise, return true. | N/A | Use the numeric constructor for the specific number type, passing in the string value. | Use the appropriate string constructor for the specific type as defined in the [XQuery 1.0 and XPath 2.0 Functions and Operators] document. |
number value | 0, +0, -0, and NaN, is converted to boolean false, anything else is converted to boolean true. | Use the string value of the atomic value, as defined in the data model. | N/A | Attempt to cast the value to the given atomic type, using the tables defined in [XQuery 1.0 and XPath 2.0 Functions and Operators]. If casting fails, raise a dynamic error. |
other atomic value | Attempt to cast the value to a boolean, using the tables defined in [XQuery 1.0 and XPath 2.0 Functions and Operators]. If casting fails, raise a dynamic error. | Attempt to cast the value to a string, using the tables defined in [XQuery 1.0 and XPath 2.0 Functions and Operators]. If casting fails, raise a dynamic error. | Attempt to cast the value to a number, using the tables defined in [XQuery 1.0 and XPath 2.0 Functions and Operators]. If casting fails, raise a dynamic error. | Attempt to cast the value to the given atomic type, using the tables defined in [XQuery 1.0 and XPath 2.0 Functions and Operators]. If casting fails, raise a dynamic error. |
Ed. Note: The entries in this table should always match the casts in [XQuery 1.0 and XPath 2.0 Functions and Operators]. If there is disagreement, [XQuery 1.0 and XPath 2.0 Functions and Operators] should take precedence.
Ed. Note: This section has been approved by the XML Query Working Group but is still being discussed by the XSLT Working Group. Some changes in XPath syntax and/or semantics may result from these discussions.
As described in 2.4.1 Type Checking, XPath defines an analysis phase, which does not depend on input data, and an evaluation phase, which does depend on input data.
The result of the analysis phase is either success or one or more static errors. Some static errors are static type errors, which occur when the static type of an expression is not correct for the context in which it appears. The term static errors also includes non-type-related errors such as syntax errors. The means by which static errors are reported is implementation-defined.
The result of the evaluation phase is either a result value or a dynamic error. Some dynamic errors are dynamic type errors, which occur when the dynamic type of an expression is not correct for the context in which it appears. The term dynamic errors also includes non-type-related dynamic errors such as numeric overflow. If an implementation returns a value, the value must conform to the dynamic rules defined in [XQuery 1.0 Formal Semantics].
[XQuery 1.0 Formal Semantics] defines the set of static and dynamic errors. In addition to these errors, an XPath implementation may raise implementation-defined warnings, either during the analysis phase or the evaluation phase. The way in which warnings are raised and handled is implementation-defined.
XPath defines a basic conformance level named Basic XPath, and two optional features called the Schema Import Feature and the Static Typing Feature. A conforming implementation must satisfy the requirements of Basic XPath, and may also provide either or both of the optional features.
A conforming Basic XPath implementation must implement the full XPath language, subject to the following limitations:
In a Basic XPath
implementation, the in-scope schema
definitions consist of a fixed set of 48 predefined type definitions. These
include the 44 built-in datatypes defined in [XML Schema], plus four
additional types: xf:yearMonthDuration
,
xf:dayTimeDuration
,
xs:anySimpleType
, and xs:anyType
.
A mapping from a Post-Schema Validation Infoset (PSVI) to the Query Data Model is specified in [XQuery 1.0 and XPath 2.0 Data Model]. In a Basic XPath implementation, this mapping maps each datatype that is not one of the 48 predefined types listed above into its nearest supertype that belongs to this list. As a result of this mapping, all complex types are mapped into xs:anyType
. (Of course, mapping from a PSVI is only one way in which a Query Data Model instance might be constructed--other ways are also possible.)
If any SequenceType contains an AtomicType that is not one of the 48 predefined types listed above, a Basic XPath implementation raises a static error.
If any SequenceType contains an ElemOrAttrType, a Basic XPath implementation raises a static error.
If the processing of an expression depends on the type of some value, and that type is not one of the 48 predefined types listed above, a Basic XPath implementation raises a dynamic error.
A Basic XPath implementation is not required to raise static type errors during the analysis phase. If an expression contains one or more non-type-related static errors, then a Basic XPath implementation must raise at least one of these static errors during the analysis phase. If the analysis phase is successful but one or more dynamic errors are encountered during the evaluation phase, then a Basic XPath implementation must raise at least one of these dynamic errors.
The Schema Import Feature removes the limitations specified by Rules 1 through 5 of Basic XPath.
The Static Typing Feature removes the limitation specified by Rule 6 of Basic XPath. An implementation that includes this feature is required to detect static type errors. If an expression contains one or more static errors, including static type errors, then a Static Typing implementation must raise at least one of these static errors during the analysis phase.
Ed. Note: The Working Group is currently discussing the relationships among the various XPath features (for example, if an expression executes successfully on an implementation with Feature A, will it also execute successfully on an implementation with Feature B?). The Working Group is also discussing the issue of "type soundness" (that is, if the Static Typing Feature is implemented and a given expression raises no static errors, what guarantees can be made about its behavior during the evaluation phase?). The editors expect to include more material on these issues in a future version of this document. (See Issue 308.)
Except as noted in this document, if any operand of an expression
raises a dynamic error, the expression also raises a dynamic error.
If an expression can validly return a value or raise a dynamic
error, the implementation may choose to return the value or raise
the dynamic error. For example, the logical expression
expr1 and expr2
may return the value false
if either operand returns false
,
or may raise a dynamic error if either operand raises a dynamic
error.
If more than one operand of an expression may raise an error, the implementation may choose which error is raised by the expression. For example, in this expression:
($x div $y) + xsd:decimal($z)
both ($x div $y)
and xsd:decimal($z)
may
raise an error. The
implementation may choose which error is raised by the "+
"
expression. Once one operand raises an error, the implementation is
not required, but is permitted, to evaluate any other operands.
A dynamic error carries an error value, which may be a single item or an empty sequence. For example, an error value might be an integer, a string, a QName, or an element. An implementation may provide a mechanism whereby an application-defined error handler can process error values and produce diagnostics; in the absence of such an error handler, the string-value of the error value may be used directly as an error message.
A dynamic error may be raised by a built-in
function or operator. For example,
the input
function raises an error if the input
sequence is not
defined in the evaluation context.
An error can be raised explicitly by calling the
xf:error
function,
which only raises an error and never returns a value.
The xf:error
function takes an optional item as its parameter, which is used as the error value. For example, the following function call raises a dynamic error
whose error value is a string:
xf:error(xf:concat("Unexpected value ", $v))
This section introduces each of the basic kinds of XPath expression. Each kind of expression has a name such as PathExpr
, which is introduced on the left side of the grammar production that defines the expression. Since XPath is a composable language, each kind of expression is defined in terms of other expressions whose operators have a higher precedence. In this way, the precedence of operators is represented explicitly in the grammar.
The simplest kinds of expressions are introduced first, followed by more complex expressions. This order of presentation does not conform to the order of operator precedence. The complete grammar is presented in the appendix [A Grammar].
The highest-level kind of expression is a ExprSequence, which is defined in 3.3.1 Constructing Sequences. The highest-level operator (that is, the kind of expression whose operators have lowest precedence) is OrExpr
, which is defined in 3.6 Logical Expressions.
[1] | XPath | ::= | ExprSequence? |
[3] | Expr | ::= | OrExpr |
Primary expressions are the basic primitives of the language. They include literals, variables, function calls, and the use of parentheses to control precedence of operators.
[28] | PrimaryExpr | ::= | Literal | FunctionCall | ("$" VarName) | ParenthesizedExpr |
[167] | VarName | ::= | QName |
A literal is a direct syntactic representation of an atomic value. XPath supports two kinds of literals: string literals and numeric literals.
[45] | Literal | ::= | NumericLiteral | StringLiteral |
[44] | NumericLiteral | ::= | IntegerLiteral | DecimalLiteral | DoubleLiteral |
[147] | IntegerLiteral | ::= | Digits |
[148] | DecimalLiteral | ::= | ("." Digits) | (Digits "." [0-9]*) |
[149] | DoubleLiteral | ::= | (("." Digits) | (Digits ("." [0-9]*)?)) ("e" | "E") ("+" | "-")? Digits |
[162] | StringLiteral | ::= | ('"' (('"' '"') | [^"])* '"') | ("'" (("'" "'") | [^'])* "'") |
The value of a string literal is a singleton sequence
containing an item whose primitive type is xs:string
and whose value is the string denoted by the characters between the
delimiting quotation marks. If the literal is delimited by single quotes, two adjacent single quote characters within the literal are interpreted as one single quote character. Similarly, if the literal is delimited by double quotes, two adjacent double quote characters within the literal are interpreted as one double quote character.
If a string literal is used inside the value of an attribute, the quote characters used to delimit the literal should be different from the quote characters that are used to delimit the attribute.
The value of a numeric literal containing no ".
" and no e
or E
character is a singleton sequence containing an item whose type is xs:integer
and whose value is obtained by parsing the numeric literal according to
the rules of the xs:integer
datatype. The value of a numeric literal containing ".
" but no e
or E
character is a singleton sequence containing an item whose primitive
type is xs:decimal
and whose value is obtained by parsing the numeric literal according to
the rules of the xs:decimal
datatype. The value of a numeric literal containing an e
or E
character is a singleton sequence containing an item whose primitive
type is xs:double
and whose value is obtained by parsing the numeric literal according to
the rules of the xs:double
datatype.
Here are some examples of literal expressions:
"12.5"
denotes the string containing the characters '1', '2', '.', and
'5'.
12
denotes the integer value twelve.
12.5
denotes the decimal value twelve and one half.
125E2
denotes the double value twelve thousand, five hundred.
The boolean values true
and false
can be represented by calls to the built-in functions xf:true()
and xf:false()
, respectively.
Values of other XML Schema built-in types can be constructed by calling the constructor for the given type. The constructors for XML Schema built-in types are defined in [XQuery 1.0 and XPath 2.0 Functions and Operators]. In general, the name of a constructor function for a given type is the same as the name of the type (including its namespace). For example:
xs:integer("12")
returns the integer value twelve.
xs:date("2001-08-25")
returns an item whose type is xs:date
and whose value represents the date 25th August 2001.
xf:dayTimeDuration("PT5H")
returns an item whose type is xf:dayTimeDuration
and whose value represents a duration of five hours.
It is also possible to construct values of various types by using a cast
expression. For example:
cast as
hatsize(9)
returns an item whose primitive value is the integer 9 and
whose type is the user-defined type hatsize
, derived from xs:integer
.
A variable evaluates to the value to which its name is bound in the evaluation context. An expression containing an unbound variable raises a static error. Variables can be bound by clauses in for expressions and quantified expressions.
XPath also allows variables to be bound in the host language environment.
[46] | ParenthesizedExpr | ::= | "(" ExprSequence? ")" |
Parentheses may be used to enforce a particular evaluation order in
expressions that contain multiple operators. For example, the expression (2 + 4)
* 5
evaluates to thirty, since the parenthesized expression (2 + 4)
is evaluated first and its result is multiplied by five. Without
parentheses, the expression 2 + 4 * 5
evaluates to twenty-two, because the multiplication operator has higher
precedence than the addition operator.
Empty parentheses are used to denote an empty sequence, as described in 3.3.1 Constructing Sequences.
A function call consists of a QName followed by a parenthesized list of zero or more expressions, called arguments. The QName and number of arguments must match the name and arity of an in-scope function in the static context (see 2.1 Expression Context); otherwise, a static error is raised.
[47] | FunctionCall | ::= | <QName "("> (Expr ("," Expr)*)? ")" |
A function call expression is evaluated as follows:
Each argument expression is evaluated, producing an argument value.
Each argument value is converted to the declared type of the corresponding function parameter, using the function conversion rules listed below.
The function is executed using the converted argument values. The result is a value of the function's declared return type.
The function conversion rules are used to convert an argument value to its required type; that is, to the declared type of the function parameter. The required type is expressed as a SequenceType. The function conversion rules are as follows:
If the required type is an AtomicType:
Atomization is applied to the given value. If the resulting atomic value is
of type xs:anySimpleType
, an attempt is made to cast it to the required type; if the cast fails,
the function call raises a dynamic type error. If the atomic value has a type that can be promoted
to the required type using the promotion rules in B.1 Type Promotion,
the promotion is done.
If the required type is a sequence or optional occurrence of AtomicType:
If the given value contains any nodes, these nodes are replaced by their typed values. Each item is converted to the required AtomicType using the conversion rule for AtomicType.
If the required type is any other SequenceType, or if no required type is declared:
No conversion is performed.
If the Static Typing Feature is implemented, and the static type of a (converted) function argument or result, as inferred by the static type inference rules in [XQuery 1.0 Formal Semantics], is not a subtype of the required type, a static type error is raised. If the Static Typing Feature is not implemented, and the dynamic type of a (converted) function argument or result does not match the required type according to the rules for SequenceType Matching, a dynamic type error is raised.
A core library of functions is defined in [XQuery 1.0 and XPath 2.0 Functions and Operators]. Functions in this library may be invoked without a namespace prefix by assigning the default function namespace to the namespace of the function library.
The comma operator in XPath serves two purposes: it separates the arguments in a function call, and it separates items in an expression that constructs a sequence (see 3.3.1 Constructing Sequences). To distinguish these two uses, parentheses can be used to delimit the individual arguments of a function call. Here are some illustrative examples of function calls:
three-argument-function(1,
2, 3)
denotes a function call with three arguments.
two-argument-function((1,
2), 3)
denotes a function call with two arguments, the first of which is a
sequence of two values.
two-argument-function(1,
())
denotes a function call with two arguments, the second of which is an
empty sequence.
one-argument-function((1, 2,
3))
denotes a function call with one argument that is a sequence of three
values.
one-argument-function(( ))
denotes a function call with one argument that is an empty sequence.
zero-argument-function( )
denotes a function call with zero arguments.
XPath comments can be used to provide informative annotation. These comments are lexical constructs only, and do not affect the processing of an expression.
[59] | ExprComment | ::= | "{--" [^}]* "--}" |
Comments may be used before and after major tokens within expressions . See A.1 Lexical structure for the exact lexical states where comments are recognized.
The following is an example of a comment:
{-- Houston, we have a problem --}
Ed. Note: The EBNF should disallow "--}" within the comment, rather than "}".
A path expression can be used to locate nodes within a tree. Because the XPath grammar is organized around the precedence of operators, the syntax for PathExpr also includes PrimaryExpr. In common usage, the term path expression denotes a PathExpr that is not simply a PrimaryExpr.
[18] | PathExpr | ::= | ("/" RelativePathExpr?) | ("//" RelativePathExpr) | RelativePathExpr |
[19] | RelativePathExpr | ::= | StepExpr (("/" | "//") StepExpr)* |
A path expression consists of a series of one or more steps, separated by "/
", and optionally beginning with "/
" or "//
". An initial "/
" or "//
" is an abbreviation for one or more initial steps that are implicitly added to the beginning of the path expression, as described below.
A path expression consisting of a single step is evaluated as described in 3.2.1 Steps.
In a path expression consisting of two or more steps, each occurrence of //
is expanded as described in 3.2.4 Abbreviated Syntax, leaving a sequence of steps separated by /
. This sequence of steps is then evaluated from left to right. Each operation E1/E2
is evaluated as follows: Expression E1
is evaluated, and if the result is not a sequence of nodes, a dynamic error is raised. The resulting sequence of nodes is sorted in document order, and duplicates are eliminated based on node identity. Each node resulting from the evaluation of E1
then serves in turn to provide an inner focus for an evaluation of E2
, as described in 2.1.2 Evaluation Context. Each evaluation of E2
must result in a sequence of nodes; otherwise, a dynamic error is raised. The sequences of nodes resulting from all the evaluations of E2
are merged, eliminating duplicate nodes based on node identity and sorting the results in document
order.
As an example of a path expression, child::div1/child::para
selects the para
element children of the div1
element children of the context node, or, in other words, the para
element grandchildren of the context node that have div1
parents.
A "/
" at the beginning of a path expression is an abbreviation for the initial step xf:root(self::node())
. The effect of this initial step is to begin the path at the root node that contains the context node. If the context item is not a node, a dynamic error is raised.
A "//
" at the beginning of a path expression is an abbreviation for the initial steps xf:root(self::node())/descendant-or-self:node()
. The effect of these initial steps is to establish an initial node sequence that contains all nodes in the same hierarchy as the context node. This node sequence is then filtered by subsequent steps in the path expression. If the context item is not a node, a dynamic error is raised.
A step generates a sequence of items and then filters the sequence by zero or more predicates. The value of the step consists of those items that satisfy the predicates. Predicates are described in 3.2.2 Predicates.
A step may consist of a primary expression (described in 3.1 Primary Expressions), a forward step, or a reverse step. A forward or reverse step always returns a sequence of nodes. A forward or reverse step might be thought of as beginning at the context node and navigating to those nodes that are reachable from the context node via a specified axis. Such a step has two parts: an axis, which defines the "direction of movement" for the step, and a node test, which specifies the node kind and/or name of the nodes to be selected by the step.
In the abbreviated syntax for a step, the axis can be omitted and other shorthand notations can be used as described in 3.2.4 Abbreviated Syntax.
The unabbreviated syntax for a forward or reverse 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
and/or name specified by the node test. For example, the
step child::para
selects the para
element children of the context node: child
is the name of the axis, and para
is the name of the element nodes to be selected on this axis. The available axes are described in 3.2.1.1 Axes. The
available node tests are described in 3.2.1.2 Node Tests. Examples of
steps are provided in 3.2.3 Unabbreviated Syntax and 3.2.4 Abbreviated Syntax.
[29] | ForwardAxis | ::= | <"child" "::"> |
[30] | ReverseAxis | ::= | <"parent" "::"> |
XPath defines a set of full set of axes for traversing documents, but a host language may define a subset of these axes. The following axes are defined:
the child
axis contains the children of the context node
the descendant
axis contains the descendants of the context node; a descendant is a
child or a child of a child and so on; thus the descendant axis never contains
attribute or namespace nodes
the parent
axis contains the parent of the context node, if there is one
the ancestor
axis contains the ancestors of the context node; the ancestors of the
context node consist of the parent of context node and the parent's parent and
so on; thus, the ancestor axis will always include the root node, unless the
context node is the root node
the following-sibling
axis contains all the following siblings of the context node; if the
context node is an attribute node or namespace node, the following-sibling
axis is empty
the preceding-sibling
axis contains all the preceding siblings of the context node; if the
context node is an attribute node or namespace node, the preceding-sibling
axis is empty
the following
axis contains all nodes, in the same document or document fragment as the context node, that
are after the context node in document order, excluding any descendants and
excluding attribute nodes and namespace nodes
the preceding
axis contains all nodes, in the same document or document fragment as the context node, that
are before the context node in document order, excluding any ancestors and
excluding attribute nodes and namespace nodes
the attribute
axis contains the attributes of the context node; the axis will be
empty unless the context node is an element
the namespace
axis contains the namespace nodes of the context node; the axis will be
empty unless the context node is an element
the self
axis contains just the context node itself
the descendant-or-self
axis contains the context node and the descendants of the context
node
the ancestor-or-self
axis contains the context node and the ancestors of the context node;
thus, the ancestor-or-self axis will always include the root node
Axes can be categorized as forward axes and reverse axes. An axis that only ever contains the context node or nodes that are after the context node in document order is a forward axis. An axis that only ever contains the context node or nodes that are before the context node in document order is a reverse axis.
In XPath, the parent
, ancestor
, ancestor-or-self
, preceding
, and preceding-sibling
axes are reverse axes; all other axes are forward axes. The ancestor
, descendant
, following
, preceding
and self
axes partition a document (ignoring attribute and namespace nodes):
they do not overlap and together they contain all the nodes in the
document.
In a sequence of nodes selected by a step, the context positions of the nodes are determined in a way that depends on the axis. If the axis is a forward axis, context positions are assigned to the nodes in document order. If the axis is a reverse axis, context positions are assigned to the nodes in reverse document order. In either case, the first context position is 1.
A node test is a condition that must be true for each node selected by a step. The condition may be based on the kind of the node (element, attribute, text, document, comment, processing instruction, or namespace) or on the name of the node.
[31] | NodeTest | ::= | KindTest | NameTest |
[32] | NameTest | ::= | QName | Wildcard |
[33] | Wildcard | ::= | "*" | <NCName ":" "*"> | <"*" ":" NCName> |
[34] | KindTest | ::= | ProcessingInstructionTest
|
[35] | ProcessingInstructionTest | ::= | <"processing-instruction" "("> StringLiteral? ")" |
[36] | CommentTest | ::= | <"comment" "("> ")" |
[37] | TextTest | ::= | <"text" "("> ")" |
[38] | AnyKindTest | ::= | <"node" "("> ")" |
Every axis has a principal node kind. If an axis can contain elements, then the principal node kind is element; otherwise, it is the kind of nodes that the axis can contain. Thus:
For the attribute axis, the principal node kind is attribute.
For the namespace axis, the principal node kind is namespace.
For all other axes, the principal node kind is element.
A node test that is a QName is true if and only if the
kind of the node is the principal
node kind and the expanded-name of the node is equal to the expanded-name
specified by the QName. For example, child::para
selects the para
element children of the context node; if the context node has no para
children, it selects an empty set of nodes. attribute::abc:href
selects the attribute of the context node with the QName abc:href
; if the context node has no such attribute, it selects an empty set of nodes.
A QName in a node test is expanded into an expanded-name using the in-scope namespaces in the expression context. An unprefixed QName used as a nametest has the namespaceURI associated with the default element namespace in the expression context. It is a static error if the QName has a prefix that does not correspond to any in-scope namespace.
A node test *
is true for any node of the principal node kind. For example, child::*
will select all element children of the context node, and attribute::*
will select all attributes of the context node.
A node test can have the form NCName:*
. In this case, the prefix is expanded in the same way as with a QName,
using the context namespace declarations. It is a static error if there is no
namespace declaration for the prefix in the expression context. The node test
will be true for any node of the principal node kind whose expanded-name has the
namespace URI to which the prefix expands, regardless of the local part of the
name.
A node test can also have the form *:NCName
. In this case, the node test is true for any node of the principal node
kind whose local name matches the given NCName, regardless of its
namespace.
The node test text()
is true for any text node. For example, child::text()
will select the text node children of the context node. Similarly, the
node test comment()
is true for any comment node, and the node test processing-instruction()
is true for any processing instruction. The processing-instruction()
test may have an argument that is a StringLiteral; in this
case, it is true for any processing instruction whose target application is equal to the
value of the StringLiteral.
A node test node()
is true for any node whatsoever.
Note:
In order to be consistent with QName in XML, whitespace is not allowed in the Wildcard production. For instance "prefix:*" is allowed, but "prefix : *" is not allowed.
[43] | Predicates | ::= | ("[" Expr "]")* |
A predicate consists of an expression, called a predicate
expression, enclosed in square brackets. A predicate serves to filter a sequence, retaining some items and discarding others. For each item in the sequence to be filtered, the predicate expression is evaluated using an
inner focus derived from that item, as described in
2.1.2 Evaluation Context. The result of the predicate expression is
coerced to a Boolean value, called the predicate truth value, as
described below. Those items for which the predicate truth value is true
are retained, and those for which the predicate truth value is false
are discarded.
The predicate truth value is derived by applying the following rules, in order:
If the value of the predicate expression is an empty sequence, the
predicate truth value is false
.
If the value of the predicate expression is an atomic value of a
numeric type, the predicate truth value is true
if and only if the value of the predicate expression is equal to the context position.
If the value of the predicate expression is an atomic value of type Boolean, the predicate truth value is equal to the value of the predicate expression.
If the value of the predicate expression is a sequence that contains
at least one node, the predicate truth value is true
. The predicate truth value in this case does not depend on
the content of the node(s).
In any other case, a type exception is raised.
Here are some examples of steps that contain predicates:
This example selects the second "chapter" element that is a child of the context node:
child::chapter[2]
This example selects all the descendants of the context node whose name is "toy" and whose "color" attribute has the value "red":
descendant::toy[attribute::color = "red"]
This example selects all the "employee" children of the context node that have a "secretary" subelement:
child::employee[secretary]
A predicate can also be used with a primary expression that is not a forward or reverse step, as illustrated in the following example:
List all the integers from 1 to 100 that are divisible by 5. (See 3.3.1 Constructing Sequences for an explanation of the to
operator.)
(1 to 100)[. mod 5 eq 0]
This section provides a number of examples of path expressions in which the axis is explicitly specified in each step. The syntax used in these examples is called the unabbreviated syntax. In many common cases, it is possible to write path expressions more concisely using an abbreviated syntax, as explained in 3.2.4 Abbreviated Syntax.
child::para
selects
the para
element children of the context node
child::*
selects all element children of the context node
child::text()
selects all text node children of the context node
child::node()
selects all the children of the context node, whatever their node
type
attribute::name
selects the name
attribute of the context node
attribute::*
selects all the attributes of the context node
descendant::para
selects the para
element descendants of the context node
ancestor::div
selects all div
ancestors of the context node
ancestor-or-self::div
selects the div
ancestors of the context node and, if the context node is a div
element, the context node as well
descendant-or-self::para
selects the para
element descendants of the context node and, if the context node is a para
element, the context node as well
self::para
selects the context node if it is a para
element, and otherwise selects nothing
child::chapter/descendant::para
selects the para
element
descendants of the chapter
element children of the context node
child::*/child::para
selects all para
grandchildren of the context node
/
selects the root of the node hierarchy that contains the context node
/descendant::para
selects all the para
elements in the same document as the context node
/descendant::list/child::member
selects all
the member
elements that have an list
parent and that are in the same document as the context node
child::para[xf:position() = 1]
selects the first para
child of the context node
child::para[xf:position() = xf:last()]
selects the last para
child of the context node
child::para[xf:position() = xf:last()-1]
selects the last but one para
child of the context node
child::para[xf:position() > 1]
selects all the para
children of the context node other than the first para
child of the context node
following-sibling::chapter[xf:position() = 1]
selects the next chapter
sibling of the context node
preceding-sibling::chapter[xf:position() = 1]
selects the previous chapter
sibling of the context node
/descendant::figure[xf:position() = 42]
selects the forty-second figure
element in the document
/child::doc/child::chapter[xf:position() = 5]/child::section[xf:position() = 2]
selects the
second section
of the fifth chapter
of the doc
document element
child::para[attribute::type="warning"]
selects
all para
children of the context node that have a type
attribute with value warning
child::para[attribute::type='warning'][xf:position() = 5]
selects the fifth para
child of the context node that has a type
attribute with value warning
child::para[xf:position() = 5][attribute::type="warning"]
selects the fifth para
child of the context node if that child has a type
attribute with value warning
child::chapter[child::title='Introduction']
selects the chapter
children of the context node that have one or more title
children with string-value equal to Introduction
child::chapter[child::title]
selects the chapter
children of the context node that have one or more title
children
child::*[self::chapter or self::appendix]
selects the chapter
and appendix
children of the context node
child::*[self::chapter or
self::appendix][xf:position() = xf:last()]
selects the
last chapter
or appendix
child of the context node
[41] | AbbreviatedForwardStep | ::= | "." | ("@" NameTest) | NodeTest |
[42] | AbbreviatedReverseStep | ::= | ".." |
The abbreviated syntax permits the following abbreviations:
The most important abbreviation is that child::
can be omitted from a step. In effect, child
is the default axis. For example, a path expression section/para
is short for child::section/child::para
.
There is also an abbreviation for
attributes: attribute::
can be
abbreviated by @
. For example, a path expression para[@type="warning"]
is short
for child::para[attribute::type="warning"]
and
so selects para
children with a type
attribute with value
equal to warning
.
//
is short
for /descendant-or-self::node()/
. For example, //para
is short for /descendant-or-self::node()/child::para
and so will select any para
element in the document (even a para
element that is a document element will be selected
by //para
since
the document element node is a child of the root node); div1//para
is
short for div1/descendant-or-self::node()/child::para
and so will select all para
descendants of div1
children.
Note that the path expression //para[1]
does not mean the same as the path
expression /descendant::para[1]
. The latter selects the first descendant para
element; the former
selects all descendant para
elements that are the first para
children of their parents.
A step consisting
of .
returns the context item. This is particularly useful in conjunction with //
. For example, the path
expression .//para
returns all para
descendant elements of the context node.
A step consisting
of ..
is short
for parent::node()
. For example, ../title
is short for parent::node()/child::title
and so will select the title
children of the parent of the context node.
Here are some examples of path expressions that use the abbreviated syntax:
para
selects the para
element children of the context node
*
selects all element children of the context node
text()
selects all text node children of the context node
@name
selects
the name
attribute of the context node
@*
selects all the attributes of the context node
para[1]
selects the first para
child of the context node
para[xf:last()]
selects the last para
child of the context node
*/para
selects
all para
grandchildren of the context node
/doc/chapter[5]/section[2]
selects the second section
of the fifth chapter
of the doc
chapter//para
selects the para
element descendants of the chapter
element children of the context node
//para
selects all
the para
descendants of the document root and thus selects all para
elements in the same document as the context node
//list/member
selects all the member
elements in the same document as the context node that have an list
parent
.
selects the context node
.//para
selects
the para
element descendants of the context node
..
selects the parent of the context node
../@lang
selects
the lang
attribute of the parent of the context node
para[@type="warning"]
selects all para
children of the context node that have a type
attribute with value warning
para[@type="warning"][5]
selects the fifth para
child of the context node that has a type
attribute with value warning
para[5][@type="warning"]
selects the fifth para
child of the context node if that child has a type
attribute with value warning
chapter[title="Introduction"]
selects the chapter
children of the context node that have one
or more title
children with string-value equal to Introduction
chapter[title]
selects the chapter
children of the context node that have one or more title
children
employee[@secretary and @assistant]
selects all
the employee
children of the context node that have both a secretary
attribute and
an assistant
attribute
book/(chapter|appendix)/section
selects
every section
element that has a parent that is either a chapter
or an appendix
element, that in turn is a child of a book
element that is a child of the context node.
book/xf:id(publisher)/name
returns the same result as xf:id(book/publisher)/name
.
XPath supports operators to construct and combine sequences. A sequence is an ordered collection of zero or more items. An item may be an atomic value or a node. An item is identical to a sequence of length one containing that item. Sequences are never nested--for example, combining the values 1, (2, 3), and ( ) into a single sequence results in the sequence (1, 2, 3).
[2] | ExprSequence | ::= | Expr ("," Expr)* |
[11] | RangeExpr | ::= | AdditiveExpr ( "to" AdditiveExpr )* |
One way to construct a sequence is by using the comma operator, which evaluates each of its operands and concatenates the resulting values, in order, into a single result sequence.
An ExprSequence is not an expression in its own right, and in general it must be enclosed in parentheses when used in a context where an expression is expected. Empty parentheses can be used to denote an empty sequence.
A sequence may contain duplicate values or nodes, but a sequence is never an item in another sequence. When a new sequence is created by concatenating two or more input sequences, the new sequence contains all the items of the input sequences and its length is the sum of the lengths of the input sequences.
Here are some examples of expressions that construct sequences:
This expression is a sequence of five integers:
(10, 1, 2, 3, 4)
This expression constructs one sequence from the sequences 10, (1, 2), the empty sequence (), and (3, 4):
(10, (1, 2), (), (3, 4))
It evaluates to the sequence:
10, 1, 2, 3, 4
This expression contains
all salary
children of the context node followed by all bonus
children:
(salary, bonus)
Assuming that $price
is bound to
the value 10.50
, this expression:
($price, $price)
evaluates to the sequence
10.50, 10.50
A RangeExpr can be used to construct a sequence of consecutive
integers. The to
operator takes two operands, both of which have a required type of
integer. A sequence is constructed containing the two integer operands and
every integer between the two operands. If the first operand is less than the
second, the sequence is in increasing order, otherwise it is in decreasing
order.
This example uses a range expression as one operand in constructing a sequence:
(10, 1 to 4)
It evaluates to the sequence:
10, 1, 2, 3, 4
This example constructs a sequence of length one:
10 to 10
It evaluates to a sequence consisting of the single integer 10
.
[14] | UnionExpr | ::= | IntersectExceptExpr ( ("union" | "|") IntersectExceptExpr )* |
[15] | IntersectExceptExpr | ::= | UnaryExpr ( ("intersect" | "except") UnaryExpr )* |
XPath provides several operators for combining sequences of
nodes. The union
and |
operators are equivalent. They take two node sequences as operands and
return a sequence containing all the nodes that occur in either of the
operands. The intersect
operator takes two node sequences as operands and returns a sequence
containing all the nodes that occur in both operands.
The except
operator takes two node sequences as operands and returns a sequence
containing all the nodes that occur in the first operand but not in the second
operand. All of these operators return their result sequences in document order
without duplicates based on node identity. If an operand
of union
, intersect
, or except
contains an item that is not a node, a dynamic error is raised.
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 $seq1
is bound to a sequence containing A and B, $seq2
is also bound to a sequence containing A and B, and $seq3
is bound to a sequence containing B and C. Then:
$seq1 union $seq1
evaluates to a sequence containing A and B.
$seq2 union $seq3
evaluates to a sequence containing A, B, and C.
$seq1 intersect $seq1
evaluates to a sequence containing A and B.
$seq2 intersect $seq3
evaluates to a sequence containing B only.
$seq1 except $seq2
evaluates to the empty sequence.
$seq2 except $seq3
evaluates to a sequence containing A only.
In addition to the sequence operators described here,[XQuery 1.0 and XPath 2.0 Functions and Operators] includes functions for indexed access to items or sub-sequences of a sequence, for indexed insertion or removal of items in a sequence, and for removing duplicate values or nodes from a sequence.
XPath provides arithmetic operators for addition, subtraction, multiplication, division, and modulus, in their usual binary and unary forms.
[12] | AdditiveExpr | ::= | MultiplicativeExpr ( ("+" | "-") MultiplicativeExpr )* |
[13] | MultiplicativeExpr | ::= | UnionExpr ( ("*" | "div" | "idiv" | "mod") UnionExpr )* |
[16] | UnaryExpr | ::= | ("-" | "+")* ValueExpr |
[17] | ValueExpr | ::= | ValidateExpr | CastExpr | PathExpr |
The binary subtraction operator must be preceded by whitespace if it could otherwise be interpreted as part of the previous token. For example, a-b
will be interpreted as a name, but a - b
will be interpreted as an arithmetic operation.
An arithmetic expression is evaluated by applying the following rules, in order, until an error is raised or a value is computed:
Atomization is applied to each operand, resulting in a single atomic value or an empty sequence for each operand.
If either operand is an empty sequence, the result of the operation is an empty sequence.
If an operand has the type xs:anySimpleType
, it is cast to xs:double
. If the cast fails, a dynamic error is raised.
If the two operands have different types, and these types can be promoted to
a common type using the promotion rules in B.1 Type Promotion, the
operands are both promoted to their least common type. For example, if the first operand is of type hatsize
which is derived from xs:decimal
, and the second operand is of type shoesize
which is derived from xs:integer
, then both operands are promoted to the type xs:decimal
.
If the operand type(s) are valid for the given operator, the operator is applied to the operand(s), resulting in an atomic value or a dynamic error (for example, an error might result from dividing by zero.) The combinations of atomic types that are accepted by the various arithmetic operators, and their respective result types, are listed in B.2 Operator Mapping. If the operand type(s) are not valid for the given operator, a type exception is raised.
XPath supports two division operators named div
and idiv
. The div
operator accepts operands of any numeric types. The result of the div
operator is the least common type of its operands; however, if both operands are of type xs:integer
, div
returns a result of type xs:double
. The idiv
operator, on the other hand, requires its operands to be of type xs:integer
and returns a result of type xs:integer
, rounded toward zero.
Here are some examples of arithmetic expressions:
The first expression below returns -1.5E0
, and the second expressions returns -1
:
-3 div 2 -3 idiv 2
Subtraction of two date values results in a value of type xf: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:
-($bellcost + $whistlecost)
Comparison expressions allow two values to be compared. XPath provides four kinds of comparison expressions, called value comparisons, general comparisons, node comparisons, and order comparisons.
[10] | ComparisonExpr | ::= | RangeExpr ( (ValueComp
|
[25] | ValueComp | ::= | "eq" | "ne" | "lt" | "le" | "gt" | "ge" |
[24] | GeneralComp | ::= | "=" | "!=" | "<" | "<=" | ">" | ">=" |
[26] | NodeComp | ::= | "is" | "isnot" |
[27] | OrderComp | ::= | "<<" | ">>" |
When an XPath expression is written within an XML document, the XML escaping rules for special characters must be followed; thus "<
" must be written as "<
".
Value comparisons are intended for comparing single values. The result of a value comparison is defined by applying the following rules, in order:
Atomization is applied to each operand, resulting in a single atomic value or an empty sequence for each operand.
If either operand is an empty sequence, the result is an empty sequence.
If either operand has the type xs:anySimpleType
, that operand is cast to a required type,
which is determined as follows:
If the type of the other operand is numeric, the required type is
xs:double
.
If the type of the other operand is xs:anySimpleType
, the required type is xs:string
.
Otherwise, the required type is the type of the other operand.
If the cast fails, a dynamic error is raised.
If the value comparison has two numeric operands of different types, one of
the operands is promoted to the type of the other operand, following the
promotion rules in B.1 Type Promotion. For example, a value of type xs:integer
can be promoted to xs:decimal
, and a value of
type xs:decimal
can be promoted to xs:double
.
The result of the comparison is true
if the value of the first operand is (equal, not equal, less than, less
than or equal, greater than, greater than or equal) to the value of the second
operand; otherwise the result of the comparison is false
. B.2 Operator Mapping describes which combinations of atomic types
are comparable, and how comparisons are performed on values of various types.
If the value of the first operand is not comparable with the value of the
second operand, a type exception is raised.
Here are some examples of value comparisons:
The following comparison is true only if $book1
has a single author
subelement and its value is "Kennedy":
$book1/author eq "Kennedy"
Ed. Note: The current definitions of the value comparison operators are not transitive. The Working Group is discussing making value comparisons transitive by removing some implicit casts from value comparisons and adding them to general comparisons.
General comparisons are defined by adding existential semantics to value
comparisons. The operands of a general comparison may be sequences of any
length. The result of a general comparison is
always true
or false
.
The general comparison A = B
is true
for sequences A
and B
if the value comparison a eq b
is true
for some item a
in A
and some item b
in B
. Otherwise, A = B
is false
.
Similarly:
A != B
is true
if and only if a ne b
is true
for some a
in A
and some b
in B
.
A < B
is true
if and only if a lt b
is true
for
some a
in A
and some b
in B
.
A <= B
is true
if and only if a le b
is true
for some a
in A
and some b
in B
.
A > B
is true
if and only if a gt b
is true
for some a
in A
and some b
in B
.
A >= B
is true
if and only if a ge b
is true
for some a
in A
and some b
in B
.
Here is an example of a general comparison:
The following comparison is true if the value of any author
subelement of $book1
is "Kennedy":
$book1/author = "Kennedy"
The result of a node comparison is defined by applying the following rules, in order:
Each operand must be either a single node or an empty sequence; otherwise a dynamic error is raised.
If either operand is an empty sequence, the result of the comparison is an empty sequence.
A comparison with the is
operator is true
if the two operands are nodes that have the same identity; otherwise it
is false
. A comparison with the isnot
operator is true
if the two operands are nodes that have different identities; otherwise
it is false
. See [XQuery 1.0 and XPath 2.0 Data Model] for a discussion of node identity.
Use of the is
operator is illustrated below.
The following comparison is true only if the left and right sides each evaluate to exactly the same single node:
//book[isbn="1558604820"] is //book[call="QA76.9 C3845"]
The result of an order comparison is defined by applying the following rules, in order:
Both operands must be either a single node or an empty sequence; otherwise a dynamic error is raised.
If either operand is an empty sequence, the result of the comparison is an empty sequence.
A comparison with the <<
operator returns true
if the first operand node is earlier than the second operand node in
document order; otherwise it returns false
.
A comparison with the >>
operator returns true
if the first operand node is later than the second operand node in
document order; otherwise it returns false
.
Here is an example of an order comparison:
The following comparison is true only if the node identified by the left side occurs before the node identified by the right side in document order:
//purchase[parcel="28-451"] << //sale[parcel="33-870"]
A logical expression is either an and-expression or
an or-expression. If a logical expression does not raise an error, its value is always one
of the boolean values true
or false
.
[4] | OrExpr | ::= | AndExpr ( "or" AndExpr )* |
[5] | AndExpr | ::= | ForExpr ( "and" ForExpr )* |
The first step in evaluating a logical expression is to find the effective boolean value of each of its operands (see 2.4.3.2 Effective Boolean Value).
The value of an and-expression is determined by the effective boolean values (EBV's) of its operands. If an error is raised during computation of one of the effective boolean values, an and-expression may raise a dynamic error, as shown in the following table:
AND: | EBV2 = true | EBV2 = false | error in EBV2 |
EBV1 = true | true | false | error |
EBV1 = false | false | false | false or error |
error in EBV1 | error | false or error | error |
The value of an or-expression is determined by the effective boolean values (EBV's) of its operands. If an error is raised during computation of one of the effective boolean values, an or-expression may raise a dynamic error, as shown in the following table:
OR: | EBV2 = true | EBV2 = false | error in EBV2 |
EBV1 = true | true | true | true or error |
EBV1 = false | true | false | error |
error in EBV1 | true or error | error | error |
The order in which the operands of a logical expression are evaluated is implementation-dependent. The tables above are defined in such a way that an or-expression can return true
if the first expression evaluated is true, and it can raise an error if evaluation of the first expression raises an error. Similarly, an and-expression can return false
if the first expression evaluated is false, and it can raise an error if evaluation of the first expression raises an error. As a result of these rules, a logical expression is not deterministic in the presence of errors, as illustrated in the examples below.
Here are some examples of logical expressions:
The following expressions return true
:
1 eq 1 and 2 eq 2
1 eq 1 or 2 eq 3
The following expression may return either false
or raise a dynamic error:
1 eq 2 and 3 idiv 0 = 1
The following expression may return either true
or raise a 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, XPath provides a function named not
that takes a general sequence as parameter and returns a boolean value.
The not
function reduces its parameter to an effective boolean value. It then
returns true
if the effective boolean value of its parameter is false
, and false
if the effective boolean value of its parameter
is true
. If an error is encountered in finding the effective boolean value of its operand, not
raises a dynamic error. The not
function is described in [XQuery 1.0 and XPath 2.0 Functions and Operators].
XPath provides a For expression for iteration. This kind of expression is often useful for computing joins between two or more documents and for restructuring data.
[6] | ForExpr | ::= | (ForClause "return")* QuantifiedExpr |
[21] | ForClause | ::= | <"for" "$"> VarName "in" Expr ("," "$" VarName "in" Expr)* |
The clauses of a For Expression are interpreted as follows:
A for
clause associates one or more variables with expressions, creating
tuples of variable bindings drawn from the Cartesian product of the sequences
of values to which the expressions evaluate. The variable binding tuples are
generated as an ordered sequence as described below.
The return
clause contains an expression that is used to construct the result of
the For expression. The return
clause is invoked once for every tuple generated by the for
clause. The expression in the return
clause is evaluated once for every invocation, and the result of the
For expression is an ordered sequence containing the results of these
invocations.
A variable name may not be used before it is bound, nor may it be used in
the expression to which it is bound. Any variable bound in a for
clause is in scope until the end of the For expression
in which it is bound. If the variable name used in the binding was already
bound in the current scope, the variable name refers to the newly bound
variable until that variable goes out of scope. At this point, the variable
name again refers to the variable of the prior binding.
If a for
clause contains multiple expressions, the tuples of variable bindings
are drawn from the Cartesian product of the sequences returned by the
expressions. The ordering of the tuples is governed by the ordering of the
sequences from which they were formed, working from left to right.
The following expression illustrates how tuples are generated from the
Cartesian product of expressions in a for
clause.
for $i in (1, 2), $j in (3, 4) return ($i, $j)
Here is the result of the above expression (the order is significant). Note that the result is presented as a sequence of numbers.
(1, 3, 1, 4, 2, 3, 2, 4)
The following example evaluates a bibliography document to create a sequence that contains each author's first and last name, followed by the titles of the books with that author. The example is based on the following input:
<bib> <book> <title>TCP/IP Illustrated</title> <author> W. Stevens </author> <publisher>Addison-Wesley</publisher> </book> <book> <title>Advanced Programming in the Unix environment</title> <author> W. Stevens </author> <publisher>Addison-Wesley</publisher> </book> </bib>
The author list is a list of authors, where each author element contains the
name of the author and a list of books written by that author. If an author has
written more than one book, that author's name will occur more than once in the
bibliography, but we want each author's name to occur only once in the author
list. We will remove duplicates using the distinct-values
function.
The distinct-values
function takes a sequence of nodes or values as input, and returns a
sequence in which duplicates have been removed by value. The order of this
sequence is not significant. Two elements are considered to have duplicate
values if their names, attributes, and normalized content are equal.
The following expression is used to transform the input bibliography into an author list:
for $a in distinct-values(//author) return ($a, for $b in //book[author = $a] return $b/title)
The result of the above expression consists of the following sequence of elements:
<author>W. Stevens</author>, <title>TCP/IP Illustrated</title>, <title>Advanced Programming in the Unix environment</title>
Note:
Query writers should use caution when combining For expressions with
path expressions. It is important to remember that path expressions always
return their results in document order, whereas the order of the results of a
For expression are determined by the orderings of the sequences in the for
clause.
XPath supports a conditional expression based on the keywords if
, then
, and else
.
[8] | IfExpr | ::= | (<"if" "("> Expr ")" "then" Expr "else")* InstanceofExpr |
The expression following the if
keyword is called the test expression, and the expressions
following the then
and else
keywords are called the then-expression and else-expression, respectively.
The first step in processing a conditional expression is to find the effective boolean value of the test expression, as defined in 2.4.3.2 Effective Boolean Value.
The value of a conditional expression is defined as follows: If the
effective boolean value of the test expression is true
, the value of the then-expression is returned. If the
effective boolean value of the test expression is false
, the value of the else-expression is returned.
Conditional expressions have a special rule for propagating dynamic errors. If the effective value of the test expression is true
, the conditional expression ignores (does not raise) any dynamic errors encountered in the else-expression. In this case, since the else-expression can have no observable effect, it need not be evaluated. Similarly, if the effective value of the test expression is false
, the conditional expression ignores any dynamic errors encountered in the then-expression, and the then-expression need not be evaluated.
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
, independently of its value:
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
or false
.
[7] | QuantifiedExpr | ::= | ((<"some" "$"> | <"every" "$">) VarName "in" Expr ("," "$" VarName "in" Expr)* "satisfies")* IfExpr |
A quantified expression begins with
a quantifier, which is the keyword some
or every
, followed by one or more in-clauses that are used to bind variables,
followed by the keyword satisfies
and a test expression. Each in-clause associates a variable with an
expression that returns a sequence of values. As in the case of a for-clause in
a For expression, the in-clauses generate tuples of variable bindings, using
values drawn from the Cartesian product of the sequences returned by the
binding expressions. Conceptually, the test expression is evaluated for each
tuple of variable bindings. Results depend on the effective boolean values of the test expressions, as defined in 2.4.3.2 Effective Boolean Value. The value of the quantified expression is defined
by the following rules:
If the quantifier is some
, the quantified expression is true
if at least one evaluation of the test expression has the effective
boolean value true
; otherwise the quantified expression is false
. This rule implies that, if the in-clauses generate zero binding
tuples, the value of the quantified expression is false
.
If the quantifier is every
, the quantified expression is true
if every evaluation of the test expression has the effective
boolean value true
; otherwise the quantified expression is false
. This rule implies that, if the in-clauses generate zero binding
tuples, the value of the quantified
expression is true
.
The order in which test expressions are evaluated for the various binding
tuples is implementation-defined. If the quantifier
is some
, an implementation may
return true
as soon as it finds one binding tuple for which the test expression has
an effective Boolean value of true
, and it may raise a dynamic error as soon as it finds one binding tuple for
which the test expression raises an error. Similarly, if the quantifier is every
, an implementation may return false
as soon as it finds one binding tuple for which the test expression has
an effective Boolean value of false
, and it may raise a dynamic error as soon as it finds one binding tuple for
which the test expression raises an error. As a result of these rules, the
value of a quantified expression is not deterministic in the presence of
errors, as illustrated in the examples below.
Here are some examples of quantified expressions:
This expression is true
if every part
element has a discounted
attribute (regardless of the values of these attributes):
every $part in //part satisfies $part/@discounted
This expression is true
if at least
one employee
element satisfies the given comparison expression:
some $emp in //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)
and (2, 3, 4)
. The expression beginning with some
evaluates to true
, and the expression beginning with every
evaluates to 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
or raise a dynamic error, since its test expression returns true
for one variable binding
and raises an error for another:
some $x in (1, 2, "cat") satisfies $x * 2 = 4
This quantified expression may either return false
or raise a dynamic error, since its test expression returns false
for one variable binding and raises an error for another:
every $x in (1, 2, "cat") satisfies $x * 2 = 4
In addition to their use in function parameters, SequenceTypes occur explicitly in instance of
, cast
, and treat
expressions.
[9] | InstanceofExpr | ::= | ComparisonExpr ( <"instance" "of"> SequenceType )? |
The boolean
operator instance of
returns true
if the value of its first operand matches the type named in its second
operand, according to the rules for SequenceType Matching; otherwise it returns false
. For example:
5 instance of xs:integer
This example returns true
because the given value is an instance of the given type.
. instance of element
This example returns true
if the context item is an element node.
[23] | CastExpr | ::= | (<"cast" "as"> | <"treat" "as">) SequenceType ParenthesizedExpr |
Occasionally it is necessary to convert a value to a specific datatype. For this purpose, XPath provides a cast
expression that creates a new value of a specific type based on an existing value. A cast
expression takes two operands: an input expression and a SequenceType, called the target type. The cast
expression first performs atomization on its input expression, resulting in a single atomic input value or the empty sequence. If the input value is the empty sequence, the cast
expression returns an empty sequence. Otherwise, the cast
expression creates a new instance of the target type that has the same lexical representation as the input value. The type of the input value is called the input type. cast
is supported only for certain combinations of input type and target type, as listed below. For the purpose of these rules, we use the terms subtype and supertype in the following sense: if type B is derived from type A by restriction, then B is a subtype of A, and A is a supertype of B.
cast
is supported for the combinations of input type and target type listed in [XQuery 1.0 and XPath 2.0 Functions and Operators]. For each of these combinations, both the input type and the target type are built-in schema types. For example, a value of type xs:string
can be cast into the type xs:decimal
.
For every built-in type T that is defined in [XML Schema], a constructor function is provided whose name is the same as T and whose semantics are the same as a cast expression with target type T. For example, the function call xs:decimal($stringvalue)
is equivalent to the expression cast as xs:decimal($stringvalue)
. If the argument to a constructor function is a literal, the result of the function may be computed statically, and an error encountered in this process may be reported as a static error. Constructor functions are described in more detail in [XQuery 1.0 and XPath 2.0 Functions and Operators].
cast
is supported if the input type is a derived atomic type and the target type is a supertype of the input type. For example, if shoesize
is derived by restriction from xs:integer
, a value of type shoesize
can be cast into the type xs:integer
.
cast
is supported if the target type is a derived atomic type and the input type is xs:string
, xs:anySimpleType
, or a supertype of the target type. If the input type is xs:string
or xs:anySimpleType
, its string value must be in the lexical space of the target type, and it is converted to the target type using the schema-defined rules for the target type. If the input type is a supertype of the target type, its value is mapped unchanged into the value space of the target type, and it is checked for conformance to all the facets of the target type (checking of a "pattern" facet may require generating a canonical lexical representation of the input value.)
For any combination of input type and target type that is not in the above list, a cast
expression raises a static error.
If it is not possible to cast the input value into the value space of the target type, a dynamic error is raised. This includes the case when any facet of the target type is not satisfied. For example, cast as xs:integer($x)
raises a dynamic error if the type of $x
is xs:decimal
and its value is 4.99
because this value cannot be represented with zero fractional digits.
In addition to cast
, XPath provides a type-checking expression called treat
, which takes two operands: an expression and a SequenceType. Unlike cast
, however, treat
does not change the type or value of its operand. Instead, the purpose of treat
is to ensure that an expression has an expected type at run-time.
The semantics of treat as type1 (expr2)
are as follows:
During static analysis (if the Static Typing Feature is implemented):
type1
must be a subtype of the static type of expr2
, using the definition of subtype in [XQuery 1.0 Formal Semantics]--otherwise, a static type error is raised. The static type of the treat
expression is type1
. This enables the expression to be used as an argument of a function that
requires a parameter of type1
.
During expression evaluation (at "run-time"):
If expr2
matches type1
, using the SequenceType Matching rules in 2.4.2 SequenceType, the treat
expression returns the value of expr2
; otherwise, it raises a dynamic error. If the value of expr2
is returned, its identity is preserved. The treat
expression ensures that the value of its expression operand conforms to the expected type at run-time.
Example:
treat as element of type USAddress ($myaddress)
The static type of $myaddress
may be element of type Address
, a less specific type than element of type USAddress
. However, at run-time, the value of $myaddress
must match the type element of type USAddress
using SequenceType Matching rules; otherwise a dynamic error is raised.
[22] | ValidateExpr | ::= | "validate" SchemaContext? "{" Expr "}" |
Ed. Note: Curly braces in this syntax may cause problems if this expression is embedded in XSLT--see Issue 267.)
A validate
expression validates its argument with respect to the in-scope schema definitions, using the schema validation process described in [XML Schema]. The argument of a validate
expression may be any sequence of elements. Validation replaces element and attribute nodes with new nodes that have their own identity and that contain type
annotations and defaults created by the validation process. If a hierarchy of nodes is validated by a validate
expression, the hierarchical relationship among these nodes will be preserved among the nodes created by the validation process.
To allow locally declared elements and attributes to be validated, a schema context may optionally be specified. If no context is specified, all top-level names in the material to be validated are treated as global names.
The following example validates the value that is bound to a variable:
validate { $x }
The validate
expression invokes the full schema validation process, except that identity
constraints, as defined in section 3.11.4 of [XML Schema]
Part 1, are not applied. All facets of simple types are checked, and
default values are supplied as defined in the XML Schema
specification.
Validating an expression is equivalent to the following steps:
The value of the expression is converted from the Data Model to an XML Information Set (see [XML Infoset].) This step is equivalent to serializing the value of the expression in XML form and then parsing it to produce an Information Set.
The Information Set produced in the previous step is validated according to the rules in [XML Schema], using the in-scope schema definitions. The result of this step is a Post-Schema Validation Infoset (PSVI). If the validation process is not successful, a dynamic type error is raised.
The PSVI produced in the previous step is converted back into the Data Model by the mapping described in [XQuery 1.0 and XPath 2.0 Data Model].
A validate
expression may contain a SchemaContext that is used in validating locally declared elements and attributes. When
a schema context is supplied, all element QNames are interpreted as they
would be if found in that context in an XML document. If the schema context begins with a QName, the QName is interpreted as the name of a globally
declared element; however, if the schema context begins with the keyword type
, the first QName is interpreted as the name of a globally declared type. The steps inside the schema context trace a path relative to the globally declared element or type, as illustrated in the following examples, which are based on schemas defined in [XML Schema], Part 0:
Suppose that $x
is bound to a shipTo
element. Then validate in po:purchaseOrder {$x}
validates the value of $x
in the context of the global element declaration po:purchaseOrder
.
Suppose that $y
is bound to a productName
element. Then validate in po:purchaseOrder/items/item {$y}
validates the value of $y
in the context of an item
element, inside an items
element, inside the global element declaration po:purchaseOrder
.
Suppose that $z
is bound to a zip
element. Then validate in type po:USAddress {$z}
validates the value of $z
in the context of the global type declaration po:USAddress
.
A character is an atomic unit of text as specified by ISO/IEC 10646 [ISO/IEC 10646] (see also [ISO/IEC 10646-2000]). Legal characters are tab, carriage return, line feed, and the legal characters of Unicode and ISO/IEC 10646, as long as these characters are legal XML characters as defined in the [XML] recommendation.
A lexical pattern is a rule that describes how a sequence of characters can match a grammar unit. A lexeme is the smallest meaningful unit in the grammar that has syntactic interpretation. A token is a symbol that matches lexemes, and is the output of the lexical analyzer. A token symbol is the symbolic name given to that token. A single token may be composed of one or more lexemes. If there is more than one lexeme, they may be separated by whitespace or punctuation. For instance, the token AxisDescendantOrSelf has two lexemes, "descendant-or-self" and "::".
Pattern | Lexeme(s) | Token Names (for example) |
---|---|---|
"or" | "or" | Or |
"=" | "=" | Equals |
(Prefix ':')? LocalPart | "p:foo" | QName |
<"descendant-or-self" "::"> | "descendant-or-self" | AxisDescendantOrSelf |
"::" |
When patterns are simple string matches, the strings are embedded directly into the BNF. In other cases, token symbols are used when the pattern is a more complex regular expression (the major cases of these are NCName, QName, and Number and String literals). It is up to an implementation to decide on the exact tokenization strategy, which may be different depending on the parser construction. For instance, an implementation may decide that a token named For
is composed of only "for", or may decide that it is composed of ("for" "("). In the first case the implementation may decide to use lexical lookahead to distinguish the "for" lexeme from a QName that has the lexeme "for". In the second case, the implementation may decide to combine the two lexemes into a single "long" token. In either case, the end grammatical result will be the same. Lexemes that must be described by lexical lookahead are delimited with the tokens that it must look ahead to, in order to be recoginized, by "<" and ">".
This grammar implies lexical states, which are lexical constraints on the tokenization process based on grammatical positioning. The exact structure of these states is left to the implementation, but the normative rules for calculating these states are given in the A.1.2 Lexical Rules section.
When tokenizing, the longest possible match that is valid in the current lexical state is prefered .
For readability, Whitespace may be used in most expressions even though not explicitly allowed by the grammar: Whitespace may be freely added between lexemes, except a few cases where whitespace is needed to disambiguate the token. For instance, in XML, "-" is a valid character in an element or attribute name. When used as an operator after the characters of a name, it must be separated from the name, e.g. by using whitespace or parentheses.
All keywords are case sensitive.
Ed. Note: Since currently ExprComments are specified at the lexical level, I leave it as an editorial issue as to how to describe this, or whether to constrain where ExprComments are allowed so they can be described by the BNF. (I would be in favor of this. -sb)
Character Classes
The following basic tokens are defined in [XML].
Identifiers
The following identifier components are defined in [XML Names].
String Literals and Numbers
[147] | IntegerLiteral | ::= | Digits |
[148] | DecimalLiteral | ::= | ("." Digits) | (Digits "." [0-9]*) |
[149] | DoubleLiteral | ::= | (("." Digits) | (Digits ("." [0-9]*)?)) ("e" | "E") ("+" | "-")? Digits |
[162] | StringLiteral | ::= | ('"' (('"' '"') | [^"])* '"') | ("'" (("'" "'") | [^'])* "'") |
Comments
Comments are lexical constructs only, and do not affect the processing of an expression. [Ed. Note: Need to expand on where, exactly, comments are allowed.]
[59] | ExprComment | ::= | "{--" [^}]* "--}" |
Defined Tokens
The following is a list of defined tokens for the XPath grammar.
[59] | S | ::= | WhitespaceChar+ |
[105] | Nmstart | ::= | Letter | "_" |
[106] | Nmchar | ::= | Letter | CombiningChar | Extender | Digit | "." | "-" | "_" |
[145] | Digits | ::= | [0-9]+ |
[162] | URLLiteral | ::= | ('"' (('"' '"') | [^"])* '"') | ("'" (("'" "'") | [^'])* "'") |
[166] | VarName | ::= | QName |
[167] | FuncName | ::= | (Prefix ":")? LocalPart |
[173] | Char | ::= | ([#x0009] | [#x000D] | [#x000A] | [#x0020-#xFFFD]) |
[174] | WhitespaceChar | ::= | ([#x0009] | [#x000D] | [#x000A] | [#x0020]) |
As discussed above, there are various strategies that can be used by an implementation to disambiguate token symbol choices. Among the choices are lexical look-ahead and look-behind, a two-pass lexical evaluation, and a single recursive descent lexical evaluation and parse. This specification does not dictate what strategy to use. However, this section does describe normative rules with which these decisions must conform to.
The lexical contexts and transitions between lexical contexts is described in terms of a series of states and transitions between those states. An implementation need not follow this approach in implementing lexer rules, but does need to conform to the results. For instance, instead of using a state automata, an implementation might use lexecal look-behind, or might use a full context-free-grammar parse, or it might make extensive use of parser lookahead (and use a more ambiguous token strategy).
The tables below define the complete lexical rules for XPath. Each table corresponds to a lexical state in which the tokens listed are recognized only in that state. When a given token is recognized in the given state, the transition to the next state is given. In some cases, a transition will "push" the current state or a specific state onto an abstract stack, and will later restore that state by a "pop" when another lexical event occurs. [Ed. Note: pushParenState(...)
, popParenState(...)
, and resetParenStateOrSwitch(...)
are left unexplained for now. Briefly, these are used to maintain the ITEMTYPE
state within a function definition in XQuery, since it is hard to distinguish lexically between a function call and a function definition. Since the lexical state mechanism is shared between XPath and XQuery, these are used in the XPath tables also, even though they are not strictly needed.]
The lexical states have in many cases close connection to the parser productions. However, just because a token is recognized in a certain lexical state, does not mean it will be legal in the parser state.
This state is for patterns that can be recognized in any state.
Pattern | Transition To State |
---|---|
WhitespaceChar
Nmstart Nmchar Digits | (maintain current state) |
This state is for patterns that occur at the beginning of an expression.
Pattern | Transition To State |
---|---|
"?" "[" "+" "-" "empty" | DEFAULT |
"{" | DEFAULT pushState(DEFAULT) |
DEFAULT pushState(DEFAULT) |
|
<"type" QName> "validate" "*" <NCName ":" "*"> <"*" ":" NCName> "." ".." StringLiteral | OPERATOR |
<"of" "type"> "/" "//" <"child" "::"> <"descendant" "::"> <"parent" "::"> <"attribute" "::"> <"self" "::"> <"descendant-or-self" "::"> <"ancestor" "::"> <"following-sibling" "::"> <"preceding-sibling" "::"> <"following" "::"> <"preceding" "::"> <"namespace" "::"> <"ancestor-or-self" "::"> "@" | QNAME |
<"cast" "as"> <"treat" "as"> | ITEMTYPE |
"$" <"for" "$"> <"some" "$"> <"every" "$"> | VARNAME |
"," | resetParenStateOrSwitch(DEFAULT) |
"(" | pushParenState(DEFAULT) |
<"text" "("> <"comment" "("> <"node" "("> <"processing-instruction" "("> | pushParenState(DEFAULT) |
<QName "("> <"if" "("> | pushParenState(DEFAULT) |
")" | popParenState(OPERATOR) |
"}" | popState |
This state is for patterns that are defined for operators.
Pattern | Transition To State |
---|---|
"/" "//" "div" "idiv" "mod" "and" "or" "*" "return" "then" "else" "to" "union" "intersect" "except" "=" "is" "!=" "isnot" "<=" ">=" "<" ">" "|" "<<" ">>" "eq" "ne" "gt" "ge" "lt" "le" "in" "satisfies" "?" "[" "+" "-" "item" "node" "document" "comment" "text" | DEFAULT |
"{" | DEFAULT pushState(DEFAULT) |
<NCName ":" "*"> <"*" ":" NCName> "." ".." StringLiteral | OPERATOR |
<"of" "type"> | QNAME |
<"instance" "of"> | ITEMTYPE |
"$" <"for" "$"> <"some" "$"> <"every" "$"> | VARNAME |
"," | resetParenStateOrSwitch(DEFAULT) |
"(" | pushParenState(DEFAULT) |
")" | popParenState(OPERATOR) |
"}" | popState |
When a qualified name is expected, and it is required to remove ambiguity from patterns that look like keywords, this state is used.
Pattern | Transition To State |
---|---|
"*" <NCName ":" "*"> <"*" ":" NCName> "." ".." | OPERATOR |
"/" "//" <"child" "::"> <"descendant" "::"> <"parent" "::"> <"attribute" "::"> <"self" "::"> <"descendant-or-self" "::"> <"ancestor" "::"> <"following-sibling" "::"> <"preceding-sibling" "::"> <"following" "::"> <"preceding" "::"> <"namespace" "::"> <"ancestor-or-self" "::"> "@" | QNAME |
"$" | VARNAME |
"(" | pushParenState(DEFAULT) |
<"text" "("> <"comment" "("> <"node" "("> <"processing-instruction" "("> | pushParenState(DEFAULT) |
")" | popParenState(OPERATOR) |
This state distinguishes tokens that can occur only inside the ItemType production.
Pattern | Transition To State |
---|---|
"attribute" "element" "node" "document" "comment" "text" "processing-instruction" "item" "untyped" <"atomic" "value"> AtomicType | DEFAULT |
<NCName ":" "*"> <"*" ":" NCName> "." ".." | OPERATOR |
"$" | VARNAME |
")" | popParenState(OPERATOR) |
This state differentiates variable names from qualified names. This allows only the pattern of a QName to be recognized when otherwise ambiguities could occur.
Pattern | Transition To State |
---|---|
VarName
| OPERATOR |
Ed. Note: Note that the "validate" keyword can not be easily distinguished at lexical evaluation time from a QName whose value is "validate". This should be fixed in the future.
The following grammar uses the same Basic EBNF notation as [XML], except that grammar symbols always have initial capital letters. The EBNF contains the lexemes embedded in the productions.
Note:
Note that the Semicolon character is reserved for future use.
Under certain circumstances, an atomic value can be promoted from
one type to another. The promotion rules listed below are used in
basic type conversions (see 2.4.3 Type Conversions) and
during processing of arithmetic expressions (see 3.4 Arithmetic Expressions) and value comparisons (see 3.5.1 Value Comparisons). The rules may be applied transitively. For example, since xs:integer
is promotable to
xs:decimal
and xs:decimal
is promotable to
xs:float
, it follows that xs:integer
is
promotable to xs:float
, without necessarily passing
through the intermediate xs:decimal
type.
The following type promotions are permitted:
A value of type xs:decimal
can be
promoted to the type xs:float
. The result is the xs:float
value that is closest to the original value.
A value of type xs:float
can be promoted to the
type xs:double
. The result is the xs:double
value that is the same as the original value.
A value of a derived
type can be promoted to its base type. The result is the base-type value that is the same as the original value. As an example of this rule, a
value of the derived type xs:integer
can be promoted to
its base type xs:decimal
.
The tables in this section list the combinations of datatypes for which the various operators of XPath are defined. For each valid combination of datatypes, the table indicates the function(s) that are used to implement the operator and the datatype of the result. Definitions of the functions can be found in [XQuery 1.0 and XPath 2.0 Functions and Operators]. Note that in some cases the function does not implement the full semantics of the given operator. For a complete description of each operator (including its behavior for empty sequences or sequences of length greater than one), see the descriptive material in the main part of this document.
In the following tables, the term numeric refers to
the types xs:integer
, xs:decimal
,
xs:float
, and xs:double
. When the result
type of an operator is listed as numeric, it means "same as the
highest type of any input operand, in promotion order." For example,
when invoked with operands of type xs:integer
and
xs:float
, the binary +
operator returns a
result of type xs:float
.
In the following tables,
the term Gregorian refers to the types
xs:gYearMonth
, xs:gYear
,
xs:gMonthDay
, xs:gDay
, and
xs:gMonth
. For binary operators that accept two
Gregorian-type operands, both operands must have the same type (for
example, if one operand is of type xs:gDay
, the other
operand must be of type xs:gDay
.)
Operator | Type(A) | Type(B) | Function | Result type |
---|---|---|---|---|
A + B | numeric | numeric | op:numeric-add(A, B) | numeric |
A + B | xs:date | xf:yearMonthDuration | op:add-yearMonthDuration-to-date(A, B) | xs:date |
A + B | xf:yearMonthDuration | xs:date | op:add-yearMonthDuration-to-date(B, A) | xs:date |
A + B | xs:date | xf:dayTimeDuration | op:add-dayTimeDuration-to-date(A, B) | xs:date |
A + B | xf:dayTimeDuration | xs:date | op:add-dayTimeDuration-to-date(B, A) | xs:date |
A + B | xs:time | xf:dayTimeDuration | op:add-dayTimeDuration-to-time(A, B) | xs:time |
A + B | xf:dayTimeDuration | xs:time | op:add-dayTimeDuration-to-time(B, A) | xs:time |
A + B | xs:datetime | xf:yearMonthDuration | op:add-yearMonthDuration-to-dateTime(A, B) | xs:dateTime |
A + B | xf:yearMonthDuration | xs:datetime | op:add-yearMonthDuration-to-dateTime(B, A) | xs:dateTime |
A + B | xs:datetime | xf:dayTimeDuration | op:add-dayTimeDuration-to-dateTime(A, B) | xs:dateTime |
A + B | xf:dayTimeDuration | xs:datetime | op:add-dayTimeDuration-to-dateTime(B, A) | xs:dateTime |
A + B | xf:yearMonthDuration | xf:yearMonthDuration | op:add-yearMonthDurations(A, B) | xf:yearMonthDuration |
A + B | xf:dayTimeDuration | xf:dayTimeDuration | op:add-dayTimeDurations(A, B) | xf:dayTimeDuration |
A - B | numeric | numeric | op:numeric-subtract(A, B) | numeric |
A - B | xs:date | xs:date | xf:subtract-dates(A, B) | xf:dayTimeDuration |
A - B | xs:date | xf:yearMonthDuration | op:subtract-yearMonthDuration-from-date(A, B) | xs:date |
A - B | xs:date | xf:dayTimeDuration | op:subtract-dayTimeDuration-from-date(A, B) | xs:date |
A - B | xs:time | xs:time | xf:subtract-times(A, B) | xf:dayTimeDuration |
A - B | xs:time | xf:dayTimeDuration | op:subtract-dayTimeDuration-from-time(A, B) | xs:time |
A - B | xs:datetime | xs:datetime | xf:get-dayTimeDuration-from-dateTimes(A, B) | xf:dayTimeDuration |
A - B | xs:datetime | xf:yearMonthDuration | op:subtract-yearMonthDuration-from-dateTime(A, B) | xs:dateTime |
A - B | xs:datetime | xf:dayTimeDuration | op:subtract-dayTimeDuration-from-dateTime(A, B) | xs:dateTime |
A - B | xf:yearMonthDuration | xf:yearMonthDuration | op:subtract-yearMonthDurations(A, B) | xf:yearMonthDuration |
A - B | xf:dayTimeDuration | xf:dayTimeDuration | op:subtract-dayTimeDurations(A, B) | xf:dayTimeDuration |
A * B | numeric | numeric | op:numeric-multiply(A, B) | numeric |
A * B | xf:yearMonthDuration | xs:decimal | op:multiply-yearMonthDuration(A, B) | xf:yearMonthDuration |
A * B | xs:decimal | xf:yearMonthDuration | op:multiply-yearMonthDuration(B, A) | xf:yearMonthDuration |
A * B | xf:dayTimeDuration | xs:decimal | op:multiply-dayTimeDuration(A, B) | xf:dayTimeDuration |
A * B | xs:decimal | xf:dayTimeDuration | op:multiply-dayTimeDuration(B, A) | xf:dayTimeDuration |
A idiv B | xs:integer | xs:integer | op:integer-div(A, B) | xs:integer |
A div B | numeric | numeric | op:numeric-divide(A, B) | numeric; but xs:double if both operands are xs:integer |
A div B | xf:yearMonthDuration | xs:decimal | op:divide-yearMonthDuration(A, B) | xf:yearMonthDuration |
A div B | xf:dayTimeDuration | xs:decimal | op:divide-dayTimeDuration(A, B) | xf:dayTimeDuration |
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(xf:compare(A, B), 1) | 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 | xf:yearMonthDuration | xf:yearMonthDuration | op:yearMonthDuration-equal(A, B) | xs:boolean |
A eq B | xf:dayTimeDuration | xf:dayTimeDuration | op:dayTimeDuration-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:anyURI-equal(A, B) | 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 | xf:not(op:numeric-equal(A, B)) | xs:boolean |
A ne B | xs:boolean | xs:boolean | xf:not(op:boolean-equal(A, B)) | xs:boolean |
A ne B | xs:string | xs:string | xf:not(op:numeric-equal(xf:compare(A, B), 1)) | xs:boolean |
A ne B | xs:date | xs:date | xf:not(op:date-equal(A, B)) | xs:boolean |
A ne B | xs:time | xs:time | xf:not(op:time-equal(A, B)) | xs:boolean |
A ne B | xs:dateTime | xs:dateTime | xf:not(op:datetime-equal(A, B)) | xs:boolean |
A ne B | xf:yearMonthDuration | xf:yearMonthDuration | xf:not(op:yearMonthDuration-equal(A, B)) | xs:boolean |
A ne B | xf:dayTimeDuration | xf:dayTimeDuration | xf:not(op:dayTimeDuration-equal(A, B) | xs:boolean |
A ne B | Gregorian | Gregorian | xf:not(op:gYear-equal(A, B)) etc. | xs:boolean |
A ne B | xs:hexBinary | xs:hexBinary | xf:not(op:hex-binary-equal(A, B)) | xs:boolean |
A ne B | xs:base64Binary | xs:base64Binary | xf:not(op:base64-binary-equal(A, B)) | xs:boolean |
A ne B | xs:anyURI | xs:anyURI | xf:not(op:anyURI-equal(A, B)) | xs:boolean |
A ne B | xs:QName | xs:QName | xf:not(op:QName-equal(A, B)) | xs:boolean |
A ne B | xs:NOTATION | xs:NOTATION | xs: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(xf: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 | xf:yearMonthDuration | xf:yearMonthDuration | op:yearMonthDuration-greater-than(A, B) | xs:boolean |
A gt B | xf:dayTimeDuration | xf:dayTimeDuration | op:dayTimeDuration-greater-than(A, B) | xs:boolean |
A lt B | numeric | numeric | op:numeric-less-than(A, B) | xs:boolean |
A lt B | xs:boolean | xs:boolean | op:boolean-less-than(A, B) | xs:boolean |
A lt B | xs:string | xs:string | op:numeric-less-than(xf: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 | xf:yearMonthDuration | xf:yearMonthDuration | op:yearMonthDuration-less-than(A, B) | xs:boolean |
A lt B | xf:dayTimeDuration | xf:dayTimeDuration | op:dayTimeDuration-less-than(A, B) | xs:boolean |
A ge B | numeric | numeric | op:numeric-less-than(B, A) | xs:boolean |
A ge B | xs:string | xs:string | op:numeric-greater-than(xf:compare(A, B), -1) | xs:boolean |
A ge B | xs:date | xs:date | op:date-less-than(B, A) | xs:boolean |
A ge B | xs:time | xs:time | op:time-less-than(B, A) | xs:boolean |
A ge B | xs:dateTime | xs:dateTime | op:datetime-less-than(B, A) | xs:boolean |
A ge B | xf:yearMonthDuration | xf:yearMonthDuration | op:yearMonthDuration-less-than(B, A) | xs:boolean |
A ge B | xf:dayTimeDuration | xf:dayTimeDuration | op:dayTimeDuration-less-than(B, A) | xs:boolean |
A le B | numeric | numeric | op:numeric-greater-than(B, A) | xs:boolean |
A le B | xs:string | xs:string | op:numeric-less-than(xf:compare(A, B), 1) | xs:boolean |
A le B | xs:date | xs:date | op:date-greater-than(B, A) | xs:boolean |
A le B | xs:time | xs:time | op:time-greater-than(B, A) | xs:boolean |
A le B | xs:dateTime | xs:dateTime | op:datetime-greater-than(B, A) | xs:boolean |
A le B | xf:yearMonthDuration | xf:yearMonthDuration | op:yearMonthDuration-greater-than(B, A) | xs:boolean |
A le B | xf:dayTimeDuration | xf:dayTimeDuration | op:dayTimeDuration-greater-than(B, A) | xs:boolean |
A is B | node | node | op:node-equal(A, B) | xs:boolean |
A isnot B | node | node | xf:not(op:node-equal(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:decimal | xs:decimal | op:to(A, B) | xs:integer+ |
A , B | item* | item* | op:concatenate(A, B) | item* |
Operator | Operand type | Function | Result type |
---|---|---|---|
+ A | numeric | op:numeric-unary-plus(A) | numeric |
- A | numeric | op:numeric-unary-minus(A) | numeric |
XPath is intended primarily as a component that can be used by other specifications. Therefore, XPath relies on specifications that use it (such as [XPointer] and [XSLT 2.0]) to specify conformance criteria for XPath in their respective environments. Specifications that set conformance criteria for their use of XPath must not change the syntactic or semantic definitions of XPath as given in this specification, except by subsetting and/or compatible extensions.
This section provides a summary of the main areas of incompatibility between XPath 2.0 and [XPath 1.0]. Many of these are areas where the specification still has open issues outstanding, so this list should not be taken as final. It is the intention of the working group to review all known incompatibilities before final publication.
The list given here assumes (a) that the source document is processed
in the absence of a schema, and (b) that the policy for handling type exceptions
is flexible
: that is, that the software attempts wherever possible
to perform conversions from the supplied type of a value to the type required
by the operation or function where it is used.
In the description below, the terms node-set and number are used with their XPath 1.0 meanings, that is, to describe expressions which according to the rules of XPath 1.0 would have generated a node-set or a number respecively.
The rules for comparing a node-set to a boolean have changed. In XPath 1.0,
an expression such as $nodeset=true()
was evaluated by converting the
node-set to a boolean and comparing the result: so this expression would return true
if $nodeset
was non-empty. In XPath 2.0, this expression is handled in
the same way as other comparisons between a sequence and a singleton: it is true if
$nodeset
contains at least one node whose typed value is true
.
The rules for converting a string to a boolean have changed, so they are now aligned with XML Schema. In XPath 2.0, the rules depend on the context. In a function call, or as an operand of the and
and or
operators (assuming fallback conversions are used) the strings "0"
and "false"
are treated as false, while in XPath 1.0, they were treated as true. All other strings are converted in the same way as XPath 1.0. In a predicate, however, a string is not currently allowed, and will cause an error.
Additional numeric types have been introduced, with the effect that arithmetic may now be done as an integer, decimal, or single-precision floating point calculation where previously it was always performed as double-precision floating point. The result of the div operator when dividing two integers is now a double, which is compatible with XPath 1.0: for example 10 div 4 returns 2.5e0, and 10 div 0 returns positive infinity. The result of the div operator when applied to decimal values, however, is a decimal, so 10.0 div 0 will raise an error.
The rules for converting numbers to strings have changed. These will affect the
way numbers are displayed in the output of a stylesheet. The output format depends on
the data type of the result: floating point values, for example, will be displayed using
scientific notation. The result of a decimal calculation such as 1.5 + 3.5
will be displayed as 5.0
, not 5
as previously. The general
rule is that the resulting string uses the canonical lexical representation for the
data type as defined in XML Schema.
The rules for converting strings to numbers have changed. A string that cannot
be interpreted as a number now (subject to resolution of an open issue) produces an
error, whereas in XPath 1.0 it produced the value NaN
(not a number).
The representation of special values such as Infinity has been aligned with XML Schema.
Strings containing a leading plus sign, or numbers in scientific notation, may now
be converted to ordinary numeric values, whereas in XPath 1.0 they were converted
to NaN
.
Many operations in XPath 2.0 produce an empty sequence as their result
when one of the arguments or operands is an empty sequence. With XPath 1.0, the result
of such an operation was typically a zero-length string or the numeric value NaN
.
Examples include the numeric operators and certain functions such as substring
. Functions also produce an empty sequence when applied to an argument
for which no other value is defined. However, for functions in the core such as name
, the XPath 1.0 behavior has been retained; for example, applying the name
function to a text node produces a zero-length string, as it did in XPath 1.0
In XPath 1.0, the <
and >
operators, when applied
to two strings, attempted to convert both the strings to numbers and then made a numeric
comparison between the results. In XPath 2.0, these operators perform a lexicographic comparison using the
default collating sequence.
In XPath 1.0, functions and operators that compared strings (for example, the
=
operator and the contains
function) worked on the basis of
character-by-character equality of Unicode codepoints, allowing Unicode normalization
at the discretion of the implementor. In XPath 2.0 (subject to resolution of open issues),
these comparisons are done using the default collating sequence. The working group may
define mechanisms allowing codepoint comparison to be selected as the default collating
sequence, but there is no such mechanism in the current draft.
In XPath 1.0, it was defined that with an expression of the form A and
B
,
B would not be evaluated if A was false. Similarly in the case of A or
B
, B would not be evaluated if A was true. This is no longer
guaranteed with XPath 2.0: the implementation is free to evaluate the two
operands in either order or in parallel. This change has been made to give
more scope for optimization in situations where XPath expressions are
evaluated against large data collections supported by indexes.
Consecutive comparison operators such as A < B < C
were supported in XPath 1.0, but are not supported in XPath 2.0.
In the XPath 1.0 data model, an element node had a namespace node for each in-scope
namespace. The parent of the namespace node was the element node, and the namespace nodes
for one element were distinct from those of any other element (as revealed, for example,
using the union operator |
). In XPath 2.0 (subject to resolution of open
issues) element nodes will still have namespace nodes for all the in-scope namespaces,
but these namespace nodes will be shared by different elements in the same document: that
is, there will be a many-to-many relationship between element nodes and namespace nodes.
This will affect any code that attempts to find the parent or ancestors of a namespace
node, or that tries to count namespace nodes or to form a union between two sets of namespace
nodes.
Backward compatibility issues affecting individual functions in the core function library are described in [XQuery 1.0 and XPath 2.0 Functions and Operators].
Values for Status has the following meaning:
resolved: a decision has been finalized and the document updated to reflect the decision.
decided: recommendations and decision(s) has been made by one or more of the following: a task-force, XPath WG, or XQuery WG.
draft: a proposal has been developed for possible future inclusion in a published document.
active: issue is actively being discussed.
unassigned: discussion of issue deferred.
subsumed: issue has been subsumed by another issue.
(parameters used: kwSort: cluster, kwFull: brief, kwDate: 00000000).
Num | Cl | Cluster | Status | Locus | Description | Originator |
---|---|---|---|---|---|---|
293 | active | xquery | Cdata and CharRef Semantics | Michael Rys | ||
323 | active | xpath | Should "unordered" be included in XPath? | XSL/XQuery joint | ||
134 | (de)reference-expr | decided | xquery | Dereference Operator and Links | Jonathan Robie | |
92 | (in)equality-operators | active | xpath | Deep equality | Jonathan | |
96 | (in)equality-operators | active | xpath | Normalized Equality | Mary Fernandez | |
28 | 3-value-logic | active | xpath | Do we need and3(), or3(), not3() built in? | XSL WG | |
215 | 3-value-logic | active | xpath | Should we have a 3-valued form of quantifiers? | Andrew Eisenberg | |
132 | attribute accessors | decided | xfo | Attribute Name, Attribute Content | Don Chamberlin | |
113 | axes | decided | xpath | What should the mechanism be for axis subsetting? | jmarsh@microsoft.com | |
328 | cdata section | active | xquery | What does CDATA section constructor construct? | Michael Kay | |
177 | TF | choice-context | active | xpath | Consistency of functions that take boolean formal argument | XPath-TF |
256 | D | collections | active | xpath | What is return type of colections? | XPath TF |
257 | D | collections | active | xpath | Does collection() always return same result? | XPath TF |
333 | conformance | active | xpath | Optional Features vs. Conformance Levels | XPath TF | |
169 | conformance | unassigned | xquery | Missing conformance section | Jonathan | |
238 | consistency | active | xpath | Consistency: tradeoff between interoperability and efficiency | Phil Wadler | |
239 | consistency | active | xpath | Consistency: bracketing of nested expressions | Phil Wadler | |
240 | consistency | active | xpath | Consistency: parenthesizing test expressions | Phil Wadler | |
241 | consistency | active | xpath | Consistency: keywords | Phil Wadler | |
252 | consistency | active | xquery | "sort by" rather than "sortby" for consistency? | Phil Wadler | |
286 | constructor-expr | active | xquery | Element Construction vs Streaming | Michael Rys | |
288 | constructor-expr | active | xquery | Element Constructor Attribute Order | Michael Rys | |
289 | T | constructor-expr | active | xquery | Attribute Value Construction from Elements | Michael Rys |
290 | constructor-expr | active | xquery | Element Attribute Constructor Name Type | Michael Rys | |
291 | T | constructor-expr | active | xquery | Element Construction anySimpleType Sequence Content | Michael Rys |
292 | constructor-expr | active | xquery | Element Construction Sequence vs Multi-expr | Michael Rys | |
146 | constructor-expr | decided | xquery | Jonathan | ||
145 | constructor-expr | unassigned | xquery | Copy and Reference Semantics | XQuery Editors | |
329 | constructors | active | xquery | Duplicate attribute constructors | Michael Kay | |
143 | constructor-syntax | unassigned | algebra | XML Constructor | Jonathan Robie | |
230 | D | context | decided | xpath | Context document adequate for multiple docuemnts? | Michael Rys |
258 | D | documents | active | xpath | Identity of Document Nodes | Jonathan Robie |
170 | D | documents | unassigned | xquery | Document collections | XQuery WG |
97 | error | active | xpath | How should the error object be supported? | Editor | |
98 | error | active | xpath | General discussion of errors | XML Query WG | |
99 | error | unassigned | xquery | TRY/CATCH and error() | XQuery Editors | |
160 | execution-model | active | xquery | Naive Implementation Strategy | Marton Nagy | |
226 | existential expressions | active | xpath | Existential Expressions | Mike Kay | |
317 | extensions | active | xquery | XQuery Extension Mechanisms | Andrew Eisenberg | |
272 | external-functions | active | xpath | External Functions | Michael Kay | |
273 | external-objects | active | xpath | External Objects | Michael Kay | |
231 | fallback | decided | xpath | data(SimpleValue) is error or no-op? | XSL WG | |
163 | filter | unassigned | algebra | Typing of Filter | Jerome Simeon | |
217 | focus | decided | xpath | Context document in focus | Michael Rys | |
265 | FTTF-xml:lang | active | xpath-fulltext | How do we determine the xml:lang for a node if it inherits xml:lang from a higher-level node? | FTTF | |
266 | FTTF-xml:lang | active | xpath-fulltext | Do we support the sublanguage portion of xml:lang? | FTTF | |
105 | function-app | active | xpath | Implicit current node for functions? | XQuery Editors | |
102 | function-app | decided | xpath | Functions on Empty Sequences | XQuery | |
103 | function-app | decided | xpath | Functions on Sequences | XQuery | |
107 | function-app | decided | xpath | Path iteration | XQuery | |
180 | functions | active | xpath | Functions expecting complex-valued arguments | XPath-TF | |
327 | functions | active | xpath | XSL/XQuery joint | ||
124 | functions | unassigned | xquery | External Functions | XQuery Editors | |
157 | functions | unassigned | xquery | Function Libraries | XQuery Editors | |
223 | functions external | active | xquery | We need a way to declare external functions | Michael Rys | |
3 | grammar | active | xpath | What should be the precedence of a RangeExpr be? | Editor | |
254 | grammar | active | xpath | Should the lexical details be in document? | XPath TF | |
168 | groupby | unassigned | xquery | GROUPBY | XML Query | |
59 | T | INSTANCEOF-expr | decided | xpath | We need precise semantics for instanceof. | mhkay@iclway.co.uk |
295 | lexical-representation | active | xquery | Lexical Representation of Atomic Values | xquery/xsl f2f | |
151 | literal-XML | unassigned | xquery | Cutting and pasting XML into XQuery | XQuery Editors | |
166 | miscellaneous | unassigned | xquery | Excluding Undesired Elements | Don Chamberlin | |
74 | module-semantics | active | xquery | Module syntax | XQuery Editors | |
75 | module-semantics | unassigned | xquery | Importing Modules | XQuery Editors | |
79 | module-syntax | unassigned | xquery | Encoding | Jonathan Robie | |
228 | namespace functions | active | xpath | Should we keep the default function namespace, and the xf: namespace? | Scott Boag | |
219 | namespaces | active | xquery | Context: namespaces | Michael Rys | |
222 | namespaces | active | xquery | Allow redefinition of namespace prefixes? | Michael Rys | |
247 | namespaces | active | xpath | What does default namespace(s) affect? | XPath TF | |
319 | namespaces | active | xquery | Namespace definitions and in-scope namespaces | XPath TF | |
85 | node-equality | decided | xfo | Identity-based equality operator | Algebra Editors | |
86 | node-equality | decided | xpath | Set operations based on value | XQuery Editors | |
186 | node order | decided | xpath | Ordering of result of union, intersect, and except operators | XPath Editors | |
184 | T | node-types | decided | xpath | Need ability to test for Comments, PIs | F&O TF |
187 | operators | active | xfo | Operations supported on date/time types | XPath Editors | |
189 | operators | active | xpath | Supported combinations of types for comparison operators | XPath Editors | |
210 | order sequences | active | xpath | Order of sequences | Phil Wadler | |
234 | order sequences | active | xpath | Who defines sorting order of ()? | Phil Wadler | |
296 | path-semantics | decided | xpath | What is definition of leading "/"? | XQuery Editors | |
5 | reserved-words | active | xpath | Reserved words | XQuery | |
123 | serialization | active | xquery | Linearization/Serialization | XQuery | |
244 | serialization | active | xquery | CDATA sections and serialization | Michael Rys | |
195 | sort | active | xquery | Semantics of sorting heterogeneous sequences | XPath Editors | |
220 | sort | active | xpath | Should there be a way to explicitly sort in document order? | Michael Rys | |
242 | sort | active | xquery | Sortby on partially ordered values? | Michael Rys | |
243 | sort | active | xpath | Provide an example of sorting "disappearing" | Michael Rys | |
251 | sort | active | xquery | Sorting "input to loop", not the result | Phil Wadler | |
300 | sort | active | xquery | Should sorting of untyped data be prohibited? | XPath TF | |
318 | sort | active | xpath | Add 'order by' clause to FLWR? | Jonathan Robie | |
155 | sort | unassigned | xquery | Sorting by Non-exposed Data | Michael Rys | |
109 | syntax | active | xpath | Need text to disambiguate Lexical Structure? | mhkay@iclway.co.uk | |
233 | syntax | active | xpath | Simpler FLWR syntax? | Phil Wadler | |
235 | syntax | active | xpath | Need parenthesis in conditional expression? | Phil Wadler | |
236 | syntax | active | xpath | SimpleType preceded by a keyword? | Phil Wadler | |
237 | syntax | active | xpath | Need parenthesis in type switch expression? | Phil Wadler | |
246 | syntax | active | xquery | Nested XQuery comments allowed? | Michael Rys | |
267 | syntax | active | xpath | Syntax problems with "validate" | XPath TF | |
287 | syntax | active | xpath | Functional Status of Comma | Michael Rys | |
315 | syntax | active | xpath | Whitespace allowed in the name of a variable! | Dana | |
112 | syntax | decided | xpath | Leading Minus | XML Query | |
144 | syntax | decided | xquery | Escaping Quotes and Apostrophes | XML Query | |
212 | syntax | decided | xpath | Is "datatype" a suitable production name? | Phil Wadler | |
229 | syntax | decided | xpath | Do we need both << and precedes? | XQuery/XSL WGs | |
208 | syntax curly brace | active | xquery | Multiple curly braces allowed? | Phil Wadler | |
245 | syntax curly brace | active | xquery | Are {} in text evaluated? | Michael Rys | |
227 | syntax dereference | active | xpath | Syntax for dereference? | Don Chambrelin | |
232 | syntax operators date | active | xpath | Use "+" and "-" on dates and durations? | Phil Wadler | |
283 | syntax-productions | active | xpath | Is the DocumentElement syntax production necessary? | Jonathan Robie | |
213 | syntax quotes | active | xpath | How to get quotes etc in string literals? | Andrew Eisenberg | |
261 | syntax quotes | active | xquery | Quoting rules in nested expressions in attribute value construction | Michael Rys | |
214 | syntax strings in attributes | active | xquery | Strings in attributes | Andrew Eisenberg | |
183 | T | text-nodes | active | xpath | Text nodes - lexical structure and typed form | XPath TF |
192 | T | type constructed element | decided | xquery | Type of a newly constructed element | XPath Editors |
172 | T | typed-value/data() | active | xpath | Some functions taking node sequences and implicitly map? | XPath TF |
54 | type-errors | active | xquery | Queries with Invalid Content | XQuery Editors | |
185 | type exception | decided | xpath | Always explicit cast? | Phil Wadler | |
200 | T | types | active | xpath | Semantics of "only" | XPath Editors |
206 | T | types | active | xpath | Typing support in XPath | Mike Kay |
224 | T | types | active | xquery | Why do we want to allow optional returns and DataType? | Michael Rys |
297 | T | types | active | xpath | Should XPath have "type binding" in variable? | XQuery Editors |
298 | T | types | active | xpath | Add Schema type names for sequences of homogeneous types? | XPath TF |
301 | T | types | active | xpath | Supporting SQL/XML mappings in Basic XQuery | Jonathan Robie |
302 | T | types | active | xpath | Support for arbitrary XML documents | Jonathan Robie |
303 | T | types | active | xpath | Define "scale-down" mappings? | Jonathan Robie |
304 | T | types | active | xpath | Declare required conformance features? | Don Chamberlin |
305 | T | types | active | xpath | Schema Import Feature prerequisite for Static Typing Feature? | Don Chamberlin |
306 | T | types | active | xpath | PSVI to Data Model mapping part of normative text? | Don Chamberlin |
307 | T | types | active | xpath | Schema Types from input documents? | Don Chamberlin |
308 | T | types | active | xpath | Type Soundness | Don Chamberlin |
309 | T | types | active | xpath | What should be the type of an error value? | Don Chamberlin |
310 | T | types | active | xquery | Are the children of a newly constructed element typed? | Dana F |
312 | T | types | active | xquery | What to do about list types? | XQuery WG |
313 | T | types | active | xquery | What to do about union types? | XQuery WG |
314 | T | types | active | xquery | Partial support for SCHEMA IMPORT in Basic XQuery? | XQuery WG |
316 | T | types | active | xpath | Is AnySimpleType = AnySimpleType*? | Michael Rys |
320 | T | types | active | xquery | Should different conformance levels give the same result for the same query and data? | Anders Berglund |
325 | T | types | active | xpath | Refering to element that is not in the in-scope schema def. | XQuery |
326 | T | types | active | xpath | Semantics of element foo of type T | XQuery |
330 | T | types | active | xquery | Should "some" do type filtering? | Michael Kay |
331 | T | types | active | xpath | Static vs. dynamic dispatch for arithmetics | Dana Florescu |
332 | types | active | xpath | Schema Import, Static Typing: what is interoperable? | XPath TF | |
196 | T | types | decided | xpath | Concrete syntax for datatype declarations | XPath Editors |
197 | T | types | decided | xpath | Need "attribute of type"? | XPath Editors |
198 | T | types | decided | xpath | Syntax for named typing | XPath Editors |
199 | T | types | decided | xpath | Support for locally declared types? | XPath Editors |
211 | T | types | decided | xpath | Treat and structural vs named typing | Phil Wadler |
40 | T | type-semantics | active | xquery | Correspondence of Types | Jerome Simeon |
42 | T | type-semantics | active | xquery | Implementation of and conformance levels for static type checking | Don |
43 | T | type-semantics | active | xquery | Defining Behavior for Well Formed, DTD, and Schema Documents | Don Chamberlin |
44 | T | type-semantics | active | xquery | Support for schema-less and incompletely validated documents | Don Chamberlin/Mary Fernandez |
46 | T | type-semantics | active | xquery | typeof() function | Jonathan |
48 | T | type-semantics | active | algebra | CASE not a subtype | XML Query |
255 | T | type-semantics | active | xpath | What are the operators on a derived type? | Don Chamberlin |
260 | T | type-semantics | active | xpath | Implicit data() on instanceof? | Michael Rys |
262 | T | type-semantics | active | xpath | Definition of data() on elements with known complex type | XPath TF |
268 | T | type-semantics | active | xpath | xsd:string and anySimpleType'd data behave the same? | XQuery WG |
269 | T | type-semantics | active | xpath | Can we get rid of the unknown keyword | XQuery WG |
270 | T | type-semantics | active | xpath | Typing, coercions, and conformance | XQuery WG |
271 | T | type-semantics | active | xpath | Type compatibility of heterogeneous union types | XQuery WG |
274 | T | type-semantics | active | xpath | Text-node-only implementation possible? | XSL WG |
275 | T | type-semantics | active | xpath | Should validation also check identity constraints? | Jonathan Robie |
276 | T | type-semantics | active | xpath | Does validation introduce new xsi:type attributes? | Jonathan Robie |
277 | T | type-semantics | active | xpath | Should validate introduce xsi:type? | Jonathan Robie |
278 | T | type-semantics | active | xpath | Does //@xsi:type match an xsi:type attribute? | Jonathan Robie |
279 | T | type-semantics | active | xpath | Should there be a lightweight cast? | Jonathan Robie |
280 | T | type-semantics | active | xpath | Do we need to distinguish atomic simple types and list simple types? | Jonathan Robie |
281 | T | type-semantics | active | xpath | Representing the type name of untyped character data | Jonathan Robie |
282 | T | type-semantics | active | xpath | xs:numeric type | Jonathan Robie |
284 | T | type-semantics | active | xpath | Static Named Typing | Jonathan Robie |
285 | T | type-semantics | active | xpath | Is the QName denoting type information optional or required? | Phil Wadler |
294 | T | type-semantics | active | xquery | Should all elements and attributes have type annotations? | Philip Wadler |
41 | T | type-semantics | decided | xquery | Static type-checking vs. Schema validation | Mary Fernandez |
45 | T | type-semantics | decided | xquery | Names in Type Definitions | Don |
47 | T | type-semantics | decided | xquery | Subtype Substitutability | XQuery Editors |
51 | TF | type-semantics | decided | xquery | Function Resolution | XQuery Editors |
253 | TF | type-semantics | decided | xpath | CAST as simple type of a node type | Michael Rys |
263 | T | type-semantics | decided | xpath | Definition of data() on elements with unknown type, whose content may be simple or complex | XPath TF |
56 | T | type-syntax | active | xquery | Human-Readable Syntax for Types | Algebra Editors |
57 | T | type-syntax | active | xquery | Inline XML Schema Declarations | Don Chamberlin |
164 | updates | unassigned | xquery | Updates | XQuery Editors | |
321 | validate | active | xquery | Is validate strict or lax? | XSL/XQuery joint | |
322 | validate | active | xquery | "validate" strict/lax override? | XSL/XQuery joint | |
225 | variables | active | xpath | Variable redefinition allowed? | Mike Kay | |
250 | variables | active | xquery | Declaring Variables in Prolog | Jonathan Robie | |
264 | variables | active | xpath | Shadowing of Variables | Michael Kay | |
324 | variables | active | xquery | How can variables be bound external to XQuery itself? | XSL/XQuery joint | |
207 | variables | decided | xpath | Variable names: QNames or NCnames? | Ashok Malhotra | |
191 | whitespace | active | xquery | Whitespace handling in element constructors | XPath Editors | |
299 | whitespace | active | xquery | Does character reference to whitespace change whitespace handling? | XPath TF | |
311 | whitespace | active | xquery | Whitespace and Attribute Constructors | ||
218 | wildcards | active | xpath | What wildcards; namespaceprefix? | Michael Rys | |
193 | T | xml non representable | active | xquery | Construction of non representable XML | XPath Editors |
130 | xquery-alignment | active | algebra | Algebra Mapping | XQuery Editors | |
152 | xqueryx | active | xqueryx | XML-based Syntax | XML Query WG | |
153 | xqueryx | active | xquery | Escape between syntaxes | Jerome Simeon |
XPath 1.0 has no reserved words. The current XQuery spec attempts to avoid reserved words but the result is that the XQuery grammar relies heavily on lexing tricks that make it difficult to document and difficult to extend. There is currently a substantial feeling in the XQuery group that the language should have some reserved words, which would be an incompatible change from XPath 1.0.
XSL WG Position: Exceptionally strong feeling that requiring element names that match a reserved word to be escaped is utterly unacceptable. If reserved words are required they must start with an escape character so they cannot conflict with element names. Attempt to maintain grammar and revisit this issue as necessary. We recognize that there is a problem but solutions are all distasteful.
Cf. 5. Reserved Words:
Subsumes: [link to subsumed issue: #xquery-xpath-issue-reserved-words] .
Cf. Keywords in XQuery
Subsumes: [link to subsumed issue: #xquery-reserved-keywords] .
Should the 3-valued logic functions be part of the XPath function library? Note that they can be implemented as user functions (not as efficient as a "native" implementation). We may want to include the user definition as an example.
Section 2.9, on functions, portrays XQuery as a statically typed language, but the mechanisms by which static typing is established are still being developed by the XML Query Algebra editorial team. A complete accounting for type requires that the XML Query Algebra conform completely to the XML Schema type system, and that many open issues be resolved.
The semantics of XQuery are defined in terms of the operators of the XML Query Algebra. The mapping of XQuery operators into Algebra operators is still being designed, and may result in some changes to XQuery and/or the Algebra. The type system of XQuery is the type system of XML Schema. Work is in progress to ensure that the type systems of XQuery, the XML Query Algebra, and XML Schema are completely aligned. The details of the operators supported on simple XML Schema datatypes will be defined by a joint XSLT/Schema/Query task force.
Static type checking and schema validation are not equivalent, but we might want to do both in a query. For example, we might want to assert statically that an expression has a particular type and also validate dynamically the value of an expression w.r.t a particular schema.
The differences between static type checking and schema validation must be enumerated clearly (the XSFD people should help us with this).
This item is a duplicate of the Formal Semantics issue [link to member only information] .
Decision by: xpath-tf on 2002-05-07 ([link to member only information] )
Decision by: xquery on 2002-05-22 ([link to member only information] )
Decision by: xsl on 2002-06-27 ([link to member only information] )
Addressed by the "Named Typing" proposal.
Accepting text in 2002-04-30 public draft.
Static type checking may be difficult and/or expensive to implement. Some discussion of algorithmic issues of type checking are needed. In addition, we may want to define "conformance levels" for XQuery, in which some processors (or some processing modes) are more permissive about types. This would allow XQuery implementations that do not understand all of Schema, and it would allow customers some control over the cost/benefit tradeoff of type checking.
This item is a duplicate of the Formal Semantics issue [link to member only information] .
Jonathan and Don to present a potential consensus proposal at the f2f (This should be a very short proposal). Note: Perhaps we should seriously consider writing the conformance section for the next set of publications.
We should specify the behavior of XQuery for well formed XML, XML validated by a schema, and XML validated by a DTD.
The mapping of a DTD validated or well formed document still needs to be defined in the Data Model.
This is related to [link to resolved issue: #xquery-schema-import] . We do not specify what is the effect of type checking a query that is applied to a document without a DTD or Schema. In general, a schema-less document has type xs:AnyType and type checking can proceed under that assumption. A related issue is what is the effect of type checking a query that is applied to an incompletely validated document. As above, we can make *no* assumptions about the static type of an incompletely validated document and must assume its static type is xs:AnyType.
This item is a duplicate of the Formal Semantics issue [link to member only information] .
Some aspects addressed by the "Named Typing" proposal.
The Data Model work still needs to be done.
Open questions: What is the result of a failed validation? Can you inspect the result?
Does the definition of a type include both element-names and element-contents (as in the Formal Semantics document), or only element-contents (as in XML Schema)?
Addressed by the "Named Typing" proposal.
Decision by: xpath-tf on 2002-05-07 ([link to member only information] )
Decision by: xquery on 2002-05-22 ([link to member only information] )
Decision by: xsl on 2002-06-27 ([link to member only information] )
Accepting text in 2002-04-30 public draft.
Do we need a function that returns the type name of its operand? If so, what should it return if the operand is an element with a given xsi:type - the element name? the name of the type denoted by xsi:type? Specification of this function requires more work on types in XQuery.
Should XQuery 1.0 support subtype substitutability for function parameters?
If subtype substitutability is not supported in XQuery Version 1, the motivation for TYPESWITCH is weakened and the decision to support TYPESWITCH should be revisited.
Addressed by the "Named Typing" proposal.
Decision by: xpath-tf on 2002-05-07 ([link to member only information] )
Decision by: xquery on 2002-05-22 ([link to member only information] )
Decision by: xsl on 2002-06-27 ([link to member only information] )
Accepting text in 2002-04-30 public draft.
More detailed rules need to be developed for function resolution. What kinds of function overloading are allowed? A promotion hierarchy of basic types needs to be specified. The issue of polymorphic functions with dynamic dispatch needs to be studied. Can overloaded functions be defined such that the parameter-type of one function is a subtype of the parameter-type of another function? If so, what are the constraints on the return-types of these functions? Is function selection based on the static type of the argument or on the dynamic type of the argument (dynamic dispatch, performed at execution time)? If XQuery supports dynamic dispatch, is it based on all the arguments of a function or on only one distinguished argument?
Observation: This is a very complex area of language design. If it proves too difficult to solve in the available time, it may be wise to take a simple approach such as avoiding dynamic dispatch in Version 1 of XML Query.
The XML Query Formal Semantics does not support overloading or dynamic dispatch. We will attempt to simplify XML Query Level 1 by omitting these, unless it becomes clear that they are needed. We realize that this might happen.
Decision by: xpath-tf on 2002-04-30 ([link to member only information] )
Decision by: xquery on 2002-05-22 ([link to member only information] )
Decision by: xsl on 2002-06-27 ([link to member only information] )
Mike: We dealt with by saying that there is only one function and the use typeswitch semantics.
Is it an error for a query to specify content that may not appear, according to the schema definition? Consider the following query:
invoice//nose
If the schema does not allow a nose to appear on an invoice, is this query an error, or will it simply return an empty list?
Addressed by the "Named Typing" proposal, but needs more work.
The Algebra has a syntax for declaring types. Up to now, XQuery uses XML Schema for declaring types. Is this sufficient? Some important questions:
Do we need to allow inline XML schema declarations in the prolog of a query? The following example shows one potential syntax for this. It extends the namespace declaration to allow literal XML Schema text to occur instead of a URI in a namespace declaration. The implementation would then assign an internal URI to the namespace.
NAMESPACE fid = "http://example.org/fiddlefaddle.xsd" NAMESPACE loc = [[ <xsd:schema xmlns:xsd = "http://www.w3.org/2000/10/XMLSchema"> <xsd:simpleType name="myInteger"> <xsd:restriction base="xsd:integer"> <xsd:minInclusive value="10000"/> <xsd:maxInclusive value="99999"/> </xsd:restriction> </xsd:simpleType> </xsd:schema> ]] FUNCTION string-to-myInteger ($s STRING) RETURNS loc:myInteger { If the facets of loc:myInteger are not satisfied, this function raises an error. LET $t := round(number($s)) RETURN TREAT AS loc:myInteger($t) } string-to-myInteger("1023")
The semantics of the instanceof operator are not defined over all operands, e.g. sets of several nodes, sequences of several values, etc. What should the symantics be for these types? Should these semantics be defined in the F&O document?
Decision by: xsl on 2002-06-27 ([link to member only information] )
Decision by: xquery on 2002-07-17 ([link to member only information] )
The issue is "dead", in the sense that the April draft contains text that everyone is happy with.
The definition and syntax of a query module are still under discussion in the working group. The specifications in this section are pending approval by the working group.
Future versions of the language may support other forms of query modules, such as update statements and view definitions.
The means by which a query module gains access to the functions defined an an external function library remains to be defined.
Should xmlns only be respected for construction, Xquery expressions but not functions, or also functions?
Do we need an identity-based equality operator? Please justify your answer with sample queries. Note that XPath gets along without it.
Cf. Should we use is and isnot instead of == and !==.
The '==' operator is already defined in the F&O document and used in XQuery use cases.
Decision by: xpath-tf on 2002-04-30 ([link to member only information] )
Decision by: xquery on 2002-05-22 ([link to member only information] )
Decision by: xsl on 2002-06-27 ([link to member only information] )
The '==' is in the document and usecases.
Note that it has been decided to change "==" to "is".
The definitions of UNION, INTERSECT, and EXCEPT for simple values are still under discussion. It is not clear that these operators should apply to simple values, because simple values do not have a concept of node identity. If these operators are defined for simple values, perhaps they should have a lower precedence than arithmetic operators.
Text is in Working Draft 2001-11-28 sec 2.4.
Decision by: xsl on 2002-01-22 ([link to member only information] )
The XSL WG felt that these operators should operate on nodes only and not be overloaded to work on "values" as well. Functions should be used for the "analogous" functionality on values. Action to Ashok to write a proposal. It was noted that one might well want to to a "value" union operating on nodes (where the typed value of each is extracted).
Decision by: xsl on 2002-01-22 ([link to member only information] )
Decision by: xquery on 2002-02-28 ([link to member only information] )Xquery acceptance of XSL proposal
These operators operate on nodes only and are not overloaded to work on "values" as well. Functions are to be used for the "analogous" functionality on values.
In XPath, <book><title> Mark Twain </title></book> and <book><author> Mark Twain </author></book> are treated as equal in comparisons. Is this acceptable for us? Do we need another notion of deep equality? If so, what are the compatibility issues with XPath?
We believe the following approach to error handling would be very useful - (1) introduce TRY <expression> CATCH <expression>, similar to try/catch in OO languages. Instead of having "throw" to throw objects, use error(<expression>), bind the result of the expression to the variable $err, and allow $err to be used in the CATCH clause.
Dana Florescu has been assigned the task of writing a proposal for this.
XQuery-Null-Issue-7: Question: What should happen if a function expecting one element is invoked on an empty sequence?
It's an error.
Text is in Working Draft 2001-11-28 sec 2.1.2, paragraph 6, item 1.3.
Decision by: xpath-tf on 2002-04-30 ([link to member only information] ) Verifying that text is in current draft.
Decision by: xquery on 2002-05-22 ([link to member only information] )Independent verification.
What should happen if a function expecting one element is invoked on a sequence of more than one element?
It's an error.
Text is in Working Draft 2001-11-28 sec 2.1.2, paragraph 6, item 1.1.
Decision by: xpath-tf on 2002-04-30 ([link to member only information] ) Verifying that text is in current draft.
Decision by: xquery on 2002-05-22 ([link to member only information] )Independent verification.
How should the current node be passed to a function in a path-step?
Using dot notation (".").
Text is in Working Draft 2001-11-28 sec 2.1.1.2, paragraph 4.
Decision by: xpath-tf on 2002-04-30 ([link to member only information] ) Verifying that text is in current draft.
Decision by: xquery on 2002-05-22 ([link to member only information] )Independent verification.
There seems to be a lot of material missing here, for example the rules for disambiguating operator names from NCNames, the two uses of "*", etc. The statement "the longest possible token" means the longest sequence that would form a token in the token-space of the grammar, not the longest that would be valid in the current syntactic context.
Should leading minus/plus be treated as unary operators or as part of a numeric literal? Or should both be supported?
Decision by: xsl on 2002-06-27 ([link to member only information] )
Decision by: xquery on 2002-07-17 ([link to member only information] )
The issue is "dead", in the sense that the April draft contains text that everyone is happy with.
Why is axis availability part of the run-time context? Myaxis::foo should be a syntax error. This seems like a really clunky mechanism for subsetting. The alternative, as Mike Kay presented, is to provide a set of booleans telling if the given axis is available.
Proposed resolution: Axis subsetting should be done at the grammar level, similar to how XSLT pattern matching is specified.
Decision by: xpath-tf on 2002-04-30 ([link to member only information] )
Decision by: xquery on 2002-05-22 ([link to member only information] )
Decision by: xsl on 2002-06-27 ([link to member only information] )
Done at grammar level.
An extensibility mechanism needs to be defined that permits XQuery to access a library of functions written in some other programming language such as Java.
Some sources of information: the definition of external functions in SQL, the implementation of external functions in Kweelt.
We need functions to return the name of an attribute and the content of an attribute.
My proposal is to create a separate section in the F&O document listing the accessors in the data model that are supported. The semantics would still be specified in the data model document. Similarly, we would add a section that listed the functions in the evaluation context that are supported. The semantics for these functions would be in the XPath document as decided this morning.
Decision by: xpath-tf on 2002-04-30 ([link to member only information] )
Decision by: xquery on 2002-05-22 ([link to member only information] )
Decision by: xsl on 2002-06-27 ([link to member only information] )
Section "Accessors" has been added to F&O.
Does the dereference operator work on links, such as XLink or HTML href? Should we also support KEY/KEYREF? In general, our handling of references needs a lot of work.
In general, how are the semantics of the dereference operator defined?
Text is in Working Draft 2001-11-28 sec 2.3.
Decision by: xsl on 2002-01-22 ([link to member only information] )
Decision by: xquery on 2002-02-28 ([link to member only information] )
Acceptance of text in December 2001 published Working Draft, that it does only id/idref.
Decision by: xpath-tf on 2002-05-07 ([link to member only information] ) Verifying that the text that the text is in the draft. Note: there is also a proposal on the table to remove => entirely.
Decision by: xquery on 2002-05-16 ([link to member only information] )
We will keep the dereference operator.
Decision by: xquery on 2002-05-22 ([link to member only information] )
The XML Query WG revisited issue 134 and decided to close the issue by removing => completely. This was not unanimous decision.
Decision by: xsl on 2002-05-23 ([link to member only information] )The XSL WG agrees with the change to remove =>.
Is there a need for a constructor that creates an instance of the XML Query Data Model from a string that contains XML text?
Close the issue, pending convincing use cases. When do we need to be able to create a string of XML text, then convert it into an instance of the XML data model? Can't there always be an intervening parser or other tool to create the XML data model instance?
In attribute constructors and string constructors, XQuery uses quotes or apostrophes as delimiters. How are these characters escaped when they occur within strings that are created by one of these constructors?
I propose that we use double-delimiters within a string literal, e.g. 'I don''t', and unlike most of my syntactic ideas, this proposal seemed to recieve general support.
Decision by: xpath-tf on 2002-04-30 ([link to member only information] )
Decision by: xquery on 2002-05-22 ([link to member only information] )
Decision by: xsl on 2002-06-27 ([link to member only information] )
Syntax in current draft has this, but explanatory text need to be added.
Can a query construct an entire XML document? What restrictions are there, eg on the internal subset, processing instructions or comments on the root level?
The constructor we propose does nothing except create a document node, and is very simple. The documents constructed in this way can be validated, fed to functions that save them or send them as messages, or used in any other way that document nodes may be used in XQuery. Currently, we can construct any node in our data model except for the document node. For instance, we have the following constructors for element and attribute nodes: [66] ComputedElementConstructor ::= "element" (QName | EnclosedExpr) "{" ExprSequence? "}" [67] ComputedAttributeConstructor ::= "attribute" (QName | EnclosedExpr) "{" ExprSequence? "}" We propose an analogous syntax for document nodes, except that there is no need to create the QName for a document node, which does not have one: DocumentNode ::= 'document' '{' ExprSequence '}' A document node constructor creates a document node. It does nothing else. It does not associate the document node with a schema or DTD, specify a file name for it, validate the instance, assign file permissions, or shine shoes. Appendix: Interesting things that are not part of document node construction Here are many things people want to do with documents. None of these are part of document node construction, but all of these things benefit from document nodes. 1. Validating a node Once created, a document may be validated, eg: let $d := document { <?xml version="1.0"?> <greeting>Hello, world!</greeting> } return validate($d) 2. Saving a node to the file system This is best done using a function that specifies the URI, and any other parameters that the system may need. The signature for such a function may look like this: save-document( document $docnode, anyURI $name, element file-params? $p) The file-params element could be used to store information on file permissions, etc. Appendix: Issues Issue: How should schemas be imported for validating a document using the document node? Consider the following example: <stylesheet xmlns="http://www.w3.org/1999/XSL/Transform" xmlns:html="http://www.w3.org/1999/xhtml" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.w3.org/1999/XSL/Transform http://www.w3.org/1999/XSL/Transform.xsd http://www.w3.org/1999/xhtml http://example.org/xhtml.xsd"> I think this is no different from validating an element node. A root element may identify namespace prefixes. Names must be defined in the in-scope schema definitions before they can be used for validation. With or without the document node, a schema location may be specified on an element. Implementations should be free to use this location to locate a schema or to ignore it, as in XML Schema. Issue: Should we allow a DOCTYPE in a document constructor? Consider the following example: let $d := document { <?xml version="1.0"?> <!DOCTYPE greeting SYSTEM "hello.dtd"> <greeting>Hello, world!</greeting> } return validate($d) If a DOCTYPE is specified, should it be used, as it would be by most XML processors?
Decision by: xquery on 2002-05-16 ([link to member only information] )
Cotton: Any objections to adopting this proposal as written by Jonathan? One objection by Michael Rys. Proposal is adopted with one objection.
Should we make it easier to sort by data that is not exposed in the result? Although the current language allows this, it is difficult to define complex sort orders in which some items are not exposed in the result and others are computed in the expression that is sorted. Is there a more convenient syntax for this that would be useful in XQuery?
Here is an example: FOR $e IN //employee WHERE ... RETURN <newe>$e/name</newe> SORTBY -- Now I would like to sort by salary but cannot. Instead, the query would have to be written as FOR $e IN (FOR $x IN //employee RETURN $x SORTBY employee/salary/data()) WHERE ... RETURN <newe>$e/name</newe> Which seems awkward. The question is of course how we can integrate the SORTBY in an other way. For example, could we say FOR $e IN //employee WHERE ... SORTBY $e/salary/data() RETURN <newe>$e/name</newe> ? Best regards Michael
XQuery needs a mechanism to allow function definitions to be shared by multiple queries. The XQuery grammar allows function definitions to occur without a query expression.
We must provide a way for queries to access functions in libraries. For instance, we might add an IMPORT statement to XQuery, with the URI of the functions to be imported. It must be possible to specify either that (1) local definitions replace the imported definitions, or (2) imported definitions replace the local ones.
Marton Nagy has suggested that it would be helpful to describe a naive implementation strategy for XQuery.
A naive XQuery implementation might parse the query, map it to Algebra syntax, and pass it to an Algebra implementation to request type checking from the algebra, returning an error if there were static type errors. A naive implementation might then request query execution from the algebra, get the results from the algebra and return it to the user.
Alternatively, the implementation might have its own algebra for execution, or it might generate statements in a specific implementation language such as XPath or SQL.We expect a wide variety of implementation approaches to be used in practice.
The current mapping of filter to the algebra does not preserve much useful type information. Can the mapping be improved? Is there another approach to filter that would yield better type information?
We believe that a syntax for update would be extremely useful, allowing inserts, updates, and deletion. This might best be added as a non-normative appendix to the syntax proposal, since the algebra is not designed for defining this portion of the language.
How are collections of documents named and addressed in queries? How are they associated with files in directory structures, or resources in various systems? How does one address documents within collections?
Should small set of functions on nodes, i.e., data(), name, uri-namespace(), be defined on node sequences and have an implicit mapping semantics?, e.g., data(a/b)
Cf. Accessing Element Data
The proposal by Michael Rys in [link to member only information: Proposal to close issue expr[nodes]] treats not()/not3() differently from all other functions that take a boolean formal argument.
Cf. Implicit conversion of node-sets to boolean for comparisons.
Lexical structure and typed form of text nodes discussed in datamodel. No analogous discussion in the XPath document on that there are two ways to access information, as typed content or as nodes. This also needs to be discussed in conjunction with construction.
Need to extend languages to test for instance-of comments, pis, etc.
Decision by: xsl on 2002-06-27 ([link to member only information] )
Decision by: xquery on 2002-07-17 ([link to member only information] )
The issue is "dead", in the sense that the April draft contains text that everyone is happy with.
Should we do explicit casts rather than type conversion, like for example Python? This would result in e.g. forceing the user to tag a string everytime...
Cf. Support for UnknownSimpleType
Addressed by the "Named Typing" proposal.
What should be the ordering of the results of the union, intersect, and except operators?
Issue is for material in sec 2.4. in Working Draft 2001-11-28.
Union, intersect, and except on node sequences are defined to return their results in document order.
Decision by: xsl on 2002-06-27 ([link to member only information] )
Decision by: xquery on 2002-07-17 ([link to member only information] )
The issue is "dead", in the sense that the April draft contains text that everyone is happy with.
What arithmetic operations should be supported on date/time types?
Issue is for material in sec 2.5. in Working Draft 2001-11-28.
Decision by: xquery on 2002-02-06 ([link to member only information] )
Locus should be Functiond and Operators
Make sure that the XPath/XQuery document is consistent with the F&O document with respect to the supported combinations of types for comparison operators.
Issue is for material in sec 2.6. in Working Draft 2001-11-28.
How is whitespace handled in element constructors?
Issue is for material in sec 2.8. in Working Draft 2001-11-28.
[link to member only information] Michael Kay:
The XQuery WG requested information from XSL WG as to how we currently deal with whitespace, in the hope that we can provide an off-the-shelf solution to the problem. In response to the action, here's a description of what XSLT does. The stylesheet is an XML document. In constructing its infoset, all processing instructions, comments, and whitespace-only text nodes are discarded. (To be absolutely precise, PIs and comments are discarded; then adjacent text nodes are merged; then whitespace-only text nodes are removed from the tree). Whitespace text nodes are retained however, in two circumstances: (a) if the whitespace text node is a child of an <xsl:text> element, and (b) if an ancestor element specifies xml:space="preserve". Certain elements in the stylesheet (for example, xsl:element) contain a "content constructor". A content constructor is a sequence of XSLT instructions, literal result elements, and literal text nodes. In evaluating a content constructor, XSLT instructions do whatever the semantics of the particular instruction say, while literal result elements and literal text nodes are copied to the result tree. The effect of this is that a whitespace-only text node in the stylesheet is copied to the result tree only if either (a) it appears immediately inside <xsl:text>, or (b) it is within the scope of an xml:space="preserve" attribute. Whitespace that is adjacent to non-white text in a literal text node is copied to the result tree. The effect of these rules is as follows: ======================================= <a> </a> generates an empty element: <a/> ======================================= <a xml-space="preserve"> </a> generates: <a xml-space="preserve"> </a> ======================================= <a><xsl:text> </xsl:text></a> generates: <a> </a> ======================================= <a> <b/> <a> generates: <a><b/></a> ======================================= <a>Some text <b/> </a> generates: <a>Some text <b/></a> ======================================= There are other complications with whitespace. Whitespace in the result tree can come from the source document as well as from the stylesheet; XSLT provides control over whether whitespace-only text nodes in the source document are significant or not. Whitespace can also be generated in the output during serialization, if the xsl:output option indent="yes" is specified. Also of course the XSLT rules apply in addition to the XML rules. XML for example normalizes line endings and normalizes whitespace (but not character references) in attribute values. This happens outside XSLT's control. Whitespace character references such as are treated differently from literal whitespace by the XML processor, but are treated identically to literal whitespace by the XSLT processor. It's fair to say that these rules create a fair bit of confusion. It usually doesn't matter for generating HTML, because whitespace in HTML is rarely significant. For generating text files, it can be quite tricky. However, the rules are well-defined and a user who understands the rules can always get the required output. What should XQuery do? I'd suggest mimicking these rules as closely as possible, if only because users then only have to learn one set of confusing rules rather than two. I can't think of any obvious improvements that would make the system less confusing. Where the user wants to explicitly output whitespace, of course, <a>{' '}</a> provides a suitable alternative to XSLT's <xsl:text> instruction. This analogy would suggest that <a> {'x'} </a> should output <a>x</a>, while <a>z {'x'} y</a> should output <a>z x y</a>: that is, the characters between <a> and "{" are ignored if they consist entirely of whitespace, but are all significant if any of them is non-whitespace. <a> </a> should output <a/>, as should <a> </a>. This is only a suggestion, of course, the decision is entirely for XQuery to make. Mike Kay
What is the type of a newly constructed element?
Issue is for material in sec 2.8. in Working Draft 2001-11-28.
Cf. Is the QName denoting type information optional or required?
Cf. Should all elements and attributes have type annotations?
Addressed by the "Named Typing" proposal.
An element constructor may contain adjacent simple values as the content of the element. This cannot be represented in XML. What should we do about this?
Issue is for material in sec 2.8. in Working Draft 2001-11-28.
What should be the concrete syntax for datatypes in function signatures and expressions? Should this syntax support node-or-value? Processing-instructions? Comments? Note that some functions in the F&O document (such as "exists") require "node-or-value" parameters.
Issue is for material in sec 2.13. in Working Draft 2001-11-28.
Addressed by the "Named Typing" proposal in SequenceType production.
Decision by: xpath-tf on 2002-04-30 ([link to member only information] ) Verifying that text is in current draft.
Decision by: xquery on 2002-05-22 ([link to member only information] )Independent verification.
The current Datatype production supports declarations of the form "element of type <var>". Do we also need declarations of the form "attribute of type <var>" or "node of type <var>"?
Issue is for material in sec 2.13. in Working Draft 2001-11-28.
Addressed by the "Named Typing" proposal in SequenceType production.
Decision by: xpath-tf on 2002-04-30 ([link to member only information] ) Verifying that text is in current draft.
Decision by: xquery on 2002-05-22 ([link to member only information] )Independent verification.
Does the Datatype declaration need a way to specify both the QName of an element or attribute and its type, eg element person of type plumber?
Issue is for material in sec 2.13. in Working Draft 2001-11-28.
Addressed by the "Named Typing" proposal in SequenceType production.
Decision by: xpath-tf on 2002-04-30 ([link to member only information] ) Verifying that text is in current draft.
Decision by: xquery on 2002-05-22 ([link to member only information] )Independent verification.
Should XQuery support the import of locally declared types from schemas?
Issue is for material in sec 2.13. in Working Draft 2001-11-28.
Addressed by the "Named Typing" proposal in SequenceType production.
Decision by: xpath-tf on 2002-04-30 ([link to member only information] ) Verifying that text is in current draft.
Decision by: xquery on 2002-05-22 ([link to member only information] )Independent verification.
The keyword "only" remains in the syntax of "instance of", but the meaning of this keyword is not clear. Do we need this? If so, what are its semantics?
Issue is for material in sec 2.13. in Working Draft 2001-11-28.
Further input from Phil Wadler: Suggest we remove "only" from the text, and turn it into an issue. (As noted in the text, "only" makes sense only if we have named types, which is another issue.) If we do have "only", it should be used consistently in both "instance of" and in the "case" of a type switch. [!]
Should variable names be QNames or NCNames? Note that XPath 1.0 uses QNames, and it may be helpful to disambiguate variable names from different modules.
Decision by: xsl on 2002-06-27 ([link to member only information] )
Decision by: xquery on 2002-07-17 ([link to member only information] )
The issue is "dead", in the sense that the April draft contains text that everyone is happy with.
2.10, * Points 1 and 2 (Draft 2001-11-28). We could specify that lexical order is used when the ordering expression yields a sequence of values. This could be quite useful, e.g., if we represent Section 1.2.3 by (1,2,3) and Section 1.4 by (1,4), then lexical ordering does the right thing. This also implies that () should sort before everything else, as that is what happens with lexical order.
2.13.2 (Draft 2001-11-28) The behaviour of treat is profoundly affected by the choice between structural and named typing. If we use structural typing, then treat changes the type but not the value; if we use named typing, then treat must return a new value containing the appropriate type names. (Similarly for type switch.) The current wording is vague on this point. Should we be less vague and more clear about what the two different choices involve?
Addressed by the "Named Typing" proposal in SequenceType production.
Decision by: xpath-tf on 2002-04-30 ([link to member only information] ) Verifying that text is in current draft.
Decision by: xquery on 2002-05-22 ([link to member only information] )Independent verification.
Is Datatype the right name for production [54] (Draft 2001-11-28)? It may be confused with XML Schema Type 2.
Decision by: xsl on 2002-06-27 ([link to member only information] )
Decision by: xquery on 2002-07-17 ([link to member only information] )
The issue is "dead", in the sense that the April draft contains text that everyone is happy with.
How do you get strings such as single and double quote to be allowed in character strings?
<name>Ben & Jerry's</name>
eg should doubling a quote escape it?
It would seem that we need to allow these CharRef's in string literals as well.
Should we have a 3-valued form of quantifiers?
QuantifiedExpr is defined as being two-valued, while SQL's is 3-valued. SQL would evaluate 5 >ALL (6, null, 7) as UNKNOWN. XQuery would return FALSE where SQL returns UNKNOWN.
The current definition of context documents may be difficult to implement in an efficient manner. Should this definition be simplified? Is this definition needed at all?
Decision by: xpath-tf on 2002-07-29 ([link to member only information] )
Decision by: xquery on 2002-07-30 ([link to member only information] )joint f2f, decision missing from minutes confirmed
Decision by: xsl on 2002-07-30 ([link to member only information] )joint f2f, decision missing from minutes confirmed
The definition of context document has been removed.
XQuery must specify how namespaces are handled in the context.
Note that:
1. An unprefixed element name used as a nametest in a query has the namespaceURI associated with the default element namespace from the context.
Note: we may decide that this is the same as the default namespace of the in-scope namespaces, but this is not certain.
2. An unprefixed attribute has a null namespaceURI
Would we prefer a syntax that requires explicit declaration of a general type when a function is to be loosely typed, rather than use the current syntax in which the type is omitted when the function is untyped.
The binding of a variable in an expression always overrides any in-scope binding of a variable with the same name". In XSLT, it is an error to declare a (local) variable if another local variable with the same name is already in scope. This rule has proved useful in catching many user errors, particularly where users misunderstand the nature of XPath variables and think that a second declaration behaves like an assignment statement. I would prefer it to be an error to declare a variable if a variable of that name is already in scope. Also, the scope of variables has not been defined with very great precision, it's not explicitly clear what
for $i ........return for $i in // X, $j in $i/z return ....
means: which $i does this refer to?
Do we want to require implementations to test all pairs in order to determine if there is an incomparable value? Note that there are three choices: return true if any pair that satisfies the condition is encountered, return error on incomparable, or permit implementations to define what to do if both a true comparison and an incomparable pair are encountered. Should static and dynamic semantics handle this differently?
What syntax should be used for dereference? In addition to the => syntax described in the document, here are two alternative approaches: (a) Treat dereferencing as an axis; (b) Simply use id(.) in a general step, with no special syntax.
The question was raised of whether the Query WG and F&O TF have 1) a good rationale for putting built-in functions in a namespace, and 2) a consistent story about how this will relate to default namespace declarations and user-defined functions.
It would seem odd to have to have all user defined functions put in the FandO namespace if a namespace is not declared for it. If you do not do that, then user defined functions that don't require a prefix will not match the QName.
And, if there is not a good rational that provides user benifits, then it seems like we are going through a lot of additional complexity for little or no benefit.
Do we need both << and precedes?
Decision by: xpath-tf on 2002-07-29 ([link to member only information] )
Decision by: xsl on 2002-07-30 ([link to member only information] )(joint meeting)
Decision by: xquery on 2002-07-30 ([link to member only information] )(joint meeting)
"precedes" and "follows" operators deleted.
Is "/" and the context document adequate for multiple documents?
Cf. Mapping Input Context
Decision by: xpath-tf on 2002-07-29 ([link to member only information] )
Decision by: xquery on 2002-07-30 ([link to member only information] )joint f2f, decision missing from minutes confirmed
Decision by: xsl on 2002-07-30 ([link to member only information] )joint f2f, decision missing from minutes confirmed
Access is provided to multiple documents using a different mechanism, specifically the input() and collection() functions.
What is the result of applying the data() function on a SimpleValue? Is it an error, is it a no-op, or is it a type exception with a fallback?
Decision by: xpath-tf on 2001-12-18 ([link to member only information] )
Decision by: xquery on 2001-12-19 ([link to member only information] )
Decision by: xquery on 2002-05-22 ([link to member only information] )Reaffirming the XPath TF telcon 2002-04-30 view.
Decision by: xsl on 2002-06-27 ([link to member only information] )
data() applied to simple value is identity function (no-op). Rationale: does not require special 'fallback' behavior and if we resolve Issue 0172 so that data is defined on node sequences, then for consistency, it should be defined on heterogeneous sequences. Still waiting on general proposal for Issue 172.
At the XPath TF telcon 2002-04-30 it was noted that the current documents do not reflect the resolution, as recorded in our issues list. The documents need to be modified accordingly.
2.10, + Point 5 (Draft 2001-11-28). If we don't adopt Plil W's proposal in Point 1, then there should be an Issue as to whether the behaviour should be specified by the user, or the vendor. One option is to let the user specify that () sorts high, low, or either, in the latter case the vendor decides.
Issue as to whether SimpleType (was BuiltInType) might be preceded by a keyword. Now that we have "element of type" it seems natural to use "type" to preced SimpleType, possible generalizing to also allow a complex type.
Consistent tradeoff between interoperability and efficiency. There are a number of places where XQuery must choose between pinning down precise behaviour or offering flexibility to the implementor. These include whether order in "for" expressions is significant, whether sorting is stable, whether order is significant for duplicate elimination, whether order is significant when finding the union, merge, except of sequences of values, and the like. We should have a consistent policy for making these choices.
Consistent bracketing of nested expressions. Some nested expressions are surrounded by parentheses (treat, cast, assert), some nested expressions are surrounded by braces (element construction, function body), and some nested expressions are not bracketed (for expression, conditional expression). We should have a consistent policy for bracketing of nested expressions.
Consistent parenthesizing of test expressions. Some test expressions are surrounded by parentheses (conditional, type switch) and some are not (where). We should have a consistent policy for parenthesizing of test expressions.
What is effect of default namespace declarations on unprefixed QNames that may occur in element constructors, attribute constructors, and name tests (or anywhere else).
In XPath 1.0, in-scope namespace decls effect prefixed QNames, but default namespace decl does not effect unprefixed names in a name test. In XSLT 2.0, we introduced multiple default namespace decls :one for constructed elements, one for names in xpath expressions.
Functions in a function library often need to access the same variables. For instance, a function library that manipulates a grammar may need to use the following variables in many functions:
$grammar := document("xpath-grammar.xml")/g:grammar $target := "xquery"
One possible syntax for this is:
'define' ''variable' varname ':=' expr
The above production would occur only in the prolog.
Consider this query:
for $x in /books/book, $y in /reviews/review where $x/isbn = $y/isbn return <newbook>{ $x/title, $x/author, $y/reviewer }</newbook> sortby isbn
This is an error, since isbn doesn't appear in newbook. (The static type system would catch this error.) What you have to write is
for $z in for $x in book, $y in review where $x/isbn = $y/isbn return <dummy>{ $x/title, $x/author, $y/reviewer, $x/isbn }</dummy> sortby isbn return <newbook>{ $z/title, $z/author, $z/reviewer }</newbook>
This is painful.
I think that XQuery should support this syntax, or something similar:
for $x in book, $y in review where $x/isbn = $y/isbn sortby $x/isbn return <newbook>{ $x/title, $x/author, $y/reviewer }</newbook>
Our plate is full with more important matters just now, but I hope we could fix this before we finalize XQuery.
Given the expression:
cast as xsd:decimal(//element_string [3]) div cast as xsd:decimal("+1.25000000")
and a type of ELEMENT element_decimal [xsd:string] for the element_string nodes, our current cast rules disallow the cast of the element node to a value, since the above expression would be translated into:
data(cast as xsd:decimal(//element_string [3])) div cast as xsd:decimal("+1.25000000")
instead of (the user expected):
cast as xsd:decimal(data(//element_string [3])) div cast as xsd:decimal("+1.25000000")
Could we change the casting rules to allow the above?
We could either add a rule that pushes data() into cast expressions or have a special rule for casting to simple value types that implies applying data() in the casted expression (similar to arithmetic expressions).
Addressed by the "Named Typing" proposal: XQuery Section 2.13 cast does data extraction.
Decision by: xpath-tf on 2002-04-30 ([link to member only information] ) Verifying that text is in current draft.
Decision by: xquery on 2002-05-22 ([link to member only information] )Independent verification.
User defines a derived type, what operators are inherited by that type. SQL has a concept of distinct type. A distinct type does not inherit the operastors on the base type. XQuery in F&O does the opposite. All operations on the base type are inherited.
[link to member only information] Don Chamberlin:
[link to member only information] Don Chamberlin:
MR: Why does collection() return item*. I want document*.
JR: You can specify what you want. You have to accept a URI and what you return is implementation dependent.
SCA: Strawpoll. 5 item*, 3 document*. No one cannot live with item*
Can an implementation provide a more specific return type than item* and still be a conforming implementation?
Some discussion. No consensus.
Consider the following query:
if (document("foo.com") == document("foo.com")) then <yep/> else <nope/>
I would like the following output:
<yep/>
I think we can achieve this if we say that the URI of a resource is used as its identity. However, one resource can be identified by more than one URI. Suppose that "foo.com/here/there/hi.xml" and "file://c:/temp/limerick-tei.xml" refer to the same resource. What does the following return?
if (document("foo.com/here/there/hi.xml") == document("file://c:/temp/limerick-tei.xml")) then <yep/> else <nope/>
Should we simply use the URI of the parameter to establish identity and say that the two do not match? Should we make the result implementation-dependent?
Does expr instance of type define an expected type with type so that data() is implied explicitly on:
let $e := <e xsi:type=?xsd:integer?/> return $e instanceof xsd:integer
is that
let $e := <e xsi:type=?xsd:integer?/> return data($e) instanceof xsd:integer
and thus true or false?
This issue is somewhat related to CAST (Issue 253), but since we perform a type test here, I would argue that we should not.
We currently say that in a constant string in XQuery, I can do any of the following three to escape quotes (please correct if I am wrong):
A. XQuery rule (works both in XQuery only and XQuery in XML embedding): quotes and double quotes are doubled if they are enclosed inside their own kind.
E.g.,
Lexical Value in datamodel '"' " '''' ' """" " '""' ""
B. XML rules (work only in XQuery in XML embedding since XML parser will work:
B1. Use ' when string delimiter is " and viceversa. This of course does not preserve data fidelity, so if the difference between them is important, you will need to use B2.
B2. Entitize
I assume that I cannot do just B, but that I have to use B to get A. E.g., <a foo="""/> in an XML document is not a valid XQuery and I have to write <a foo=""""/>
The problem that I have is that I do not know what the rules are for nesting quotes inside XQuery expressions:
What are the rules for:
<foo bar="{fnc1(<baz goo="{fnc2("string arg")}"/>)}"/>
Do I have to double and then triple? Does {} mean that the outside "" become inconsequential?
An alternative definition of data() on elements with known complex type:
If $e is an element of an known (complex) type, then data($e) evaluates to the concatenation of $e's text nodes and has UnknownSimpleType.
This definition is appropriate when explicit casts are necessary to convert UnknownSimpleType to other atomic types, i.e., when the basic conversion rules *DO NOT* implicitly convert UnknownSimpleType to other atomic types.
The benefit of this alternative is that a user can always safely apply data() to any node and is guaranteed never to get an error.
The the data() function is only defined on element and attributes with a simple type. The definition of data() on other kinds of nodes or on element and attributes with unknown type is still an open issue.
The corresponding issue in the Formal Semantics document is Issue-108.
Decision by: xpath-tf on 2002-04-11 ([link to member only information] )
xf:data(): decided that it should return the error object when applied to document, PI, comment and namespace nodes.
This change should be reflected in the F&O, XPath and Data Model document.
XSLT does not allow a local variable to be declared if there is already a local variable in scope with the same name. For example, the following is disallowed:
<xsl:variable name="i" select="0"/> <xsl:for-each select="item"> <xsl:variable name="i" select="$i + 1"/> <a><xsl:value-of select="$i"/></a> </xsl:for-each>
This restriction has proved with experience to be a good thing, because users writing a construct such as the one above have almost invariably misunderstood the way variables work in a declarative language; if the construct were allowed, it would not give them the results they expect.
The equivalent XQuery expression is currently allowed:
let $i := 0 for $x in item let $i := $i + 1 return <a>{$i}</a>
XPath 2.0 has no "let" expression, but it can include variable declarations, and these are allowed to shadow each other.
For XSLT users, it seems inconsistent that there should be different rules in XSLT and in XPath. The XSLT 1.0 rule, which makes variable shadowing an error, has proved useful in practice and we recommend that it should be adopted also for XPath 2.0 and XQuery 1.0.
Should we simplify the relationship between xsd:string and the anySimpleType'd data to have them both behave the same operationally by providing implicit coercions and being type compatible?
Alternate, in some peoples view mutually exclusive, issue:
Should we simplify the relationship between xsd:string and the anySimpleType'd data to have them both behave the same operationally by disallowing implicit coercions on anySimpleType and being type compatible?
One difficulty in designing XQuery is that it must meet the needs of two quite different constituencies:
Convenient: Quickly write queries to explore a large body of data. Works best with implicit coercions and dynamic typing.
Reliable: Solidly engineer queries for web services. Works best with explicit coercions and static typing.
We've already agreed to have two conformance levels, one with dynamic typing and one with static typing. Perhaps the dynamic typing level should have implicit coercions and the explicit typing level should have explicit coercions.
Currently the formal semantics maps arithmetic and comparison operations that have union types as (at least of one of) their argument types to a runtime type switch. This has serious unwanted consequences for "algebraization" of queries and optimization and leads to some surprising static typing results.
Should we make non-promotable union types on such operations a type error instead?
The ability to call external functions is an established feature of XSLT 1.0, and is retained in XSLT 2.0. The facility is widely used, and some significant libraries of external functions have been developed by third parties. We made an attempt to standardize language bindings for external functions in the XSLT 1.1 working draft, but this proved highly controversial and has been dropped. The facility remains, however, even though the binding mechanisms remain implementation-defined.
The XPath 2.0 specification continues to tolerate external functions, though it doesn't really acknowledge their existence properly. All we say is that the repertoire of functions that can be called is part of the context.
The issue is: should the function function-available() function be transferred from XSLT to XPath?
This function tests whether a named function is available, and returns true if it is, and false if it isn't. A typical call is:
if (function-available('my:debug')) then my:debug('Hi!') else ()
This has two implications:
(a) a call on my:debug must not be a static error if the function is not available
(b) the names of functions (and the in-scope namespaces needed to resolve their QNames) must be available at run-time.
Logically the function-available() function has no dependencies on XSLT so it should be transferred to XPath.
Part of the strength of external functions is that they can return objects that are outside the scope of the XPath type system. For example, a function library for performing SQL database access may have a function sql:connect() that returns an object representing a database connection. This object may be passed as an argument to calls on other functions in the SQL function library.
The way this is handled in XPath 1.0 is that the XPath specification defines four data-types, and explicitly leaves the host language free to define additional data types. We could probably live with a similar solution for XPath 2.0, but it's a fudge, and I think we ought to try and do better.
Note that the only things you can do with an external object (under the XSLT 1.0 rules) are to assign it to a variable, or pass it as the argument to another function. In practice I think implementations also allow external objects to have additional behavior, for example they might allow conversion to a string when used in a context where a string is required. I think we should leave such behavior implementation-defined rather than saying that it is always an error.
The question arises as to where external objects should fit into the type hierarchy. Should they be a top-level thing at the same level as "sequence", or should they be one level down, along with "node" and "atomic value"? I think it makes most sense to preserve the principle "everything is a sequence", which means that there are now three kinds of item: nodes, atomic values, and external objects.
Handling this rigorously sounds like quite a pervasive change to the spec, but I don't think it's as bad as it seems. I don't think we should add any language features to support external objects, with the possible exception of a keyword "external" in the type syntax so that one can test for it using "instance of". Functions and operators that work on any sequence (for example, count) should treat an external object like any other item in the sequence. Operations that expect nodes will fail if presented with an external object; operations that expect atomic values will also fail, except that implementations may define fallback conversions from external objects to atomic values.
The current proposed text for XQuery element constructors precludes a "text node only" implementation. Since XSL should have semantics aligned with XQuery a decision needs to be made by the XSL WG as to if this restriction is acceptable to construction in XSLT.
Should validation also check identity constraints? Note that valid identity constraints of partial documents does not imply validity of the document as a whole. The current document says that identity constraints are not checked.
Does validation introduce new xsi:type attributes, or should xsi:type attributes introduced for validation be removed?
Note: The XPath telcon suggested that we eliminate this issue and simply say that any attributes introduced for the purpose of validation are removed as part of the validate semantics.
Should validate introduce xsi:type to reflect type annotations that are not explicitly stated using an xsi:type in the source document?
The current draft introduces xsi:type to reflect inferred or dynamically computed types.
Does //@xsi:type match an xsi:type attribute? Compare to xml:lang, xml:space, xmlns, which are not represented as attributes in the XML Information Set. Note, however, that xsi:type is represented as an attribute in the Infoset. Should we treat it like other special XML attributes in the Data Model?
Should there be any provision for a lightweight cast that does not observe facets? Phil Wadler has suggested that 'validate' be used whenever full schema validation is desired, and 'cast' be used as a lightweight validation, which can be used for either simple or complex types, but which does not supply defaults, enforce facets, or check integrity constraints. It may be easier to optimize through cast than through validate, but supporting both constructs may confuse users due to their similarity. He suggests the following syntax for these expressions:
('cast'|'validate') as SequenceType () ('cast'|'validate') 'in' ContextExpr { Expr }
We need a way to represent the type name of untyped character data. In XML Schema, there is no one type that corresponds to this - in strict mode, elements whose content is untyped character data will have the type 'anyType' and attributes whose content is untyped character data will have the type 'anySimpleType', but this interacts in somewhat complex ways with lax and skip validation.
For now, we assume that character data may be associated with a SimpleType whose name is 'xs:unknownSimpleType'. This type does not currently exist in XML Schema, so we must coordinate with them on this issue.
If Schema does not provide a single type to represent untyped character data, we will provide a keyword for it in the ItemType production.
For our Formal Semantics, it would be very helpful to have a simple type to represent all numerics. For now, we are using the SimpleType name "xs:numeric". In XML Schema terms, this would be a union type. We must coordinate with XML Schema to see if they can support this. If not, we will provide a keyword for numerics in the ItemType production.
The element construction rules in 2.8 make efficient streaming of element construction difficult/impossible. For example, we execute the following expression on a stream and serialize the result in a streaming processing (such as XSLT like applications):
<foo>{"foo", "bar", if (expr) then "baz" else <baz/>}</foo>
If expr is true, then this is serialized:
<foo>foo bar baz</foo>
If expr is false, then this is serialized: <foo>foobar<baz/></foo>
The implementation must cache up the "foo" and "bar" strings, just in case a sub-element node is constructed. If not, then I must insert a space between "foo" and "bar". This seems to contradict one of our explicit use scenarios in the XML Query Requirements (section 2.5).
Is , a dyadic operator or (, , ,) a polyargument operator? The element construction rules seem to indicate the later, but the document is not clear. If , is a dyadic node-concatenation operation, then it would be more streamable than as an argument separator for the element constructor.
Unlike XSLT, attributes seem to be allowed anywhere which makes streaming implementations impossible. XSLT has the following rule:
"The following are all errors:
* Adding an attribute to an element after children have been added to it; implementations may either signal the error or ignore the attribute."
Example:
let $e := expr return <a>{<b/>, ($e/@* | $e/*)</a>
XSLT would consider this an error. XQuery does not. This makes streaming impossible (see #element-construction-vs-streaming). Note that while the above query can easily be rewritten, there are cases (e.g. function calls) where the rewrite is not possible.
XQuery should allow implementations to disallow attribute nodes that are specified after the first child node in the sequence. It should not allow disregarding them.
What does XQuery do if assigning a list of element nodes to an attribute if the type of the attribute is not a list type?
Example:
<book isbn="{$i/booknum}" />:
This query implicitly gets rewritten to: <book isbn="{data($i/booknum)}" />
What happens if there are more than one booknum elements and ISBN is untyped or not a list type?
Does the name expression on dynamically computed names in element/attribute constructors be of type QName without implicit cast from string, QName with implicit cast from string, or string?
If the name is constructed by an expression, the expected type is xs:QName. Xs:string is in general implicitly cast to xs:QName (and xs:anyURI).
The current element construction treats sequences of anySimpleType values different from other simple typed values. This seems inconsistent. The document should make it clear why there is a difference. If there is a reason, is the reason good enough?
The data model cannot represent CDATA or CharRef, since the Information Set looses this information.
The XQuery document should make it clear that:
1. CDATA sections and CharRefs inside XQueries that are not embedded inside XML (which is what the XQuery document only talks about), are syntactic helps to write queries that otherwise would need entitization (in the case if CDATA sections) or a unicode input device (CharRefs).
2. Implementations can chose to use this information as serialization hints to preserve the CDATA and entitization.
Should all elements and attributes have type annotations? In particular, should a newly-constructed element or attribute have a generic type annotation such as "anyType", rather than the current proposal in which it has no type annotation at all? (This is largely a cosmetic issue, about whether "anyType" should be denoted by an explicit annotation or by the absence of an annotation.)
The wording in section 2.8.3 needs to be aligned with Data model and F&O; 'lexical representation' needs to be defined differently and be consistent in XQuery, Datamodel, F&O. It probably needs to be string value (canonical value of integer in W3C Schema has a "." so not appropriate [or we need to have our own definition of the canonical value...]).
The current Working Drafts are inconsistent in their definition of a leading slash in a path expresion. A consistent definition needs to be developed.
Decision by: xpath-tf on 2002-07-29 ([link to member only information] )
Decision by: xquery on 2002-07-30 ([link to member only information] )joint f2f, decision missing from minutes confirmed
Decision by: xsl on 2002-07-30 ([link to member only information] )joint f2f, decision missing from minutes confirmed
Leading "/" on a path expression means "root(self::node())": the root node of the tree containing the context item. Note that self::node() (and therefore leading "/") raises a dynamic error if the context item is not a node.
The 2002-06-24 grammar introduces the "binding" production. "assert" is removed from both XQuery and XPath. "binding" currently requires reserved words. Should "binding" be in XPath?
Several reasons NOT to include it in XPath:
- grammar
- semantics don't match function call semantics
- rarely useful
- reads oddly for range variables if (some integer $x in (1,2,"fred") satisfies $x=1)
- biggest of all, users are asking us to simplify. We will get a very adverse reaction if we make "for" expressions more complicated.
But it is worrying to have such a big split between XPath and XQuery.
Should we (or ask schema to) add Schema type names for sequences of homogeneous types?
If we add them now and Schema decide to add them later these would be different as the namespace for the type would be different...
Must Basic XQuery support the SQL/XML mappings? One of the original purposes for Basic XQuery was support for mapping relational data, but the SQL/XML mappings would not be allowed as data in the current definition of Basic XQuery, because they contain (a) user-derived simple types, and (b) named complex types, which would result in type annotations in our data model. Since SQL/XML is the only proposed standard for relational mappings, do we need to ensure that we support it in Basic XQuery?
The Data Model document defines mappings from the PSV Infoset. If we decide it is essential to query arbitrary XML documents with Basic XQuery, should we define interoperable mappings that would create a representation that has no named types other than built-in XML Schema types? For instance, we might state Basic XQuery implementations map user-derived types to the nearest built-in type, do not create type annotations for named complex types.
During the analysis phase, in-scope schema definitions are derived from schemas named in Schema Import clauses.
Should there be additional in-scope schema definitions that are part of the static context? Should there be another set of in-scope schema definitions that are part of the dynamic context? What would that do to static typing? Would this interfere with interoperability?
In particular:
1. Should an environment be allowed to statically predefine schema definitions for a query? This would allow queries on fixed collections or known message types to provide strong type information without forcing users to explicitly import the corresponding schemas.
2. How does type information found dynamically in queried documents affect the query environment?
Does data() dynamically use the type information found in the instances that are queried, even when the types have not been declared in imported schemas? Note that Basic XQuery does not work properly if this is not true, since it must be able to discover the types of elements without importing their definition.
May an instance contain types that have not been imported into the static environment? If we say it may not, then schema imports are needed to query any document that contains types that are not predefined in XQuery.
May documents that are queried have different definitions for the same names? Note that solutions that dynamically load type information from a document into the in-scope schema definitions may try to introduce all such definitions into the static environment, which should cause an error according to our current rules.
If we want Basic XQuery to be able to query documents that have types that are not predefined, then data() must be able to use type information from instances. But if we want to be able to query validated documents that have different schemas this information must not be added to the static environment (or else we must find a way to add more than one schema definition for a given name to the static environment, or say that the static environment is dynamic, or....).
My tentative conclusions:
1. The in-scope schema definitions should be determined statically.
2. data() and many operators must be able to utilize the type information found in a document.
3. As a matter of convenience, it should be possible to import the schemas associated with a single document or with all documents in a collection. For instance, a syntax like the following may be useful:
import schema from collection "jdbc:datadirect:sqlserver://localhost:1433;database='airports'"
or
import schema from document "file:///C:/projects/query/requirements/xml-spec.xsd"
4. Implementations should be allowed to implicitly import schemas into the environment before executing a query, using any of the approved ways above.
The Static Typing Feature is claimed to have a property called "type soundness." However, Dana says she has counterexamples to the claim of type soundness as described in this section (Section 2.4.2.3). (At least sequence type matching breaks TYPE SOUNDNESS so what else breaks it?) We need to examine the claim and make sure it is stated correctly.
What should be the type of an error value? Section 2.4.3 says that it can be one item. Some people think it should be more flexible (any sequence of items), and other people think it should be less flexible (an item of a particular type). Some people think it should be an element with a well-defined structure.
Whitespace in an XSLT attribute value template is significant insofar as it survives the XML rules for normalization of attributes. This means that CRLF combinations and tabs are normalized to x20 spaces, unless they are written as XML character references. I think it's an open question whether XQuery wants to emulate the XML attribute normalization rules.
In XSLT,
<foo bar=" {'x'} "/>
will produce the result <foo bar=" x "/>
while <foo bar=" "/> produces an element containing an attribute whose value is a single CR character.
If XQuery wants to reproduce this behavior exactly, then it's going to have to reproduce the XML treatment of whitespace as well as the XSLT treatment.
But whether it does so or not, I think Mary is right that
<foo bar=" {'x'} "/>
should produce lt;foo bar=" x "/> and not <foo bar="x"/>. There is a difference between element and attribute constructors: attributes have quotes around them, and this sets a different expectation.
Given the following function:
define function foo(xs:anySimpleType $x) returns xs:anySimpleType {$x}
and the untyped data
<a a="1"/><a a="2"/><a a="3"/>
should the following be a (static or dyamic) type error or should it work?
foo(/a/@a)
If it should work, what should the following query return?
count(data(<e>1 2</e>)) count(data(<a b="1 2"/>/@b))
Should it be 1 or 2?
anySimpleType is the base type of all the *primitive* XML Schema datatypes.
List and union types are *generated* (my word, Schema uses the word *derived*) from primitive types and thus, not included in anySimpleType. See the extract from the XML Schema datatypes spec below.
"[Definition:] There exists a conceptual datatype, whose name is anySimpleType, that is the simple version of the ur-type definition from [XML Schema Part 1: Structures]. anySimpleType can be considered as the *base type* of all *primitive* types. The *value space* of anySimpleType can be considered to be the *union* of the *value space*s of all *primitive* datatypes."
Thus, the function call above should result in a (static or dynamic, depending on typing conformance) type error.
The count expressions would always return 1.
Issue: XQuery has not determined what extension mechanisms might be supported. XQuery may support the following:
Four issues were raised in a proposal to restructure sorting in XQuery [1]:
1. Should we add an 'order by' clause to FLWR?
The following syntax has been proposed:
FLWRExpr ::= (ForClause | LetClause)+ SortClause? WhereClause? "return" Expr OrderClause ::= "order by" stable? SortSpecList SortSpecList ::= Expr SortModifier ("," SortSpecList)? SortModifier ::= ("ascending" | "descending")? ("empty" "greatest" | "empty" "least")?
The OrderClause sorts the tuple stream based on the conditions specified in the SortSpecList.
In the status quo, 'sortby' is a standalone postfix expression. FLWR is used to iterate, and 'sortby' is used to sort. This causes certain difficulties, because iteration and sorting are not distinct, unrelated operations - in general, the order in which the output sequence is ordered determines the best order to choose when iterating over the input.
When sorting data created with element constructors, it can sometimes be quite tricky to determine the original source of data in a constructed element. The more complex the expressions that construct the element, the more tricky this becomes. It is also tricky to iterate in an order determined by data that is not returned in a generated sequence.
If we add this clause, should a FLWOR expression that contains an OrderClause but no ForClause result in a semantic error, since there is no tuple stream to sort?
2. If we add an 'order by' clause, should we keep the sortby() expression, or remove it from our language?
Keeping it is convenient for some expressions. Removing it leaves us with a simpler language, and does not require us to explain to our users why we have two ways of doing the same thing.
3. How should we formalize 'order by' - or should we formalize it in Version 1.0?
The most straightforward way to formalize 'order by' is to use tuples, which do not exist in our Data Model, and these would cause significant change to our Formal Semantics. However, the semantics of 'order by' are straightforward.
Our options seem to be:
3.a. Ensure that we know how it would be formalized using tuples, but postpone including this in the Formal Semantics until after Version 1.
3.b. Refuse to add the feature unless it can be formalized with our current Data Model.
3.c. Restrict the feature to functionality easily formalized with our current Data Model.
I believe there was significant enthusiasm for 3.a. in today's telcon.
4. Is the 'order by' clause part of the XPath spec, or is it only in XQuery?
Jonathan
Addition of namespaces in the query prolog to the in-scope namespaces; how is this information carried through to provide input to validation?
Additional aspecs are:
(a) the whole question of how the namesapce context is affected by namespace declarations in element constructors
(b) the general notion (in XQuery, specifically), that the static context can vary for different parts of a query
(c) what information gets through to act as input to validation
Are different conformance levels going to give the same results? Is it possible to get different results for the same query? The principle should be that you either get the same result or a failure. Currently this isn't the case.
[link to member only information] Anders Berglund:
[link to member only information] Kristoffer Rose:
When using the form 'element foo of type T', should 'foo' be a globally declared element in the in-scope schema or not? Should there be constraints on which type T is allowed? The language document assumes foo is globally declared and T is a restriction of the type of foo. The formal semantics does not make that assumption.
Currently "some" doesn't do any filtering, which seems unnatural. We could change the some behaviour to actually do the type filtering.
It is easy to imagine that "some hatsize $h in $seq satisfies $h=3" ignores items in $seq that are not hatsizes. Currently, of course, it causes an error if the sequence might contains things other than hatsizes.
The current XPath/XQuery specification, as well as the Formal semantics document, mandate that the specific arithmetic operation to be executed depends on the runtime type of the arguments. For example, the addition of two variables $x and $y will be executed as an integer addition if the dynamic types of the two values are both subtypes of integer, and does not depend on the static type of the variables $x and $y (which may be decimal).
Implementing this semantics requires a runtime dispatch plus an runtime interaction with the type system for subtype testing. This can be very costly. Moreover, this semantics can prohibit other useful compile time optimizations like index utilization.
We may allow implementations to use either a static or dynamic dispatch for arithmetic operations in order to improve performance.
What interoperability is expected for queries that are executed with and without Schema Import? Does the current text reflect the desired goals?
What interoperability is expected for queries that are executed with and without Static Typing? Does the current text reflect the desired goals?
[link to member only information] Phil Wadler:
Cf. Should different conformance levels give the same result for the same query and data?
Should "Schema Import" and "Static Typing" be independent, optional features or should there be a layer of conformance levels? For XQuery the latter might be "Basic XQuery", "Basic XQuery" + "Schema Import", and "Basic XQuery" + "Schema Import" + "Static Typing".
A new section has been added on Errors and Conformance. All references to the "error value" have been deleted since this value is no longer part of the Data Model.
The grammar has been revised to explicitly represent precedence of operators. This grammar change required editorial changes to some parts of the document, including the description of path expressions.
The grammar appendix has been reworked, and the use of tokens much reduced. A strong effort has been made to reduce reserved keywords. Lexical recognition is now explained more uniformily for XQuery and XPath, and is represented by lexical state transition tables.
A new arithmetic operator, idiv
(integer division) has been added.
A new prefix operator, unordered
, has been added.
The dereference operator (=>
) has been deleted.
The precedes
and follows
operators have been deleted.
The assert
expression has been deleted.
Definitions of constructor functions and cast
expressions have changed. Every built-in type now has a constructor function with the same name as the type. It is now possible to cast to a derived atomic type from xs:string
or from any supertype of the derived type (facets are checked during casting).
The definition of Effective Boolean Value has been changed to return True for a sequence containing both nodes and atomic values.
The rules for Sequence Type Matching have been revised to take into account substitution groups.
The keyword unknown
in a SequenceType has been changed to untyped
.
Material has been added on importation of type definitions from input documents.
Four predefined namespace prefixes have been added: xml
, xs
, xsd
, and xsi
. Also, a default function namespace has been predefined.
Examples based on filter
and shallow
functions have been deleted, since these functions are no longer built-in.
The term context document has been removed from the evaluation context. The semantics of path expressions have been described without reference to this term.
The grammar no longer supports a sequence of consecutive comparison operators such as a < b < c
. This is documented as an incompatibility with XPath 1.0.
New arithmetic functions for date/time values have been added to the Operator Mapping Table.
An additional XPath incompatibility has been documented: A and B
no longer guarantees that B
will not be evaluated if A
is false.
Grammar of path expressions has been reorganized to conform more closely to description in Formal Semantics.
Material has been added on Named Typing, including detailed syntax for SequenceType declaration, explanation of static and dynamic type-checking, and new rules for type-matching in function calls.
Explanatory material has been added on typed values, document order, and the error value.
Some terminology has been changed for consistency with other documents; for example, "simple value" changed to "atomic value".
Some changes have been made to rules for handling untyped data in arithmetic and comparison expressions.
A more detailed specification is provided for the static and dynamic semantics of treat
and assert
.
A new section has been added on validate
expressions.
More details have been provided on the semantics of element and attribute constructors, including their data model representations.
A new section has been added on Input Functions, describing the input(), collection(), and document() functions.
An Operator Mapping Table has been added (Appendix B.)
Quantified expressions now permit multiple variable bindings.
The semantics of sortby
have changed: all ordering keys must now have the same type, and explicit control is provided over the placement of empty sort keys.
The semantics of and
, or
, and quantified expressions have changed so that an implementation is not forced to evaluate all the operand expressions if it encounters an error or a conclusive result.
Union, Intersect, and Except expressions now apply to nodes only, not to atomic values.
The definitions of the precedes and follows operators have been made independent of the preceding and following axes, since these axes are not supported in XQuery.
The operators ==
and !==
have been changed to is
and isnot
.
Quotes are now required around attribute values in element constructors, even if the value is computed by an enclosed expression.
It has been clarified that the result of a dereference operator is a node list in document order without duplicates.
It has been clarified that the default element namespace applies to types as well as to elements.
Document had been completely rewritten during the joint work on XPath (see text in Intro).
The following issues have been resolved:
Should not( () ) == true or () or not3 function be defined?
Do we really require for
at the
XPath expression level?
Datatypes... XQuery suggests that XPath 2.0 should have a richer set of datatypes based on the built-in types of XML Schema and the notion of an ordered sequence.
Do we need a Context Item to track the "current item" in a for itteration, and, if so, how should it work? How should "." work in relation to it?
Does the context include a default namespace declaration?
Do we need a datatype names binding in the context?
How should qname-to-collation bindings be handled?
Implied existential quantifiers
Functions on Empty Sequences... What should happen if a function expecting one element is invoked on an empty sequence?
Functions on Sequences... What should happen if a function expecting one element is invoked on a sequence of more than one element?
Path iteration... How should the current node be passed to a function in a path-step?
Should we use is and isnot instead of == and !==.
Semantics of positional predicates in XPath
Function call rules needed