Copyright © 2001 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 obsoleted by other documents at any time. It is inappropriate to use W3C Working Drafts as reference material or to cite them as other than "work in progress." A list of current public W3C technical reports can be found at http://www.w3.org/TR/.
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. The current version of this document is the first publicly released Working Draft containing the results of integrating these languages.
This document is a work in progress. It contains many open issues, and should not be considered to be fully stable. Vendors who wish to create preview implementations based on this document do so at their own risk. While this document reflects the general consensus of the working groups, there are still controversial areas that may be subject to change.
Comments on this document should be sent to www-xpath-comments@w3.org (archived at http://lists.w3.org/Archives/Public/www-xpath-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).
1 Introduction
2 Expressions
2.1 Basics
2.1.1 Expression Context
2.1.1.1 Static Context
2.1.1.2 Evaluation Context
2.1.2 Type Conversions
2.2 Primary Expressions
2.2.1 Literals
2.2.2 Variables
2.2.3 Parenthesized Expressions
2.2.4 Function Calls
2.2.5 Comments
2.3 Path Expressions
2.3.1 Axis Steps
2.3.1.1 Axes
2.3.1.2 Node Tests
2.3.2 General Steps
2.3.3 Step Qualifiers
2.3.3.1 Predicates
2.3.3.2 Dereferences
2.3.4 Unabbreviated Syntax
2.3.5 Abbreviated Syntax
2.4 Sequence Expressions
2.4.1 Constructing Sequences
2.4.2 Combining Sequences
2.5 Arithmetic Expressions
2.6 Comparison Expressions
2.6.1 Value Comparisons
2.6.2 General Comparisons
2.6.3 Node Comparisons
2.6.4 Order Comparisons
2.7 Logical Expressions
2.8 For Expressions
2.9 Conditional Expressions
2.10 Quantified Expressions
2.11 Datatypes
2.11.1 Referring to Datatypes
2.11.2 Expressions on Datatypes
A Complete BNF
A.1 Grammar
A.2 Precedence Order
A.3 Lexical structure
A.3.1 Lexical States
B References
B.1 Normative References
B.2 Non-normative References
B.3 Background References
B.4 Informative Material
C Glossary
D Backwards Compatibility with XPath 1.0 (Non-Normative)
E XPath 2.0 and XQuery 1.0 Issues (Non-Normative)
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 contains XPath Version 2.0 as a subset. Any expression that is syntactically valid and executes successfully in both XPath 2.0 and XQuery 1.0 will return the same result in both languages. Since these languages are so closely related, their grammars and language descriptions are generated from a common source to ensure consistency, and the editors of these specifications work together closely.
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. [Ed. Note: The current edition of [XQuery 1.0 Formal Semantics] has not incorporated recent language changes; it will be made consistent with this document in its next edition.]
The library of functions and operators supported by XPath is defined in [XQuery 1.0 and XPath 2.0 Functions and Operators].
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.
| [2] | Expr | ::= | OrExpr
| AndExpr | ForExpr | QuantifiedExpr | IfExpr | GeneralComp | ValueComp | NodeComp | OrderComp | InstanceofExpr | RangeExpr | AdditiveExpr | MultiplicativeExpr | UnionExpr | IntersectExceptExpr | UnaryExpr | CastExpr | PathExpr |
Note:
For the grammar productions in the main body of this document, the same Basic EBNF notation is used as in [XML], except that grammar symbols always have initial capital letters. The EBNF contains only non-terminals, and all terminal tokens are expanded for readability. Optional whitespace is not represented. A normative version of the EBNF that includes tokens and token states is presented in the appendix [A Complete BNF].
Note:
The use of a prefix token ":" is allowed on unprefixed QNames to visually distinguish tokens that are spelled the same as keywords. For instance, the following is a path expression containing the element names "for", "if", and "return": :for/:if/:return.
The value of an expression is always a sequence. A sequence is an ordered collection of zero or more items. An item is either a simple value or a node. A simple value consists of a value contained in the value space of one of the primitive datatypes described in [XML Schema], together with a reference to a schema component that describes its type. Schema components are defined in [XQuery 1.0 and XPath 2.0 Data Model]. A node conforms to one of the seven node kinds described in
[XQuery 1.0 and XPath 2.0 Data Model]. Some kinds of nodes have typed values, string values, and names, which can be extracted from the node using accessors. The typed value of a node is a sequence of zero or more simple values. The string value of a node is an instance of the type xs:string. The name of a node is an instance of the type xs:QName.
A sequence containing exactly one item is called a singleton sequence. A sequence containing zero items is called an empty sequence.
In this document, the namespace prefix xs: is considered to be bound to the XML Schema namespace http://www.w3.org/2001/XMLSchema (described in [XML Schema]), and the prefix xf: is considered to be bound to the namespace of XPath/XQuery functions and operators, http://www.w3.org/2001/11/xquery-operators (described in [XQuery 1.0 and XPath 2.0 Functions and Operators]).
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 defined as all information that is available during static analysis of the expression, prior to its evaluation. This information can be used to decide whether the expression contains a static error.
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, an error will be raised. 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 on QNames within the expression.
Default namespace for element names. This is a namespace URI. This namespace is used for any unprefixed QName appearing in a position where an element name is expected.
Default namespace for function names. This is a namespace URI. This namespace is used for any unprefixed QName appearing as the function name in a function call.
In-scope type definitions. This is a set of (QName, type definition) pairs. It defines the set of types that are available for reference within the expression.
In-scope variables. This is a set of (QName, type) pairs. It defines the set of variables that have been declared and are available for reference within the XPath expression. The QName represents the name of the variable, and the type represents its static data type.
In-scope functions. This is a set of (QName, function signature) pairs. It defines the set of functions that are available to be called from within the expression. The QName represents the name of the function, and the function signature specifies the static types of the function parameters and function result.
In-scope collations. This is a set of (QName, collation) pairs. It defines the names of the collations that are available for use in function calls that take a collation name as an argument. A collation may be regarded as an object that supports two functions: a function that given a set of strings, returns a sequence containing those strings in sorted order; and a function that given two strings, returns true if they are considered equal, and false if not.
Default collation. This is a collation. This collation is used by string comparison functions when no explicit collation is specified.
Base URI. This is an absolute URI, used by the xf:document function
when resolving the relative URI of a document to be
loaded, if no explicit base URI is supplied in the function call.
The evaluation context of an expression is defined as information that is available at the time the expression is evaluated. The evaluation context consists of all the components of the static context, and the additional components listed below.
The first four components of the dynamic context (context item, context position, context size, and context document) are called the focus of the expression. The focus enables the processor to keep track of which nodes are being processed by the expression.
The focus for the outermost expression is supplied by the environment in which the expression is evaluated. Certain language constructs, notably the path expression E1/E2
and the filter expression E1[E2], create a new focus for the evaluation of
a sub-expression. In both these constructs, E2 is evaluated once for each
item in the sequence that results from evaluating E1. Each time E2
is evaluated, it is evaluated with a different focus. The focus for evaluating E2
is referred to below as the inner focus, while the focus for evaluating
E1 is referred to as the outer focus. The inner focus exists only while
E2 is being evaluated. When this evaluation is complete, evaluation of the
containing expression continues with its original focus unchanged.
[Ed. Note: See issue 216.]
The context item is the item currently
being processed. An item is either a simple value or a node. When the context item is a node, it can also be referred to as the context node. The context item is returned by the expression ".". When the expressions E1/E2 or E1[E2]
are evaluated, each item in the sequence obtained by evaluating E1 becomes
the context item in the inner focus for an evaluation of E2.
The context position is the position of
the context item within the sequence of items currently being processed. It changes whenever the
context item changes. Its value is always an integer greater than zero.
The context position is returned by the expression position().
When the expressions E1/E2 or E1[E2] are evaluated,
the context position in the inner focus for an evaluation of E2 is the position
of the context item in the sequence obtained by evaluating E1. The position
of the first item in a sequence is always 1 (one). The context position is always less than
or equal to the context size.
The context size is the number of items in
the sequence of items currently being processed.
Its value is always an integer greater than zero.
The context size is returned by the expression last().
When the expressions E1/E2 or E1[E2] are evaluated,
the context position in the inner focus for an evaluation of E2 is the number
of items in the sequence obtained by evaluating E1.
The context document
is the document currently being processed. Its value is a node, which is always
a document node. If there is a context node, and if the tree containing the context node has
a document node as its root, then this document node will be the context document. When
an inner focus is created and the context item in the inner focus is not a node,
or is a node belonging to a tree whose root is not a document node,
then the context document in this inner focus will be the
same as the context document in the outer focus.
The context document is returned by the XPath expression "/", and is
used implicitly as the base for any absolute path expression, as well being used as
input to certain functions such as xf:id.
[Ed. Note: See Issue 217.]
Dynamic variables. This is a set of (QName, type, value) triples. It contains the same QNames as the in-scope variables in the static context for the expression. Each QName is associated with the dynamic type and value of the corresponding variable. The dynamic type associated with a variable may be more specific than the static type associated with the same variable. The value of a variable is, in general, a sequence.
The dynamic types and values of variables are provided by the host language environment in which an XPath expression is being evaluated.
Current date and time. This information represents a point in time during processing of a query. It can be retrieved by the xf:currentDateTime function. If invoked multiple times during the execution of a query, this function always returns the same result.
Certain operators, functions, and syntactic constructs expect a value of a particular type to be supplied: this is referred to as a required type. A required type may be specified in the following ways:
In the signature of a function definition
In the description of an operator
In the description of a syntactic construct, such as the test in a conditional expression
The required type may be specified as a simple type, an optional occurrence of a simple type, a sequence of a simple type, or a sequence of nodes. If no required type is specified, the value may be any sequence. If the value supplied does not conform to the required type, it is converted to the required type by applying the basic conversion rules.
In some cases, the basic conversion rules may invoke a type exception. A type exception may be invoked either statically (during query analysis) or dynamically (during query execution). The handling of type exceptions in XPath is described below.
The basic conversion rules are as follows:
If the required type is a simple type or an optional occurrence of a simple type:
If the given value is a sequence of more than one item, a type exception is invoked. If the given value is a single node, its typed value is extracted by calling its typed value accessor. If the node has no typed value accessor or if its typed value is a sequence containing more than one item, a type exception is invoked.
If the (given or extracted) value has an unknown simple type (as in the case of character data in a schemaless document), an attempt is made to cast it to the required simple type. If the cast fails, a type exception is invoked.
If the (given or extracted) value does not conform to the required type, a type exception is raised. This includes the case in which the (given or extracted) value is an empty sequence and the required type is not an optional occurrence.
If the required type is a sequence of a simple type:
If the given value is a sequence containing one or more nodes, each such node is replaced by its typed value, resulting in a sequence of simple values. Each of these simple values then is converted to the required type by applying the rules described above for converting values to a required simple type.
If the required type is a sequence of nodes:
If the given value contains any item that is not a node, a type exception is invoked.
Ed. Note: In order to handle user-defined function signatures, the notion of "required type" must be extended to include the full datatype syntax in 2.11 Datatypes. The basic conversion rules must be extended to deal with complex types. For example, can an element of a given type be used where an element of a supertype is expected? Can an element be used where another element in the same substitution group is expected?
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 to treat a type exception as an error, or it may choose to handle the exception by applying a fixed set of rules called fallback conversions.
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 language environment that implements fallback conversions must apply the following rules, in order:
If the required type is anything other than a simple type or a single node, an 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, an 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 simple value, only the first of these simple values is retained. The resulting (supplied or extracted) simple value is converted to the required type according to the rules in the following table:
| boolean type | string type | number type | other simple 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. | 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 simple value, as defined in the data model. | N/A | Attempt to cast the value to the given simple type, using the tables defined in [XQuery 1.0 and XPath 2.0 Functions and Operators]. If a cast can not be done, an error occurs, otherwise a warning should be given. |
| other simple 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 a cast can not be done, an error occurs. If precision is lost, a warning should be given. | Attempt to cast the value to a string, using the tables defined in [XQuery 1.0 and XPath 2.0 Functions and Operators]. If a cast can not be done, an error occurs. If precision is lost, a warning should be given. | Attempt to cast the value to a number, using the tables defined in [XQuery 1.0 and XPath 2.0 Functions and Operators]. If a cast can not be done, an error occurs. If precision is lost, a warning should be given. | Attempt to cast the value to the given simple type, using the tables defined in [XQuery 1.0 and XPath 2.0 Functions and Operators]. If a cast can not be done, an error occurs, otherwise a warning should be given. |
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.
Primary expressions are the basic primitives of the language.
| [38] | PrimaryExpr | ::= | Variable
| Literal | FunctionCall | ParenthesizedExpr |
A literal is a direct syntactic representation of a simple value. XPath supports two kinds of literals: string literals and numeric literals.
| [40] | Literal | ::= | NumericLiteral | StringLiteral |
| [39] | NumericLiteral | ::= | IntegerLiteral | DecimalLiteral | DoubleLiteral |
| [132] | IntegerLiteral | ::= | [0-9]+ |
| [133] | DecimalLiteral | ::= | ("." [0-9]+) | ([0-9]+ "." [0-9]*) |
| [134] | DoubleLiteral | ::= | (("." [0-9]+) | ([0-9]+ ("." [0-9]*)?)) ([e] | [E]) ([+] | [-])? [0-9]+ |
| [141] | StringLiteral | ::= | (["] [^"]* ["]) | (['] [^']* [']) |
The value of a string literal is a singleton sequence
containing an item whose primitive type is xs:string and whose value is
the string denoted by the characters between the delimiting quotation
marks.
The value of a numeric literal containing no "." and no e or
E character is a singleton sequence containing an item whose
type is xs:integer
and whose value is obtained
by parsing the numeric literal according to the rules of the xs:integer
datatype.
The value of a numeric literal containing "." but no e or
E character is a singleton sequence containing an item whose
primitive type is xs:decimal
and whose value is obtained
by parsing the numeric literal according to the rules of the xs:decimal
datatype. The value of a numeric literal containing an e or
E character is a singleton sequence containing an item whose
primitive type is xs:double and whose value is obtained
by parsing the numeric literal according to the rules of the xs:double
datatype.
Here are some examples of literal expressions:
"12.5" denotes the string containing the
characters '1', '2', '.', and '5'.
12 denotes the integer value twelve.
12.5 denotes the decimal value twelve and one half.
125E2 denotes the double value twelve thousand,
five hundred.
Values of other XML Schema built-in types can be constructed by calling the constructor for the given type. The constructors for XML Schema built-in types are defined in [XQuery 1.0 and XPath 2.0 Functions and Operators]. For example:
xf:true() and xf:false() return the
boolean values true and false, respectively.
xf:integer("12") returns the integer value twelve.
xf:date("2001-08-25")
returns an
item whose simple type is xs:date and whose value represents the date 25th
August 2001.
It is also possible to construct values of other built-in types using
the cast expression.
For example:
cast as xs:positiveInteger(12) returns a simple value whose primitive value is the decimal value 12.0 and whose type is the built-in derived type xs:positiveInteger.
A variable evaluates to the value to which the variable's QName is bound in the evaluation context. It is an error if the variable's QName is not defined in the evaluation context. Variables can be bound by clauses in For expressions and Quantified expressions, and by function calls which bind values to the formal parameters of functions.
XPath also allows variables to be bound in the host language environment.
| [124] | Variable | ::= | "$" QName |
The binding of a variable in an expression
always overrides any in-scope binding of a variable
with the same name. For example,
for $v in (1,2) return for $v in (3,4) return $v
evaluates to (3, 4, 3, 4)
because the definition of $v in the inner
for expression overrides the definition of
$v in the outer for expression.
Parentheses may be used to enforce a particular evaluation order in expressions that contain multiple operators, as shown in the following example:
The expression (2 + 4) * 5 evaluates to thirty;
the parenthesized expression (2 + 4) is evaluated first
and
its result is multiplied by five.
Without parentheses, the expression 2 + 4 * 5 evaluates to
twenty-two, because the multiplication operator has higher precedence
than the addition operator.
Parentheses are also used as delimiters in constructing a sequence, as described in 2.4.1 Constructing Sequences.
A function call consists of a QName followed by a parenthesized list of zero or more expressions. The QName must match the name of an in-scope function in the static context (see 2.1.1 Expression Context). The expressions inside the parentheses provide the arguments of the function call. The number of arguments must equal the number of formal arguments in the function's signature; otherwise an error is raised.
| [42] | FunctionCall | ::= | QName "(" (Expr ("," Expr)*)? ")" |
A function call expression is evaluated as follows:
Each argument expression is evaluated, producing an argument value.
The basic conversion rules are applied for each argument value and its corresponding required type from the function's signature. These rules produce a value of the required type for each function parameter or raise a type exception.
If all argument values can be converted to their corresponding required types, the function is applied to the converted values, and the result of the function call is the result of the function application.
A very common type conversion rule is the
extraction of a simple value from a node. For example, assume that the context node contains an
attribute named color that contains a string. The
required type of the only argument to
xf:upper-case
is string. In the function application:
xf:upper-case(@color)
the typed value of the attribute node color is extracted
before the function is applied.
A large library of functions is defined in [XQuery 1.0 and XPath 2.0 Functions and Operators]. Although functions in that document
have the namespace prefix xf,
this prefix is not required if
the expression context defines a default namespace for the
core library.
The comma operator serves two purposes: it separates actual arguments in a function call, and it separates items in an expression that constructs a sequence (see 2.4.1 Constructing Sequences). To distinguish these two uses, parentheses are used to delimit items in a sequence constructor.
Here are some examples of function calls in which arguments that are literal sequences are delimited with parentheses:
three-argument-function(1, 2, 3) denotes a
function call with three arguments.
two-argument-function((1, 2), 3) denotes a function call
with two arguments, the first of which is a sequence of two values.
two-argument-function(1, ())
denotes a function call with two arguments, the second of which is an empty
sequence.
one-argument-function((1, 2, 3)) denotes a function call
with one argument that is a sequence of three values.
Comments can be used to annotate a expression with informative information. Comments are lexical constructs only, and have no meaning within the expression.
| [49] | ExprComment | ::= | "{--" [^}]* "--}" |
Comments may be used before and after major tokens within expressions . See A.3 Lexical structure for the exact lexical states where comments are recognized.
Ed. Note: The EBNF here should disallow "--}" within the comment, rather than "}".
A path expression locates nodes within a tree, and returns a sequence of distinct nodes in document order. A path expression is always evaluated with respect to an evaluation context. There are two kinds of path expressions: relative and absolute.
| [20] | PathExpr | ::= | AbsolutePathExpr | RelativePathExpr |
| [22] | AbsolutePathExpr | ::= | ("/" RelativePathExpr?) | ("//" RelativePathExpr) |
| [23] | RelativePathExpr | ::= | StepExpr (("/" | "//") StepExpr)* |
| [24] | StepExpr | ::= | AxisStep | GeneralStep |
A relative path expression consists of one or more
steps separated by / or //. The steps in a relative
path expression are composed together from left to right. Each step in
turn selects a sequence of nodes. An initial
sequence of steps is composed together with a following step as
follows: each node selected by the initial sequence is used to provide a focus for the following step, as described in
2.1.1.2 Evaluation Context. The following step is executed for each such focus, and the resulting sequences of nodes are merged, eliminating duplicate node identities and preserving document order. For example,
child::div1/child::para selects the
para element children of the div1 element
children of the context node, or, in other words, the
para element grandchildren that have div1
parents.
An absolute path expression consists of / or // followed by a relative path expression (if the path begins with /, the relative path expression is optional.) A / by itself
selects the root node of the document containing the context node. If
it is followed by a relative path expression, then the path expression
selects the sequence of nodes that would be selected by the relative
path expression relative to the root node of the context document.
The uses of // in path expressions are examples of abbreviated syntax, explained in 2.3.5 Abbreviated Syntax.
The steps in a path expression are of two general kinds, called axis steps and general steps.
| [25] | AxisStep | ::= | (Axis? NodeTest StepQualifiers) | AbbreviatedStep |
| [26] | Axis | ::= | "child" "::" | "descendant" "::" | "parent" "::" | "attribute" "::" | "self" "::" | "descendant-or-self" "::" | "ancestor" "::" | "following-sibling" "::" | "preceding-sibling" "::" | "following" "::" | "preceding" "::" | "namespace" "::" | "ancestor-or-self" "::" |
An axis step begins at the context node, navigates to those nodes that are reachable from the context node via a predefined axis, and selects some subset of the reachable nodes. An axis step has three parts:
an axis, which specifies the relationship between the nodes selected by the axis step and the context node. The axis might be thought of as the "direction of movement" of the axis step.
a node test, which specifies the node type and expanded-name of the nodes selected by the axis step.
zero or more step qualifiers, which further modify the sequence of nodes selected by the axis step.
In the abbreviated syntax for an axis step, the axis can be omitted and other shorthand notations can be used as described in 2.3.5 Abbreviated Syntax.
The unabbreviated syntax for an axis step consists of the axis name and node test
separated by a double colon, followed by zero or more step qualifiers. For example, in
child::para[position()=1], child is the name
of the axis, para is the node test and
[position()=1] is a step qualifier.
The node sequence selected by an axis step is found by generating an initial node sequence from the axis and
node test, and then applying each of the step qualifiers
in turn. The initial node sequence consists of the nodes reachable from the
context node via the specified axis that have the node type and
expanded-name specified by the node test. For example, a location step
descendant::para selects the para element
descendants of the context node: descendant specifies
that each node in the initial node sequence must be a descendant of the
context, and para specifies that each node in the initial
node sequence must be an element named para. The available
axes are described in 2.3.1.1 Axes. The available node tests
are described in 2.3.1.2 Node Tests. Step qualifiers are described in 2.3.3 Step Qualifiers. Examples of axis steps are provided in 2.3.4 Unabbreviated Syntax
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 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 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. Since the self axis always contains at most one node, it makes no difference whether it is a forward or reverse axis. 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.
A node test is a condition that must be true for each node selected by an axis step. The condition may be based on the type of the node and/or its name.
| [27] | NodeTest | ::= | NameTest | KindTest |
| [28] | NameTest | ::= | QName | Wildcard |
| [29] | Wildcard | ::= | "*" | ":"? NCName ":" "*" | "*" ":" NCName |
| [30] | KindTest | ::= | ProcessingInstructionTest
| CommentTest | TextTest | AnyKindTest |
| [31] | ProcessingInstructionTest | ::= | "processing-instruction" "(" StringLiteral? ")" |
| [32] | CommentTest | ::= | "comment" "(" ")" |
| [33] | TextTest | ::= | "text" "(" ")" |
| [34] | AnyKindTest | ::= | "node" "(" ")" |
[Definition: Every axis has a principal node type. If an axis can contain elements, then the principal node type is element; otherwise, it is the type of the nodes that the axis can contain.] Thus:
For the attribute axis, the principal node type is attribute.
For the namespace axis, the principal node type is namespace.
For all other axes, the principal node type is element.
A node test that is a QName
is true if and only if the type of the node (see [XQuery 1.0 and XPath 2.0 Data Model])
is the principal node type and the expanded-name of the node is equal to
the expanded-name specified
by the QName. For example,
child::para selects the para element
children of the context node; if the context node has no
para children, it will select an empty set of nodes.
attribute::href selects the href attribute
of the context node; if the context node has no href
attribute, it will select an empty set of nodes.
A QName in a node test is expanded into an expanded-name using the in-scope namespaces in the expression context. An unprefixed QName used as a nametest has the namespaceURI associated with the default element namespace in the expression context. It is an error if the QName has a prefix that does not correspond to any in-scope namespace.
A node test * is true for any node of the principal
node type. For example, child::* will select all element
children of the context node, and attribute::* will
select all attributes of the context node.
A node test can have the form NCName:*. In this
case, the prefix is expanded in the same way as with a QName, using the context namespace
declarations. It is an error if there is no namespace declaration for
the prefix in the expression context. The node test will be true for
any node of the principal type whose expanded-name has the namespace URI
to which the prefix expands, regardless of the local part of the
name.
A node test can also have the form *:NCName. In this case, the node test is true for any node of the principal node type whose local name matches the given NCName, regardless of its namespace.
The node test text() is true for any text node. For
example, child::text() will select the text node
children of the context node. Similarly, the node test
comment() is true for any comment node, and the node test
processing-instruction() is true for any processing
instruction. The processing-instruction() test may have
an argument that is
a StringLiteral; in this case, it
is true for any processing instruction that has a name equal to the
value of the StringLiteral.
A node test node() is true for any node of any type
whatsoever.
In addition to the axis step format described above, a step in a path expression may take another form, called a general step.
| [35] | GeneralStep | ::= | PrimaryExpr StepQualifiers |
A general step is simply a primary expression, possibly followed by one or more step qualifiers. Since a primary expression may in turn contain any expression in parentheses, a general step may contain any expression.
The expression in the general step must evaluate to a sequence of nodes. The result of the general step is this sequence of nodes, modified by any step qualifiers and sorted if necessary into document order. If the expression in the general step returns any values that are not nodes, an error is raised.
As in the case of an axis step, a general step is executed once if it is the first step in the path expression. If it is not the first step, the general step is executed once for each node selected by the preceding step, using the focus provided by each of these nodes in turn, as described in 2.1.1.2 Evaluation Context. The nodes selected by the general step are then used in turn to provide foci for execution of the following step, if any.
Here are some examples of path expressions that contain general steps:
The path expression in this example begins with a general step that contains a function call. The document function returns the root node of a document.
document("book3.xml")/descendant::author
This is a three-step path expression in which the second step is a general step that uses the | operator (see 2.4.2 Combining Sequences.)
child::school/(child::faculty | child::staff)/child::address
Step qualifiers are of two general forms: predicates, which are used to filter a node sequence by applying some test, and dereferences, which are used to map reference-type attribute nodes into the nodes that they reference.
| [37] | StepQualifiers | ::= | (("[" Expr "]") | ("=>" NameTest))* |
A predicate consists of an expression, called a predicate expression, enclosed in square brackets. A predicate serves to filter a node sequence, retaining some nodes and discarding others. For each node in the node sequence to be filtered, the predicate expression is evaluated using a focus derived from that node, as described in 2.1.1.2 Evaluation Context. The result of the predicate expression is coerced to a Boolean value, called the predicate truth value, as described below. Those nodes for which the predicate truth value is true are retained, and those for which the predicate truth value is false are discarded.
The predicate truth value is derived by applying the following rules, in order:
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 one simple value of a numeric type, the value is rounded to an integer using the rules of the round function, and the predicate truth value is true if and only if the resulting integer is equal to the value of the context position.
If the value of the predicate expression is one simple value of type Boolean, the predicate truth value is equal to the value of the predicate expression.
If the value of the predicate expression is a sequence containing at least one node, the predicate truth value is true. Note that the predicate truth value in this case does not depend on the content of the node.
In any other case, an error is raised.
In a sequence of nodes selected by an axis step, the context positions of the nodes are determined in a way that depends on the axis. If the axis is a forward axis, context positions are assigned to the nodes in document order. If the axis is a reverse axis, context positions are assigned to the nodes in reverse document order. In either case, the first context position is 1.
Here are some examples of steps that contain predicates:
This example selects the second "chapter" element that is a child of the context node:
child::chapter[2]
This example selects all the descendants of the context node whose name is "toy" and whose "color" attribute has the value "red":
descendant::toy[attribute::color = "red"]
This example selects all the "employee" children of the context node that have a "secretary" subelement:
child::employee[secretary]
A dereference operates on a node sequence, mapping element and/or attribute nodes into the nodes that they reference. Every node in the sequence that is input to the dereference must be an element or attribute node whose content is of type IDREF or IDREFS; otherwise an error is raised. The dereference generates a new sequence consisting of the element nodes whose ID-type attribute values match the IDREF values extracted from the elements and attributes in the input sequence. The resulting sequence is filtered by the NameTest that follows the dereference operator, retaining only nodes whose expanded-names match the expanded-name specified in the NameTest. The filtered sequence of element nodes is then sorted into document order.
Here are some examples of steps that contain dereferences:
This example selects the figure that is referenced by the first figure reference that is a child of the context node:
child::figref[1]/attribute::refid=>figure
This example selects the manager of the manager of the context node, assuming that the context node is an emp node and that each emp node has a manager attribute that references the emp node of the employee's manager:
attribute::manager=>emp/attribute::manager=>emp
This section provides a number of examples of path expressions in which the axis is explicitly specified in each step. The syntax used in these examples is called the unabbreviated syntax. In many common cases, it is possible to write path expressions more concisely using an abbreviated syntax, as explained in 2.3.5 Abbreviated Syntax.
child::para selects the
para element children of the context node
child::* selects all element
children of the context node
child::text() selects all text
node children of the context node
child::node() selects all the
children of the context node, whatever their node type
attribute::name selects the
name attribute of the context node
attribute::* selects all the
attributes of the context node
descendant::para selects the
para element descendants of the context node
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 document root (which is
always the parent of the document element)
/descendant::para selects all the
para elements in the same document as the context node
/descendant::olist/child::item selects all the
item elements that have an olist parent and
that are in the same document as the context node
child::para[position()=1] selects the first
para child of the context node
child::para[position()=last()] selects the last
para child of the context node
child::para[position()=last()-1] selects
the last but one para child of the context node
child::para[position()>1] selects all
the para children of the context node other than the
first para child of the context node
following-sibling::chapter[position()=1]
selects the next chapter sibling of the context node
preceding-sibling::chapter[position()=1]
selects the previous chapter sibling of the context
node
/descendant::figure[position()=42] selects
the forty-second figure element in the
document
/child::doc/child::chapter[position()=5]/child::section[position()=2]
selects the second section of the fifth
chapter of the doc document
element
child::para[attribute::type="warning"]
selects all para children of the context node that have a
type attribute with value warning
child::para[attribute::type='warning'][position()=5]
selects the fifth para child of the context node that has
a type attribute with value
warning
child::para[position()=5][attribute::type="warning"]
selects the fifth para child of the context node if that
child has a type attribute with value
warning
child::chapter[child::title='Introduction']
selects the chapter children of the context node that
have one or more title children with string-value equal to
Introduction
child::chapter[child::title] selects the
chapter children of the context node that have one or
more title children
child::*[self::chapter or self::appendix]
selects the chapter and appendix children of
the context node
child::*[self::chapter or
self::appendix][position()=last()] selects the last
chapter or appendix child of the context
node
| [36] | AbbreviatedStep | ::= | "." | ".." | ("@" NameTest StepQualifiers) |
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 to @. For
example, a path expression para[@type="warning"] is short
for child::para[attribute::type="warning"] and so selects
para children with a type attribute with
value equal to warning.
// 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 . is short for
self::node(). This is particularly useful in
conjunction with //. For example, the path expression
.//para is short for
self::node()/descendant-or-self::node()/child::para
and so will select all para descendant elements of the
context node.
A step consisting of .. is short for
parent::node(). For example, ../title is
short for parent::node()/child::title and so will
select the title children of the parent of the context
node.
Here are some examples of path expressions that use the abbreviated syntax:
para selects the para element children of
the context node
* selects all element children of the
context node
text() selects all text node children of the
context node
@name selects the name attribute of
the context node
@* selects all the attributes of the
context node
para[1] selects the first para child of
the context node
para[last()] selects the last para child
of the context node
*/para selects all para grandchildren of
the context node
/doc/chapter[5]/section[2] selects the second
section of the fifth chapter of the
doc
chapter//para selects the para element
descendants of the chapter element children of the
context node
//para selects all the para descendants of
the document root and thus selects all para elements in the
same document as the context node
//olist/item selects all the item
elements in the same document as the context node that have an
olist parent
. selects the context node
.//para selects the para element
descendants of the context node
.. selects the parent of the context node
../@lang selects the lang attribute
of the parent of the context node
para[@type="warning"] selects all para
children of the context node that have a type attribute with
value warning
para[@type="warning"][5] selects the fifth
para child of the context node that has a type
attribute with value warning
para[5][@type="warning"] selects the fifth
para child of the context node if that child has a
type attribute with value warning
chapter[title="Introduction"] selects the
chapter children of the context node that have one or
more title children with string-value equal to
Introduction
chapter[title] selects the chapter
children of the context node that have one or more title
children
employee[@secretary and @assistant] selects all
the employee children of the context node that have both a
secretary attribute and an assistant
attribute
book/(chapter|appendix)/section selects
every section element that has a parent that is either
a chapter or an appendix element, that in turn is a child
of a section element that is a child of the context node.
book/xf:ID(publisher)/name returns the same
result as xf:ID(book/publisher)/name.
XPath supports operators to construct and combine sequences. A sequence is an ordered collection of zero or more items. An item may be a simple value or a node.
| [41] | ParenthesizedExpr | ::= | "(" ExprSequence? ")" |
| [1] | ExprSequence | ::= | Expr ("," Expr)* |
| [13] | RangeExpr | ::= | Expr "to" Expr |
One way to construct a sequence is with a ParenthesizedExpr, which is zero or more expressions separated by the comma (",") operator and delimited by parentheses. A parenthesized expression is evaluated by evaluating each of its constituent expressions and concatenating the resulting sequences, in order, into a single result sequence. A sequence may contain duplicate values or nodes, but a sequence is never an item in another sequence. When a new sequence is created by concatenating two or more input sequences, the new sequence contains all the items of the input sequences and its length is the sum of the lengths of the input sequences.
Here are some examples of expressions that construct sequences:
This expression is a sequence of five integers:
(10, 1, 2, 3, 4)
This expression constructs one sequence from the sequences 10, (1, 2), the empty sequence (), and (3, 4):
(10, (1, 2), (), (3, 4))
It evaluates to the sequence:
(10, 1, 2, 3, 4)
This expression contains all salary children
of the context node followed by all bonus children:
(salary, bonus)
Assuming that $price is bound to the value
10.50, this expression:
($price, $price)
evaluates to the sequence
(10.50, 10.50)
A RangeExpr can be used to construct a sequence of
consecutive integers. The
to operator takes two operands, both of which have a required type of integer. A sequence is constructed
containing the two integer operands and every integer between the two
operands.
If the first operand is less than the second, the
sequence is in increasing order, otherwise it is in decreasing order.
This example uses a range expression inside a sequence expression:
(10, 1 to 4)
It evaluates to the sequence:
(10, 1, 2, 3, 4)
| [16] | UnionExpr | ::= | Expr ("union" | "|") Expr |
| [17] | IntersectExceptExpr | ::= | Expr ("intersect" | "except") Expr |
XPath provides several operators for combining sequences.
The union and | operators are
equivalent.
They take two sequences as operands
and return a sequence containing all the items that occur in either of the operands.
The intersect operator
takes two sequences as operands and
returns a sequence containing all the items that occur in both operands.
The except operator
takes two sequences as operands and
returns a sequence containing all the items that occur in the first operand but not
in the second operand.
All of these operators eliminate duplicates from their result sequences. Two nodes are considered to be duplicates if they have the same node identity. Two simple values are considered to be duplicates if they return true when used as operands of the eq operator.
In the result sequences returned by these operators, nodes appear in document order, but the order of simple values is implementation-defined.
Here are some examples of expressions that combine sequences.
Assume in the following examples that there are three elements, <a/>, <b/>, and <c/>, and three sequences that contain these elements:
$seq1 = (<a/>, <b/>),
$seq2 = (<a/>, <b/>), and
$seq3 = (<b/>, <c/>). Then:
$seq1 union $seq1 evaluates to
(<a/>, <b/>).
$seq2 union $seq3
evaluates to (<a/>, <b/>, <c/>).
$seq1 intersect $seq1
evaluates to (<a/>, <b/>).
$seq2 intersect $seq3
evaluates to <b/>.
$seq1 except $seq2 evaluates to
(), the empty sequence.
$seq2 except $seq3
evaluates to <a/>.
The following examples illustrate how sequence-combining operators might be used with sequences of simple values.
(1, 2, 2, 3) union (2, 3, 4) evaluates to (1, 2, 3, 4)
(1, 2, 2, 3) intersect (2, 3, 4) evaluates to (2, 3)
(1, 2, 2, 3) except (2, 3, 4) evaluates to (1)
In addition to the sequence operators described here, [XQuery 1.0 and XPath 2.0 Functions and Operators] includes functions for indexed access to items or sub-sequences of a sequence, for indexed insertion or removal of items in a sequence, and for removing duplicate values or nodes from a sequence.
XPath provides arithmetic operators for addition, subtraction, multiplication, division, and modulus, in their usual binary and unary forms.
| [14] | AdditiveExpr | ::= | Expr ("+" | "-") Expr |
| [15] | MultiplicativeExpr | ::= | Expr ("*" | "div" | "mod") Expr |
| [18] | UnaryExpr | ::= | ("-" | "+") Expr |
The binary subtraction operator must be preceded by white space if it follows an NCName, in order to distinguish it from a hyphen, which is a valid name character. For example, a-b will be interpreted as a single token.
The operands of an arithmetic expression do not have required types. An arithmetic expression is evaluated by applying the following rules, in order, until an error is raised or a value is computed:
If any operand is a sequence of length greater than one, a type exception is raised.
If any operand is an empty sequence, the result is an empty sequence.
If any operand is a node, its typed-value accessor is applied. If the node has no typed-value accessor, or if the typed-value accessor returns a sequence of more than one value, an error is raised. If the typed-value accessor returns the empty sequence, the result of the expression is the empty sequence.
If any operand is an untyped simple value (such as character data in a schemaless document), it is cast to the type suggested by its lexical form. For example, the untyped value 12 is cast to the type xs:integer.
If the arithmetic expression has two numeric operands of different types, one of the operands is promoted to the type of the other operand, following the promotion rules in [XQuery 1.0 and XPath 2.0 Functions and Operators]. For example, a value of type xs:integer can be promoted to xs:decimal, and a value of type xs:decimal can be promoted to xs:double.
If the operand type(s) are valid for the given operator, the operator is applied to the operand(s), resulting in either a simple value or an error (for example, an error might result from dividing by zero.) The combinations of simple types that are accepted by the various arithmetic operators, and their respective result types, are listed in [XQuery 1.0 and XPath 2.0 Functions and Operators]. If the operand type(s) are not valid for the given operator, a type exception is raised.
Ed. Note: A future version of this document will provide a mapping from the arithmetic operators to the functions that implement these operators for various datatypes. See issue 182.
Here are some examples of arithmetic expressions:
In general, arithmetic operations on numeric values result in numeric values:
($salary + $bonus) div 12
Subtraction of two dateTime values results in a duration:
$emp/hiredate - $emp/birthdate
Subtracting a duration from a dateTime results in a dateTime:
$paper/deadline - $paper/worktime
This example illustrates the difference between a subtraction operator and a hyphen:
$unit-price - $unit-discount
Unary operators have higher precedence than binary operators, subject of course to the use of parentheses:
-($bellcost + $whistlecost)
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.
| [9] | ValueComp | ::= | Expr ("eq" | "ne" | "lt" | "le" | "gt" | "ge") Expr |
| [8] | GeneralComp | ::= | Expr ("=" | "!=" | "<" | "<=" | ">" | ">=") Expr |
| [10] | NodeComp | ::= | Expr ("==" | "!==") Expr |
| [11] | OrderComp | ::= | Expr ("<<" | ">>" | "precedes" | "follows") Expr |
Value comparisons are intended for comparing single values. The result of a value comparison is defined by applying the following rules, in order:
If either operand is an empty sequence, the result is an empty sequence.
If either operand is a sequence containing more than one item, an error is raised.
If either operand is a node, its typed value is extracted. If the typed value is an empty sequence, the result of the comparison is an empty sequence. If the typed value is a sequence containing more than one item, an error is raised.
If one of the operands is an untyped simple value (such as character data in a schemaless document) and the other operand is a typed simple value, the untyped operand is cast into the type of the other operand. If both of the operands are untyped values, they are both cast to the type xs:string.
The result of the comparison is true if the value of the first operand is (equal, not equal, less than, less than or equal, greater than, greater than or equal) to the value of the second operand; otherwise the result of the comparison is false. [XQuery 1.0 and XPath 2.0 Functions and Operators] describes which combinations of simple types are comparable, and how comparisons are performed on values of various types. If the value of the first operand is not comparable with the value of the second operand, a type exception is invoked.
Ed. Note: A future version of this document will provide a mapping from the comparison operators to the functions that implement these operators for various datatypes. See issue 182.
Here is an example of a value comparison:
The following comparison is true only if $book1 has a single author subelement and its value is "Kennedy":
$book1/author eq "Kennedy"
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:
Both operands must be either a single node or an empty sequence; otherwise an error is raised.
If either operand is an empty sequence, the result of the comparison is an empty sequence.
A comparison with the == operator is true if the two operands are nodes that have the same identity; otherwise it is false. A comparison with the !== operator is true if the two operands are nodes that have different identities; otherwise it is false. See [XQuery 1.0 and XPath 2.0 Data Model] for a discussion of node identity.
Here is an example of a node comparison:
The following comparison is true only if the left and right sides each evaluate to exactly the same single node:
//book[isbn="1558604820"] == //book[call="QA76.9 C3845"]
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 an 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, or false if the first operand node is later than the second operand node in document order.
A comparison with the >> operator returns true if the first operand node is later than the second operand node in document order, or false if the first operand node is earlier than the second operand node in document order.
A comparison with the precedes operator returns true if the first operand node is reachable from the second operand node using the preceding axis; otherwise it returns false.
A comparison with the follows operator returns true if the first operand node is reachable from the second operand node using the following axis; otherwise it returns false.
Here is an example of an order comparison:
The following comparison is true only if the node identified by the left side occurs before the node identified by the right side in document order:
//purchase[parcel="28-451"] << //sale[parcel="33-870"]
A logical expression is either an and-expression or an or-expression. The value of a logical expression is always one of the boolean values true or false.
| [3] | OrExpr | ::= | Expr "or" Expr |
| [4] | AndExpr | ::= | Expr "and" Expr |
The first step in evaluating a logical expression is to reduce each of its operands to an effective boolean value by applying the following rules, in order:
If the operand is an empty sequence, its effective boolean value is false.
If the operand is one simple boolean value, the operand serves as its own effective boolean value.
If the operand is a sequence that contains at least one node, its effective boolean value is true.
In any other case, a type exception is invoked.
An and-expression returns the value true if the effective boolean values of both of its operands are true; otherwise it returns the value false.
An or-expression returns the value false if the effective boolean values of both of its operands are false; otherwise it returns the value true.
In addition to and- and or-expressions, 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 using the same rules that are used for the operands of logical expressions. It then returns true if the effective boolean value of its parameter is false, and false if the effective boolean value of its parameter is true. The not function is described in [XQuery 1.0 and XPath 2.0 Functions and Operators].
Ed. Note: Functions named
and3,or3, andnot3may be provided to implement three-valued logic. See Issue 28.
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.
| [5] | ForExpr | ::= | ForClause "return" Expr |
| [21] | ForClause | ::= | "for" "$" QName "in" Expr ("," Variable "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 unordered function indicates that the order of a sequence is not significant and can be changed during processing of an expression. Using this function in the
expressions of a for clause allows an implementation
more freedom in optimization, and the resulting
queries may be faster. The following query returns the
same results as above, but the tuples may occur in any order.
for $i in unordered(1, 2),
$j in unordered(3, 4)
return ($i, $j)
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[$b/author = $a]
return $b/title)
Here is the result of the above expression. The result is presented as a 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.
| [7] | IfExpr | ::= | "if" "(" Expr ")" "then" Expr "else" Expr |
The expression following the if keyword is called the test expression, and the expressions following the then and else keywords are called result expressions.
The first step in processing a conditional expression is to find the effective boolean value of the test expression by applying the following rules, in order:
If the test expression returns an empty sequence, its effective boolean value is false.
If the test expression returns one simple boolean value, this value serves as the effective boolean value.
If the test expression returns a sequence that contains at least one node, its effective boolean value is true.
In any other case, a type exception is invoked.
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 first ("then") result expression is returned. If the effective boolean value of the test expression is false, the value of the second ("else") result expression is returned.
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.
| [6] | QuantifiedExpr | ::= | ("some" "$" | "every" "$") QName "in" Expr "satisfies" Expr |
A quantified expression begins with a quantifier which is the keyword some or every. The quantifier is followed by a variable,
the keyword in, a sequence
expression, the keyword
satisfies,
and a test expression.
The sequence expression is evaluated, and for each value in the resulting sequence, the variable is bound to the given value and the test expression is evaluated.
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 sequence expression returns an empty sequence, 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 or returns a single node whose typed value is true; otherwise the quantified expression is false.
This rule implies that, if the sequence expression returns an empty sequence, the value of the quantified expression is true.
The effective boolean value of the test expression is computed by applying the following rules, in order:
If the test expression returns an empty sequence, its effective boolean value is false.
If the test expression returns one simple boolean value, this value serves as the effective boolean value.
If the test expression returns a sequence that contains at least one node, its effective boolean value is true.
In any other case, a type exception is invoked.
Here are some examples of conditional 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)
It is sometimes necessary in XPath to refer to a datatype. Datatypes are used in specifying the parameters of functions, and they are used explicitly in several kinds of XPath expressions.
| [43] | Datatype | ::= | (("element" "of" "type" QName) | DTKind | "node" | SimpleType | "item") OccurrenceIndicator |
| [44] | DTKind | ::= | ("element" | "attribute") QName? |
| [45] | SimpleType | ::= | QName |
| [46] | OccurrenceIndicator | ::= | ("*" | "+" | "?")? |
An XML Schema simple type can be referred to by its
QName. For example, xs:string refers to the XML
Schema simple type "string".
A global element or attribute defined in a Schema can be referred to by the keyword element or attribute followed by a QName. Such an element or attribute
must be defined exactly once in a Schema
available to the expression. For example, element duck
refers to the globally defined duck element in some schema that is available to the expression.
One can also refer to all elements that have a given XML
Schema simple or complex type using the element of
type keywords followed by
the QName of the type. For example, element of type
animal refers to any element whose type is
animal. Note that there might be several such
elements--for example, both duck and
dog elements might be of type
animal.
The keyword element without a QName indicates any element node. The keyword attribute without a QName indicates any attribute node. The keyword node indicates a node of any kind, including element, attribute, text, and other nodes as described in [XQuery 1.0 and XPath 2.0 Data Model]. The keyword item indicates either a node or a simple value. These "wildcard" datatypes are useful in writing generic functions that operate on various kinds of values and in dealing with well-formed documents where type information is limited or unknown.
Any datatype can be followed by an occurrence indicator that indicates the allowed number of occurrences, using the following convention:
? indicates zero or one occurrence of the given type
* indicates zero or more occurrences of the given type
+ indicates one or more occurrences of the given type
Here are some examples of datatypes that might be used in XPath expressions:
xs:date refers to the builtin Schema type date
attribute? refers to an optional attribute
element office:letter refers to an element with a specific name
element of type po:address+ refers to one or more elements 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 simple values
Datatypes occur explicitly in several kinds of XPath expressions.
| [12] | InstanceofExpr | ::= | Expr "instance" " |