Copyright © 2003 W3C® (MIT, ERCIM, Keio), All Rights Reserved. W3C liability, trademark, document use and software licensing rules apply.
XPath 2.0 is an expression language that allows the processing of values conforming to the data model defined in [XQuery 1.0 and XPath 2.0 Data Model]. The data model provides a tree representation of XML documents as well as atomic values such as integers, strings, and booleans, and sequences that may contain both references to nodes in an XML document and atomic values. The result of an XPath expression may be a selection of nodes from the input documents, or an atomic value, or more generally, any sequence allowed by the data model. The name of the language derives from its most distinctive feature, the path expression, which provides a means of hierarchic addressing of the nodes in an XML tree. XPath 2.0 is a superset of [XPath 1.0], with the added capability to support a richer set of data types, and to take advantage of the type information that becomes available when documents are validated using XML Schema. A backwards compatibility mode is provided to ensure that nearly all XPath 1.0 expressions continue to deliver the same result with XPath 2.0; exceptions to this policy are noted in [H Backwards Compatibility with XPath 1.0].
This section describes the status of this document at the time of its publication. Other documents may supersede this document. A list of current W3C publications and the latest revision of this technical report can be found in the W3C technical reports index at http://www.w3.org/TR/.
This is a public W3C Working Draft for review by W3C Members and other interested parties. Publication as a Working Draft does not imply endorsement by the W3C Membership. This is a draft document and may be updated, replaced or obsoleted by other documents at any time. It is inappropriate to cite this document as other than work in progress.
XPath 2.0 has been defined jointly by the XML Query Working Group and the XSL Working Group (both part of the XML Activity). 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 contains several changes. The section entitled "SequenceType
Matching" has been rewritten and includes new material on handling of
unrecognized types. A new concrete type, xdt:untypedAny, has
been introduced, and the isnot comparison operator has been
removed. Rules for static and dynamic implementations have been clarified. A
complete list of changes can be found in J
Revision Log.
This is a Last Call Working Draft. Comments on this document are due on 15 February 2004. Comments should be sent to the W3C mailing list public-qt-comments@w3.org (archived at http://lists.w3.org/Archives/Public/public-qt-comments/) with [XPath] at the beginning of the subject field.
Patent disclosures relevant to this specification may be found on the XML Query Working Group's patent disclosure page at http://www.w3.org/2002/08/xmlquery-IPR-statements and 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 Dynamic Context
2.2 Processing
Model
2.2.1 Data Model Generation
2.2.2 Schema Import Processing
2.2.3 Expression Processing
2.2.3.1
Static Analysis Phase
2.2.3.2
Dynamic Evaluation Phase
2.2.4 Serialization
2.2.5 Consistency Constraints
2.3 Documents
2.3.1 Document Order
2.3.2 Atomization
2.3.3 Effective Boolean Value
2.3.4 Input Sources
2.4 Types
2.4.1 Predefined Types
2.4.2 Typed Value and String Value
2.4.3 SequenceType Syntax
2.4.4 SequenceType Matching
2.4.4.1
Matching a SequenceType and a Value
2.4.4.2
Matching an ItemType and an Item
2.4.4.3
Matching an ElementTest and an Element
Node
2.4.4.4
Matching an AttributeTest and an Attribute
Node
2.5 Error Handling
2.5.1 Kinds of Errors
2.5.2 Handling Dynamic Errors
2.5.3 Errors and Optimization
2.6 Optional
Features
3 Expressions
3.1 Primary
Expressions
3.1.1 Literals
3.1.2 Variable References
3.1.3 Parenthesized Expressions
3.1.4 Context Item Expression
3.1.5 Function Calls
3.1.6 XPath 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 Node 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.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
3.10.3 Castable
3.10.4 Constructor Functions
3.10.5 Treat
A XPath Grammar
A.1 EBNF
A.1.1 Grammar Notes
A.2 Lexical
structure
A.2.1 White Space Rules
A.2.2 Lexical Rules
A.3 Reserved Function
Names
A.4 Precedence
Order
B Type Promotion and Operator Mapping
B.1 Type Promotion
B.2 Operator Mapping
C Context Components
C.1 Static
Context Components
C.2 Dynamic Context Components
D References
D.1 Normative
References
D.2 Non-normative References
D.3 Non-normative
Informative Material
E Glossary
F Summary of Error Conditions
G Conformance
H Backwards Compatibility with XPath
1.0 (Non-Normative)
H.1 Incompatibilities when
Compatibility Mode is true
H.2 Incompatibilities when
Compatibility Mode is false
H.3 Incompatibilities when using a
Schema
I XPath 2.0 and XQuery 1.0 Issues
(Non-Normative)
J Revision Log (Non-Normative)
J.1 12 November 2003
The primary purpose of XPath is to address the nodes of [XML 1.0] trees. XPath gets its name from its use of a path notation for navigating through the hierarchical structure of an XML document. XPath uses a compact, non-XML syntax to facilitate use of XPath within URIs and XML attribute values.
[Definition: 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, which is defined in the [XQuery 1.0 and XPath 2.0 Data Model] 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:
[XQuery 1.0 and XPath 2.0 Data Model] defines the data model that underlies all XPath expressions.
[XQuery 1.0 and XPath 2.0 Formal Semantics] defines the static semantics of XPath and also contains a formal but non-normative description of the dynamic semantics that may be useful for implementors and others who require a formal definition.
The type system of XPath is based on [XML Schema].
The default function library and the operators supported by XPath are 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 1.0], except that grammar symbols always have initial capital letters. Unless otherwise noted (see A.2 Lexical structure), 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 XPath Grammar]. The appendix should be regarded as the normative version.
In the grammar productions in this document, nonterminal symbols are underlined and literal text is enclosed in double quotes. Certain productions (including the productions that define DecimalLiteral, DoubleLiteral, and StringLiteral) employ a regular-expression notation. The following example production describes the syntax of a function call:
| [60] | FunctionCall |
::= | QName "(" (ExprSingle ("," ExprSingle)*)? ")" |
The production should be read as follows: A function call consists of a QName followed by an open-parenthesis. The open-parenthesis is followed by an optional argument list. The argument list (if present) consists of one or more expressions, separated by commas. The optional argument list is followed by a close-parenthesis.
Certain aspects of language processing are described in this specification as implementation-defined or implementation-dependent.
[Definition: Implementation-defined indicates an aspect that may differ between implementations, but must be specified by the implementor for each particular implementation.]
[Definition: Implementation-dependent indicates an aspect that may differ between implementations, is not specified by this or any W3C specification, and is not required to be specified by the implementor for any particular implementation.]
A language aspect described in this specification as implementation-defined or implementation dependent may be further constrained by the specifications of a host language in which XPath is embedded.
This document normatively defines the dynamic semantics of XPath. The static semantics of XPath are normatively defined in [XQuery 1.0 and XPath 2.0 Formal Semantics]. In this document, examples and material labeled as "Note" are provided for explanatory purposes and are not normative.
The basic building block of XPath is the expression, which is a string of Unicode characters. 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. [Definition: XPath is a functional language, which means that expressions can be nested with full generality. ] [Definition: XPath is also a strongly-typed language in which the operands of various expressions, operators, and functions must conform to the expected types.]
Like XML, XPath is a case-sensitive language. Keywords in XPath use lower-case characters and are not reserved—that is, names in XPath expressions are allowed to be the same as language keywords—except for the list of reserved function-names in A.3 Reserved Function Names.
The value of an expression is always a sequence. [Definition: A sequence is an ordered collection of
zero or more items.] [Definition: An item is either an
atomic value or a
node.] [Definition: 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).] [Definition: A node is an instance of one of the
seven node kinds defined 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.
[Definition: 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). [Definition: A sequence containing zero items is called an empty sequence.]
Names in XPath conform to the syntax in [XML Names]. This document uses the following namespace prefixes(these prefix bindings are illustrative rather than normative):
xs = http://www.w3.org/2001/XMLSchema
xsi = http://www.w3.org/2001/XMLSchema-instance
fn = http://www.w3.org/2003/11/xpath-functions
xdt = http://www.w3.org/2003/11/xpath-datatypes
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 are used without a namespace prefix.
[Definition: 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 dynamic context.
[Definition: 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. If analysis of an expression relies on some component of the static context that has not been assigned a value, a static error is raised.[err:XP0001]
The individual components of the static context are summarized below. Further rules governing the semantics of these components can be found in C.1 Static Context Components.
[Definition: XPath 1.0 compatibility mode.
This value is true if
rules for backward compatibility with XPath Version 1.0 are in effect;
otherwise it is false.]
[Definition: 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.]
[Definition: Default element/type namespace. 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.] The initial default element/type namespace may be provided by the external environment.
[Definition: Default function namespace. This is a namespace URI. This namespace URI is used for any unprefixed QName appearing as the function name in a function call. The initial default function namespace may be provided by the external environment.]
[Definition: In-scope schema definitions. This is a generic term for all the element, attribute, and type definitions that are in scope during processing of an expression.] It includes the following three parts:
[Definition: In-scope type definitions. Each named type definition is identified either by a QName (for a named type) or by an implementation-dependent type identifier (for an anonymous type). The in-scope type definitions include the predefined types as described in 2.4.1 Predefined Types. ]
[Definition: In-scope element declarations. Each element declaration is identified either by a QName (for a top-level element declaration) or by an implementation-dependent element identifier (for a local element declaration). An element declaration includes information about the substitution groups to which this element belongs.]
[Definition: In-scope attribute declarations. Each attribute declaration is identified either by a QName (for a top-level attribute declaration) or by an implementation-dependent attribute identifier (for a local attribute declaration). ]
[Definition: In-scope variables. This is a set of (QName, type) pairs. It defines the set of variables that are available for reference within an expression. The QName is the name of the variable, and the type is the static type of the variable.]
An expression that binds a variable (such as a for,
some, or every expression) extends the in-scope
variables of its subexpressions with the new bound variable and its type.
[Definition: In-scope functions. This component defines the set of functions that are available to be called from within an expression. Each function is uniquely identified by its expanded QName and its arity (number of parameters).] [Definition: Each function has a function signature that specifies the name of the function and the static types of its parameters and its result.]
The in-scope functions include constructor functions, which are discussed in 3.10.4 Constructor Functions.
[Definition: 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.
[Definition: Default collation. This collation is used by string comparison functions and operators when no explicit collation is specified.]
[Definition:
Base URI. This is an absolute URI, used when necessary in the
resolution of relative URIs (for example, by the fn:resolve-uri
function.)]
[Definition: Statically-known documents. This is a
mapping from strings onto types. The string represents the absolute URI of a
resource that is potentially available using the fn:doc
function. The type is the type of the document node that would result from
calling the fn:doc function with this URI as its argument. ] If
the argument to fn:doc is not a string literal that is present
in statically-known documents, then the static type of fn:doc is
document-node()?.
Note:
The purpose of the statically known documents is to provide type
information, not to determine which documents are available. A URI need not
be found in the statically known documents to be accessed using
fn:doc.
[Definition: Statically-known collections.
This is a mapping from strings onto types. The string represents the absolute
URI of a resource that is potentially available using the
fn:collection function. The type is the type of the sequence of
nodes that would result from calling the fn:collection function
with this URI as its argument.] If the argument to fn:collection
is not a string literal that is present in statically-known collections, then
the static type of
fn:collection is node()?.
Note:
The purpose of the statically known collections is to provide type
information, not to determine which collections are available. A URI need not
be found in the statically known collections to be accessed using
fn:collection.
[Definition: The dynamic context of an expression is defined as information that is available at the time the expression is evaluated.] If evaluation of an expression relies on some part of the dynamic context that has not been assigned a value, a dynamic error is raised.[err:XP0002]
The individual components of the dynamic context are summarized below. Further rules governing the semantics of these components can be found in C.2 Dynamic Context Components.
The dynamic context consists of all the components of the static context, and the additional components listed below.
[Definition: 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.
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.
[Definition: The context item is the item
currently being processed in a path expression. An item is either an atomic
value or a node.][Definition: 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.
[Definition: The context position is the
position of the context item within the sequence of items currently being
processed in a path expression. ]It changes whenever the context item
changes. Its value is always an integer greater than zero. The context
position is returned by the expression fn:position(). When an
expression E1/E2 or E1[E2] is evaluated, the
context position in the inner focus for an evaluation of E2 is
the position of the context item in the sequence obtained by evaluating
E1. The position of the first item in a sequence is always 1
(one). The context position is always less than or equal to the context
size.
[Definition: The context size is the number of
items in the sequence of items currently being processed in a path
expression.] Its value is always an integer greater than zero. The context
size is returned by the expression fn:last(). When an expression
E1/E2 or E1[E2] is evaluated, the context size in
the inner focus for an evaluation of E2 is the number of items
in the sequence obtained by evaluating E1.
[Definition: Dynamic variables. This is a set of (QName, value) pairs. It contains the same QNames as the in-scope variables in the static context for the expression. The QName is the name of the variable and the value is the dynamic value of the variable.]
[Definition: Function implementations. Each function in in-scope functions has a function implementation that enables the function to map instances of its parameter types into an instance of its result type. ]
[Definition: Current date and time. This information
represents an implementation-dependent point in time
during processing of a query or transformation. It can be retrieved by the
fn:current-date, fn:current-time, and
fn:current-dateTime functions. If invoked multiple times during
the execution of a query or transformation, these functions always return the
same result.]
[Definition: 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 xdt:dayTimeDuration that is determined by the host language. See [ISO 8601] for the range of legal values of a timezone.]
[Definition: Available documents. This is a
mapping of strings onto document nodes. The string represents the absolute
URI of a resource. The document node is the root of a tree that represents
that resource using the data
model. The document node is returned by the fn:doc function
when applied to that URI.] The set of available documents is not constrained
by the set of statically-known documents, and it may be empty.
[Definition: Available collections. This
is a mapping of strings onto sequences of nodes. The string represents the
absolute URI of a resource. The sequence of nodes represents the result of
the fn:collection function when that URI is supplied as the
argument. ] The set of available collections is not constrained by the set of
statically-known collections, and it may be empty.
XPath is defined in terms of the data model and in terms of the expression context.
Figure 1: Processing Model Overview
Figure 1 provides a schematic overview of the processing steps that are discussed in detail below. Some of these steps are completely outside the domain of XPath; in Figure 1, these are depicted outside the line that represents the boundaries of the language, an area labeled the external processing domain. The external processing domain includes generation of the data model (see 2.2.1 Data Model Generation), schema import processing (see 2.2.2 Schema Import Processing) and serialization (see 2.2.4 Serialization). The area inside the boundaries of the language is known as the XPath processing domain, which includes the static analysis and dynamic evaluation phases (see 2.2.3 Expression Processing). Consistency constraints on the XPath processing domain are defined in 2.2.5 Consistency Constraints.
Before an expression can be processed, the input documents to be accessed by the expression must be represented in the data model. This process occurs outside the domain of XPath, which is why Figure 1 represents it in the external processing domain. Here are some steps by which an XML document might be converted to the data model:
A document may be parsed using an XML parser that generates an XML Information Set (see [XML Infoset]). The parsed document may then 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, its Information Set is preserved. (See DM1 in Fig. 1.)
The Information Set or PSVI may be transformed into the data model by a process described in [XQuery 1.0 and XPath 2.0 Data Model]. (See DM2 in Fig. 1.)
The above steps provide an example of how a document in the data model might be constructed. A document or fragment might also be synthesized directly from a relational database, or constructed in some other way (see DM3 in Fig. 1.) XPath is defined in terms of operations on the data model, but it does not place any constraints on how documents and instances in the data model are constructed.
Each atomic value, element node, and attribute node in the data model is annotated with its
dynamic type. The dynamic
type specifies a range of values—for example, an attribute named
version might have the dynamic type xs:decimal,
indicating that it contains a decimal value. For example, 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 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
xdt:untypedAtomic.
The value of an element is represented by the children of the element
node, which may include text nodes and other element nodes. The 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
xdt:untypedAny.
An atomic value of unknown type is annotated with the type
xdt:untypedAtomic.
The in-scope schema definitions in the static context are provided by the host language (see step SI1 in Figure 1) and must satisfy the consistency constraints defined in 2.2.5 Consistency Constraints.
XPath defines two phases of processing called the static analysis phase and the dynamic evaluation phase (see Fig. 1). An implementation is free to use any strategy or algorithm whose result conforms to these specifications.
[Definition: The static analysis phase depends on the expression itself and on the static context. The static analysis phase does not depend on input data (other than schemas).]
During the static analysis phase, the XPath expression is parsed into an internal representation called the operation tree (step SQ1 in Figure 1). A parse error is raised as a static error.[err:XP0003] The static context is initialized by the implementation (step SQ2). The static context is used to resolve type names, function names, namespace prefixes and variable names.
The operation tree is then normalized by making explicit the implicit operations such as atomization, type promotion and extraction of Effective Boolean Values (step SQ5). The normalization process is described in [XQuery 1.0 and XPath 2.0 Formal Semantics].
If the Static Typing Feature is supported, each
expression is assigned a static
type (step SQ6). [Definition: 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 and XPath 2.0
Formal Semantics].] 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
5 + 1.2 is xs:decimal.
During the static analysis phase, if the Static Typing Feature is in effect and an operand of an expression is found to have a static type that is not appropriate for that operand, a type error is raised.[err:XP0004] 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 either to produce a value of type T or to raise a dynamic error.
During the static analysis phase, if the Static Typing
Feature is in effect and the static type assigned to an expression other than
() is empty, a static error is raised.[err:XP0005] This catches cases in which a query refers to an
element or attribute that is not present in the in-scope schema
definitions, possibly because of a spelling error.
The purpose of type-checking during the static analysis phase is to provide early detection of type errors and to infer type information that may be useful in optimizing the evaluation of an expression.
[Definition: The dynamic evaluation phase occurs after completion of the static analysis phase. During the dynamic evaluation phase, the value of the expression is computed.]
The dynamic evaluation phase can occur only if no errors were detected during the static analysis phase. If the Static Typing Feature is in effect, all type errors are detected during static analysis and serve to inhibit the dynamic evaluation phase. If the Static Typing Feature is not in effect, an implementation is allowed to raise type-related warnings during the static analysis phase, but it must proceed with the dynamic evaluation phase despite these warnings. In this case, type errors must be detected and raised during the dynamic evaluation phase.
The dynamic evaluation phase depends on the operation tree of the expression being evaluated (step DQ1), on the input data (step DQ4), and on the dynamic context (step DQ5), which in turn draws information from the external environment (step DQ3) and the static context (step DQ2). Execution of the evaluation phase may create new data-model values (step DQ4) and it may extend the dynamic context (step DQ5)—for example, by binding values to variables.
[Definition: A dynamic type is associated with each value as it is computed. The dynamic type of a value may be either a structural description (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 evaluation 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 error is raised.[err:XP0006]
Even though static typing can catch many type errors before an expression is executed, it is
possible for an expression to raise an error during evaluation that was not
detected by static analysis. 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 whose
static type is
xdt:untypedAtomic. 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.
When the Static Typing Feature is in effect, it is also possible for static analysis of an expression to raise a type error, even though execution of the expression on certain inputs would be successful. For example, an expression might contain a function that requires an element as its parameter, and the static analysis phase might infer the static type of the function parameter to be an optional element. This case is treated as a type error and inhibits evaluation, even though the function call would have been successful for input data in which the optional element is present.
[Definition: Serialization is the process of converting a set of nodes from the data model into a sequence of octets (step DM4 in Figure 1.) ] The general framework for serialization of the data model is described in [XSLT 2.0 and XQuery 1.0 Serialization].
The host language may provide a serialization option based on this framework.
In order for XPath to be well defined, the data model, the static context, and the dynamic context must be mutually consistent. The consistency constraints listed below are prerequisites for correct functioning of an XPath implementation. Enforcement of these consistency constraints is beyond the scope of this specification.
Some of the consistency constraints use the term data model schema. [Definition: For a given node in the data model, the data model schema is defined as the schema from which the type annotation of that node was derived.] For a node that was constructed by some process other than schema validation, the data model schema consists simply of the type definition that is represented by the type annotation of the node.
For every data model node that has a type annotation other than
xs:anyType, if that type annotation is found in the in-scope schema definitions
(ISSD), then its definition in the ISSD must be the same as its definition in
the data model
schema. Furthermore, all types that are derived by extension from the
given type in the data model schema must also be known by
equivalent definitions in the ISSD.
For every element name EN that is found both in a data model node and in the in-scope schema definitions (ISSD), all elements that are known in the data model schema to be in the same substitution group as EN must also be known in the ISSD to be in the same substitution group as EN.
Every item type (i.e., every element, attribute, or type name) referenced in in-scope variables or in-scope functions must be in the in-scope schema definitions.
For each mapping of a string to a document node in available documents, if there exists a mapping of the same string to a document type in statically-known documents, the document node must match the document type, using the matching rules in 2.4.4 SequenceType Matching.
For each mapping of a string to a sequence of nodes in available collections, if there exists a mapping of the same string to a type in statically-known collections, the sequence of nodes must match the type, using the matching rules in 2.4.4 SequenceType Matching.
The dynamic variables in the dynamic context and the in-scope variables in the static context must correspond as follows:
All variables defined in in-scope variables must be defined in dynamic variables.
For each (variable, type) pair in in-scope variables and the corresponding (variable, value) pair in dynamic variables such that the variable names are equal, the value must match the type, using the matching rules in 2.4.4 SequenceType Matching.
XPath is generally used to process documents. The representation of a document is normatively defined in [XQuery 1.0 and XPath 2.0 Data Model]. The functions used to access documents and collections are normatively defined in [XQuery 1.0 and XPath 2.0 Functions and Operators]. Because documents are centrally important in XPath processing, we provide a summary of some key concepts here.
An ordering called document order is defined among all the nodes used during a given query or transformation, which may consist of one or more trees (documents or fragments). Document order is defined in [XQuery 1.0 and XPath 2.0 Data Model], and its definition is repeated here for convenience.
Document order is a total ordering, although the relative order of some nodes is implementation-dependent. Informally, document order is the order returned by an in-order, depth-first traversal of the data model. Document order is stable, which means that the relative order of two nodes will not change during the processing of a given query or transformation, even if this order is implementation-dependent.
Within a tree, document order satisfies the following constraints:
The root node is the first node.
The relative order of siblings is determined by their order in the XML representation of the tree. A node N1 occurs before a node N2 in document order if and only if the start of N1 occurs before the start of N2 in the XML representation.
Namespace nodes immediately follow the element node with which they are associated. The relative order of namespace nodes is stable but implementation-dependent.
Attribute nodes immediately follow the namespace nodes of the element with which they are associated. The relative order of attribute nodes is stable but implementation-dependent.
Element nodes occur before their children; children occur before following-siblings.
The relative order of nodes in distinct trees is stable but implementation-dependent, subject to the following constraint: If any node in tree T1 is before any node in tree T2, then all nodes in tree T1 are before all nodes in tree T2.
The semantics of some XPath operators depend on a process called atomization. [Definition: Atomization
is applied to a value when the value is used in a context in which a sequence
of atomic values is required. The result of atomization is either a sequence
of atomic values or a type
error. Atomization of a sequence is defined as the result of invoking the
fn:data function on the sequence, as defined in [XQuery 1.0 and XPath 2.0 Functions and
Operators].]
The semantics of fn:data are repeated here for convenience.
The result of fn:data is the sequence of atomic values produced
by applying the following rules to each item in the input sequence:
If the item is an atomic value, it is returned.
If the item is a node, its typed value is returned.
Atomization is used in processing the following types of expressions:
Arithmetic expressions
Comparison expressions
Function calls and returns
Cast expressions
Under certain circumstances (listed below), it is necessary to find the
effective boolean value
of a value. [Definition: The effective boolean value of a value is
defined as the result of applying the fn:boolean function to the
value, as defined in [XQuery 1.0 and XPath
2.0 Functions and Operators].]
The semantics of fn:boolean are repeated here for
convenience. fn:boolean returns false if its
operand is any of the following:
An empty sequence
The boolean value false
A zero-length value of type xs:string or
xdt:untypedAtomic
A numeric value that is equal to zero
The xs:double or xs:float value
NaN
Otherwise, fn:boolean returns true.
The effective boolean value of a sequence is computed implicitly during processing of the following types of expressions:
Logical expressions (and, or)
The fn:not function
Certain types of predicates, such as a[b]
Conditional expressions (if)
Quantified expressions (some, every)
Note:
Note that the definition of effective boolean value is not used when casting a value to the
type xs:boolean.
XPath has a set of functions that provide access to input data. These functions are of particular importance because they provide a way in which an expression can reference a document or a collection of documents. The input functions are described informally here; they are defined in [XQuery 1.0 and XPath 2.0 Functions and Operators].
An expression can access input documents either by calling one of the input functions or by referencing some part of the expression context that is initialized by the external environment, such as a variable or a context item.
The input functions supported by XPath are as follows:
The fn:doc function takes a string containing a URI that
refers to an XML document, and returns a document node whose content is the
data model representation of
the given document.
The fn:collection function takes a string containing a URI,
and returns the data model representation of the collection identified by the
URI. A collection may be any sequence of nodes. For example, the expression
fn:collection("http://example.org")//customer identifies all the
customer elements that are descendants of nodes found in the
collection whose URI is http://example.org.
If a given input function is invoked repeatedly with arguments that resolve to the same absolute URI during the scope of a single query or transformation, each invocation returns the same result.
XPath is a strongly typed language with a type system based on [XML Schema]. The XPath type system is formally defined in [XQuery 1.0 and XPath 2.0 Formal Semantics].
The in-scope type definitions in the static context are initialized with a set of
predefined types that is determined by the host language. This set may
include some or all of the types defined by [XML
Schema] in the namespace http://www.w3.org/2001/XMLSchema,
represented in this document by the namespace prefix xs. It may
also include the types defined in the namespace
http://www.w3.org/2003/11/xpath-datatypes, represented in this
document by the namespace prefix xdt. The types in this
namespace are defined in [XQuery 1.0 and
XPath 2.0 Functions and Operators] and are summarized below.
xdt:anyAtomicType is an abstract type that includes all
atomic values (and no values that are not atomic). It is a subtype of
xs:anySimpleType, which is the base type for all simple types,
including atomic, list, and union types. All specific atomic types such as
xs:integer, xs:string, and
xdt:untypedAtomic, are subtypes of
xdt:anyAtomicType.
xdt:untypedAny is a concrete type used to denote the dynamic
type of an element node that has not been assigned a more specific type. It
has no subtypes. An element that has been validated in skip
mode, or that has a PSVI type property of xs:anyType, is
represented in the Data Model by an element node with the type
xdt:untypedAny.
xdt:untypedAtomic is a concrete type used to denote untyped
atomic data, such as text that has not been assigned a more specific type. It
has no subtypes. An attribute that has been validated in skip
mode, or that has a PSVI property of xs:anySimpleType, is
represented in the Data Model by an attribute node with the type
xdt:untypedAtomic.
xdt:dayTimeDuration is a concrete subtype of
xs:duration whose lexical representation contains only day,
hour, minute, and second components.
xdt:yearMonthDuration is a concrete subtype of
xs:duration whose lexical representation is restricted to
contain only year and month components.
The relationships among the types in the xs and
xdt namespaces are illustrated in Figure 2. The abstract types,
represented by ovals in the figure, may be assigned to an expression during
the static
analysis phase if no more specific type can be inferred for the
expression. During the dynamic evaluation phase, each node or value in
the data model is assigned a concrete type, represented by one of the types
listed in the rectangular boxes in Figure 2. A more complete description of
the XPath type hierarchy can be found in [XQuery 1.0 and XPath 2.0 Functions and
Operators].
Figure 2: Summary of XPath Type Hierarchy
In the data model, every
node has a typed value and a string value. The typed
value of a node is a sequence of atomic values and can be extracted by
applying the fn:data function to the node. The typed value for
each kind of node is defined by the dm:typed-value accessor in
[XQuery 1.0 and XPath 2.0 Data Model]. The string
value of a node is a string and can be extracted by applying the
fn:string function to the node. The string value for each kind
of node is defined by the dm:string-value accessor in [XQuery 1.0 and XPath 2.0 Data Model]. Element and attribute
nodes have a type annotation, which represents (in an implementation-dependent way) the
dynamic (run-time) type
of the node. In the [XQuery 1.0 and XPath 2.0 Data
Model], type annotation is defined by the dm:type accessor;
however, XPath does not provide a way to directly access the type annotation
of an element or attribute node.
The relationship between the typed value and the string value for various kinds of nodes is described and illustrated by examples below.
For text, document, and namespace nodes, the typed value of the node is
the same as its string value, as an instance of the type
xdt:untypedAtomic. (The string value of a document node is
formed by concatenating the string values of all its descendant text nodes,
in document order.)
The typed value of a comment or processing instruction node is the same as
its string value. It is an instance of the type xs:string.
The typed value of an attribute node with the type annotation
xdt:untypedAtomic is the same as its string value, as an
instance of xdt:untypedAtomic. The typed value of an attribute
node with any other type annotation is derived from its string value and type
annotation in a way that is consistent with schema validation.
Example: A1 is an attribute having string value "3.14E-2" and
type annotation xs:double. The typed value of A1 is the
xs:double value whose lexical representation is
3.14E-2.
Example: A2 is an attribute with type annotation xs:IDREFS,
which is a list datatype derived from the atomic datatype
xs:IDREF. Its string value is "bar baz faz". The
typed value of A2 is a sequence of three atomic values ("bar",
"baz", "faz"), each of type xs:IDREF.
The typed value of a node is never treated as an instance of a named list
type. Instead, if the type annotation of a node is a list type (such as
xs:IDREFS), its typed value is treated as a sequence of the
atomic type from which it is derived (such as xs:IDREF).
For an element node, the relationship between typed value and string value depends on the node's type annotation, as follows:
If the type annotation is xdt:untypedAtomic, or denotes a
complex type with mixed content, then the typed value of the node is equal to
its string value, as an instance of xdt:untypedAtomic.
Note:
Since xs:untypedAny is a complex type with mixed content,
this rule applies to elements whose type is xs:untypedAny.
Example: E1 is an element node having type annotation
xdt:untypedAny and string value "1999-05-31". The
typed value of E1 is "1999-05-31", as an instance of
xdt:untypedAtomic.
Example: E2 is an element node with the type annotation
formula, which is a complex type with mixed content. The content
of E2 consists of the character "H", a child element named
subscript with string value "2", and the character
"O". The typed value of E2 is "H2O" as an instance
of xdt:untypedAtomic.
If the type annotation denotes a simple type or a complex type with simple content, then the typed value of the node is derived from its string value and its type annotation in a way that is consistent with schema validation.
Example: E3 is an element node with the type annotation cost,
which is a complex type that has several attributes and a simple content type
of xs:decimal. The string value of E3 is "74.95".
The typed value of E3 is 74.95, as an instance of
xs:decimal.
Example: E4 is an element node with the type annotation
hatsizelist, which is a simple type derived from the atomic type
hatsize, which in turn is derived from xs:integer.
The string value of E4 is "7 8 9". The typed value of E4 is a
sequence of three values (7, 8, 9),
each of type hatsize.
If the type annotation denotes a complex type with empty content, then the typed value of the node is the empty sequence.
If the type annotation denotes a complex type with element-only content,
then the typed value of the node is undefined. The fn:data
function raises a type error
[err:XP0007] when applied to such
a node.
Example: E5 is an element node with the type annotation
weather, which is a complex type whose content type specifies
element-only. E5 has two child elements named
temperature and precipitation. The typed value of
E5 is undefined, and the fn:data function applied to E5 raises
an error.
[Definition: When it is necessary to refer to a type in an XPath expression, the SequenceType syntax is used. The name SequenceType suggests that this syntax is used to describe the type of an XPath value, which is always a sequence.]
QNames appearing in a SequenceType have their prefixes expanded to namespace URIs by means of the in-scope namespaces and the default element/type namespace. It is a static error [err:XP0008] to use a TypeName in an ElementTest or AttributeTest if that name is not found in the in-scope type definitions. It is a static error [err:XP0008] to use an ElementName in an ElementTest if that name is not found in the in-scope element definitions unless a TypeNameOrWildcard is specified. It is a static error [err:XP0008] to use a (SchemaContextPath ElementName) pair in an ElementTest if the ElementName can not be located from the in-scope element definitions using the SchemaContextPath. It is a static error [err:XP0008] to use an AttributeName in an AttributeTest if that name is not found in the in-scope attribute definitions unless a TypeNameOrWildcard is specified. It is a static error [err:XP0008] to use a (SchemaContextPath AttributeName) pair in an AttributeTest if the AttributeName can not be located from the in-scope attribute definitions using the SchemaContextPath. If a QName that is used as an AtomicType is not defined as an atomic type in the in-scope type definitions, a static error is raised. [err:XP0051]
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(po:shipto, po:address) refers to an element that has
the name po:shipto (or is in the substitution group of that
element), and has the type annotation po:address (or a subtype
of that type)
element(po:shipto, *) refers to an element named
po:shipto (or in the substitution group of
po:shipto), with no restrictions on its type
element(*, po:address) refers to an element of any name that
has the type annotation po:address (or a subtype of
po:address). If the keyword nillable were used
following po:address, that would indicate that the element may
have empty content and the attribute xsi:nil="true", even though
the declaration of the type po:address has required content.
node()* refers to a sequence of zero or more nodes of any
type
item()+ refers to a sequence of one or more nodes or atomic
values
[Definition: During evaluation of an
expression, it is sometimes necessary to determine whether a value with a
known type "matches" an expected type, expressed in the SequenceType syntax.
This process is known as SequenceType matching.] For example, an
instance of expression returns true if the actual
type of a given value matches a given type, or false if it does
not.
Note:
In this specification, the word "type", when used without modification, represents a type that can be expressed using the SequenceType production. When we refer specifically to W3C XML Schema simple or complex types, appropriate modifiers are used to make this clear.
The rules for SequenceType matching compare the actual type
of a value with an expected type. These rules are a subset of the static
typing rules defined in [XQuery 1.0 and
XPath 2.0 Formal Semantics], which compare the static type of an
expression with the expected type of the context in which the expression is
used. The static typing rules are a superset of the SequenceType
matching rules because the static type of an expression is typically more
general than the dynamic type of the value produced by evaluating the
expression. For example, the static type of the expression if (expr)
then "true" else 0 is xs:string | xs:integer, as
described in [XQuery 1.0 and XPath 2.0
Formal Semantics]. However, if expr evaluates to
true, then the dynamic type of this expression is
xs:string.
Some of the rules for SequenceType matching require matching of simple or complex types to determine whether a given type is the same as or derived from an expected type. These types may be "known" types, which are defined in the in-scope schema definitions, or "unknown" types, which are not defined in the in-scope schema definitions. An unknown type might be encountered, for example, if the module in which the given type is encountered does not import the schema in which the given type is defined. In this case, an implementation is allowed (but is not required) to provide an implementation-dependent mechanism for determining whether the unknown type is compatible with the expected type. For example, an implementation might maintain a data dictionary containing information about type hierarchies.
We define the process of matching simple or complex types using a
pseudo-function named type-matches(ET,
AT) that takes an expected simple or complex type
ET and an actual simple or complex type AT, and either
returns a boolean value or raises a type error. [err:XP0004][err:XP0006] This pseudo-function type-matches
is defined as follows:
type-matches(ET, AT) returns
true if:
AT is a known type, and is the same as ET, or is derived by one or more steps of restriction or extension from ET, or
AT is an unknown type, and an implementation-dependent mechanism is able to determine that AT is derived by restriction from ET.
type-matches(ET, AT) returns
false if:
AT is a known type, and is not the same as ET, and is not derived by one or more steps of restriction or extension from ET, or
AT is an unknown type, and an implementation-dependent mechanism is able to determine that AT is not derived by restriction from ET.
type-matches(ET, AT) raises a
type error [err:XP0004][err:XP0006] if:
ET is an unknown type, or
AT is an unknown type, and the implementation is not able to determine whether AT is derived by restriction from ET.
Note:
The type-matches pseudo-function can not be written as a real
XQuery function, because types are not valid function parameters.
The rules for SequenceType matching are given below, with examples (the examples are for purposes of illustration, and do not cover all possible cases).
The SequenceType empty() matches a value that is the empty
sequence.
An ItemType with no OccurrenceIndicator matches any value that contains exactly one item if the ItemType matches that item (see 2.4.4.2 Matching an ItemType and an Item).
An ItemType with an OccurrenceIndicator matches a value if the number of items in the value matches the OccurrenceIndicator and the ItemType matches each of the items in the value.
An OccurrenceIndicator specifies the number of items in a sequence, as follows:
? matches zero or one items
* matches zero or more items
+ matches one or more items
As a consequence of these rules, any SequenceType whose
OccurrenceIndicator is * or ? matches a value that
is an empty sequence.
An ItemType consisting simply of a QName is interpreted as an
AtomicType. An AtomicType AtomicType matches an atomic value
whose actual type is AT if type-matches(AtomicType,
AT) is true.
Example: The AtomicType xs:decimal matches the value
12.34 (a decimal literal). xs:decimal also matches
a value whose type is shoesize, if shoesize is an
atomic type derived by restriction from xs:decimal.
A named atomic type may be a generic type such as
xdt:anyAtomicType. Note that the names of non-atomic types such
as xs:IDREFS are not accepted in this context, but can often be
replaced by an atomic type with an occurrence indicator, such as
xs:IDREF*.
item() matches any single item.
Example: item() matches the atomic value 1 or
the element <a/>.
node() matches any node.
text() matches any text node.
processing-instruction() matches any processing-instruction
node.
processing-instruction(N) matches any
processing-instruction node whose name (called its "PITarget" in XML) is
equal to N, where N is an NCName.
Example: processing-instruction(xml-stylesheet) matches any
processing instruction whose PITarget is xml-stylesheet.
For backward compatibility with XPath 1.0, the PITarget of a processing
instruction may also be expressed as a string literal, as in this example:
processing-instruction("xml-stylesheet").
comment() matches any comment node.
document-node() matches any document node.
document-node(E) matches any document
node that contains zero or more comments and processing instructions and
contains exactly one element node, if E is an ElementTest that
matches the element node (see 2.4.4.3 Matching
an ElementTest and an Element Node).
Example: document-node(element(book)) matches any document
node containing zero or more comments and processing instructions and exactly
one element node that is matched by the ElementTest
element(book).
An ItemType that is an ElementTest or AttributeTest matches an element or attribute node as described in the following sections.
[Definition: An ElementTest is used to match an element node by its name and/or type.]
In the following rules, ElementName and TypeName are
names that match the corresponding productions in the grammar, where
TypeName is optionally followed by the keyword
nillable. The pair SchemaContextPath ElementName
represents a path that matches the corresponding productions in the grammar.
Note that the SchemaContextPath ElementName pair is just one path;
for instance, the path hospital/staff/person is an example of
such a pair, where hospital/staff/ is the
SchemaContextPath and person is the
ElementName. Two QNames "match" if their expanded forms (URIs and
local names) are identical.
An ElementTest may take one of the following forms:
element(), element(*), and
element(*,*) match any single element node, regardless of its
name or type.
element(ElementName,
TypeName) matches a given element node if:
the name of the element node matches ElementName or matches the name of an element in a substitution group headed by an element with the name ElementName, and:
type-matches(TypeName, AT) is
true, where AT is the type of the given element node.
However, if the given element node has the nilled property, then
this rule is satisfied only if TypeName is followed by the keyword
nillable.
For this form, there is no requirement that ElementName be defined in the in-scope element declarations.
Example: element(person, surgeon) matches an non-nilled
element node whose name is person and whose type annotation is
surgeon.
Example: element(person, surgeon nillable) matches an element
node whose name is person and whose type annotation is
surgeon, and permits the element node to have the
nilled property.
element(ElementName) matches an element
node if:
the name of the element node matches ElementName or matches the name of an element in a substitution group headed by an element with the name ElementName, and:
type-matches(ST, AT) is
true, where ST is the simple or complex type of element
ElementName in the in-scope element declarations, and AT is the type
of the given element node. However, if the given element node has the
nilled property, then this rule is satisfied only if ST
includes the nillable option.
Example: element(person) matches an element node whose name
is person and whose type matches the type of the top-level
person element declaration in the in-scope element
declarations.
element(ElementName, *) matches an
element node of any type if the name of the element matches
ElementName or matches the name of an element in a substitution
group headed by an element with the name ElementName.
For this form, there is no requirement that ElementName be defined in the in-scope element declarations.
Example: element(person, *) matches any element node whose
name is person, regardless of its type.
element(*, TypeName) matches a given
element node regardless of its name, if
type-matches(TypeName, AT) is
true, where AT is the type of the given element node.
However, if the given element node has the nilled property, then
this rule is satisfied only if TypeName is followed by the keyword
nillable.
Example: element(*, surgeon) matches any non-nilled element
node whose type annotation is surgeon, regardless of its
name.
Example: element(*, surgeon nillable) matches any element
node whose type annotation is surgeon, regardless of its name,
and permits the element to have the nilled property.
element(SchemaContextPath ElementName)
matches a given element node if:
the name of the given element node matches the ElementName, and:
type-matches(ST, AT) is
true, where ST is the type of the element declaration
that would be associated with an element named ElementName in the
context identified by SchemaContextPath. (This may be either a
locally declared element or a top-level element.) However, if the given
element node has the nilled property, then this rule is
satisfied only if ST includes the nillable option. If
SchemaContextPath and ElementName together do not identify
a valid schema path in the in-scope schema definitions, a static error is raised.[err:XP0055]
Example: element(hospital/staff/person) matches an element
node whose name is person and whose type matches the type of the
element identified by the schema path hospital/staff/person.
Example: element(type(schedule)/person) matches an element
node whose name is person and whose type matches the type of a
person element within the named type schedule.
[Definition: An AttributeTest is used to match an attribute node by its name and/or type.]
In the following rules, AttributeName and TypeName are
names that match the corresponding productions in the grammar. The pair
SchemaContextPath AttributeName represents a path that matches the
corresponding productions in the grammar. Note that the SchemaContextPath
AttributeName pair is just one path; for instance, the path
catalog/product/price is an example of such a pair, where
catalog/product/ is the SchemaContextPath and
price is the AttributeName. Two QNames "match" if their
expanded forms (URIs and local names) are identical.
An AttributeTest may take one of the following forms:
attribute(), attribute(*), and
attribute(*,*) match any single attribute node, regardless of
its name or type.
attribute(AttributeName,
TypeName) matches a given attribute node if:
the name of the given attribute node matches AttributeName, and:
type-matches(TypeName, AT) is
true, where AT is the type annotation of the given
attribute node.
For this form, there is no requirement that AttributeName be defined in the in-scope attribute declarations.
Example: attribute(price, currency) matches an attribute node
whose name is price and whose type annotation is
currency.
attribute(AttributeName) matches a
given attribute node if:
the name of the given attribute node matches AttributeName, and:
type-matches(ST, AT) is
true, where ST is the simple or complex type of
attribute AttributeName in the in-scope attribute
declarations, and AT is the type of the given attribute
node.
Example: attribute(price) matches an attribute node whose
name is price and whose type annotation matches the top-level
attribute declaration for a price attribute.
attribute(AttributeName, *) matches an
attribute node of any type if the name of the node matches
AttributeName.
For this form, there is no requirement that AttributeName be defined in the in-scope attribute declarations.
Example: attribute(price, *) matches any attribute node whose
name is price, regardless of its type annotation.
attribute(*, TypeName) matches a given
attribute node if type-matches(TypeName,
AT) is true, where AT is the type
annotation of the given attribute node.
Example: attribute(*, currency) matches any attribute node
whose type annotation is currency, regardless of its name.
attribute(SchemaContextPath
AttributeName) matches a given attribute node if:
the name of the given attribute node matches the AttributeName, and:
type-matches(ST, AT) is
true, where ST is the type of the attribute declaration
that would be associated with an attribute named AttributeName in
the context identified by SchemaContextPath. (This may be either a
locally declared attribute or a top-level attribute.)
Example: attribute(catalog/product/price) matches an
attribute node whose name is price and whose type matches the
type of the attribute identified by the schema path
catalog/product/price.
Example: attribute(type(plan)/price) matches an attribute
node whose name is price and whose type matches the type of a
price attribute within the globally defined type
plan.
As described in 2.2.3 Expression Processing, XPath defines an analysis phase, which does not depend on input data, and an evaluation phase, which does depend on input data. Errors may be raised during each phase.
[Definition: A static error is an error that must be detected during the analysis phase. A syntax error is an example of a static error. The means by which static errors are reported during the analysis phase is implementation-defined. ]
[Definition: A dynamic error is an error that must be detected during the evaluation phase and may be detected during the analysis phase. Numeric overflow is an example of a dynamic error. ]
[Definition: A type error may be raised during the analysis or evaluation phase. During the analysis phase, a type error occurs when the static type of an expression does not match the expected type of the context in which the expression occurs. During the evaluation phase, a type error occurs when the dynamic type of a value does not match the expected type of the context in which the value occurs. ]
The outcome of the analysis phase is either success or one or more type errors and/or static errors. The result of the evaluation phase is either a result value, a type error, or a dynamic error.
If any expression (at any level) can be evaluated during the analysis
phase (because all its explicit operands are known and it has no dependencies
on the dynamic context), then any error in performing this evaluation may be
reported as a static error. However, the fn:error() function
must not be evaluated during the analysis phase. For example, an
implementation is allowed (but not required) to treat the following
expression as a static error, because it calls a constructor function with a
constant string that is not in the lexical space of the target type:
xs:date("Next Tuesday")
In addition to static errors, dynamic errors, and type errors, an XPath implementation may raise warnings, either during the analysis phase or the evaluation phase. The circumstances in which warnings are raised, and the ways in which warnings are handled, are implementation-defined.
In addition to the errors defined in this specification, an implementation may raise a dynamic error if insufficient resources are available for processing a given expression. For example, an implementation may specify limitations on the maximum numbers or sizes of various objects. These limitations, and the consequences of exceeding them, are implementation-dependent.
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 raises an error, the implementation may choose which error is raised by the expression. For example, in this expression:
($x div $y) + xs:decimal($z)
both the sub-expressions ($x div $y) and
xs:decimal($z) may raise an error. The implementation may choose
which error is raised by the "+" expression. Once one operand
raises an error, the implementation is not required, but is permitted, to
evaluate any other operands.
A dynamic error carries an error value. [Definition: An error value is a single item or the 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
div operator raises an error if its second operand equals
zero.
An error can be raised explicitly by calling the fn:error
function, which only raises an error and never returns a value. This function
is defined in [XQuery 1.0 and XPath 2.0
Functions and Operators]. The fn:error function takes an
optional item as its parameter, which is the error value. For example, the following function call
raises a dynamic error
whose error value is a string:
fn:error(fn:concat("Unexpected value ", fn:string($v)))
Because different implementations may choose to evaluate or optimize an expression in different ways, the detection and reporting of dynamic errors is implementation-dependent.
When an implementation is able to evaluate an expression without evaluating some subexpression, the implementation is never required to evaluate that subexpression solely to determine whether it raises a dynamic error. For example, if a function parameter is never used in the body of the function, an implementation may choose whether to evaluate the expression bound to that parameter in a function call.
Similarly, in evaluating an expression, an implementation is not required to search for data whose only possible effect on the result would be to raise an error, as illustrated in the following examples.
If an implementation can find (for example, by using an index) that at
least one item returned by $expr1 in the following example has
the value 47, it is allowed to return true as the
result of the some expression, without searching for another
item returned by $expr1 that would raise an error because it is
not an integer.
some $x in $expr1 satisfies $x = 47
In the following example, if an implementation can find (for example, by
using an index) the product element-nodes that have an
id child with the value 47, it is allowed to return
these nodes as the result of the path expression, without searching for
another product node that would raise an error because it has an
id child whose value is not an integer.
//product[id = 47]
In some cases, an optimizer may be able to achieve substantial performance improvements by rearranging an expression so that the underlying operations are performed in a different order than that in which they are written. In such cases, errors may be raised that would not have been raised if the expression were evaluated as written. However, an expression must not be rearranged in a way that changes its result value in the absence of errors.
The expression in the following example cannot raise a casting error if it is evaluated exactly as written (i.e., left to right). An implementation is permitted, however, to reorder the predicates to achieve better performance (for example, by taking advantage of an index). This reordering could cause the expression to raise an error.
$N[@x castable as xs:date][xs:date(@x) gt xs:date("2000-01-01")]
To avoid unexpected errors caused by reordering of expressions, tests that are designed to prevent dynamic errors should be expressed using conditional expressions. Conditional expressions raise only dynamic errors that occur in the branch that is actually selected.
Unlike the previous example, the following example cannot raise a dynamic
error if @x is not castable into an xs:date.
$N[if (@x castable as xs:date)
then xs:date(@x) gt xs:date("2000-01-01")
else false()]
[Definition: XPath 2.0 defines an optional feature called the Static Typing Feature.] An implementation that includes this feature is required to detect type errors during the static analysis phase. If an expression contains one or more static errors or type errors, then a Static Typing implementation must raise at least one of these errors during the static analysis phase.
This section discusses each of the basic kinds of expression. Each kind of
expression has a name such as PathExpr, which is introduced on
the left side of the grammar production that defines the expression. Since
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 order in which expressions are discussed in this document does not reflect the order of operator precedence. In general, this document introduces the simplest kinds of expressions first, followed by more complex expressions. For the complete grammar, see Appendix [A XPath Grammar].
| [15] | XPath |
::= | Expr? |