W3C

XML Path Language (XPath) 2.0

W3C Working Draft 30 April 2002

This version:
http://www.w3.org/TR/2002/WD-xpath20-20020430
Latest version:
http://www.w3.org/TR/xpath20
Previous versions:
http://www.w3.org/TR/2001/WD-xpath20-20011220
Editors:
Anders Berglund (XSL WG), IBM Research <alrb@us.ibm.com>
Scott Boag (XSL WG), IBM Research <scott_boag@us.ibm.com>
Don Chamberlin (XML Query WG), IBM Almaden Research Center <chamberlin@almaden.ibm.com>
Mary F. Fernandez (XML Query WG), AT&T Labs <mff@research.att.com>
Michael Kay (XSL WG), Software AG <Michael.Kay@softwareag.com>
Jonathan Robie (XML Query WG), Invited Expert <jonathan.robie@datadirect-technologies.com>
Jérôme Siméon (XML Query WG), Bell Labs, Lucent Technologies <simeon@research.bell-labs.com>

Abstract

XPath is a language for addressing parts of an XML document.

Status of this Document

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

This document is the result of joint work by the XSL and XML Query Working Groups, which are jointly responsible for XPath 2.0, a language derived from both XPath 1.0 and XQuery. The XPath 2.0 and XQuery 1.0 Working Drafts are generated from a common source. These languages are closely related, sharing much of the same expression syntax and semantics, and much of the text found in the two Working Drafts is identical.

This version of the document contains new details about the type system of XPath, including a syntax for declaring types in function signatures and other expressions. It describes the semantics of several expressions that operate on types, including treat, assert, and validate expressions. It also describes in greater detail the semantics of element and attribute constructors and how they operate on the underlying data model.

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

Public comments on this document and its open issues are welcome. Of particular interest are comments on error handling (see issues 97 and 98.) Comments should be sent to the W3C XPath/XQuery mailing list, public-qt-comments@w3.org (archived at http://lists.w3.org/Archives/Public/public-qt-comments/).

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

Table of Contents

1 Introduction
2 Expressions
    2.1 Basics
        2.1.1 Expression Context
            2.1.1.1 Static Context
            2.1.1.2 Evaluation Context
            2.1.1.3 Input Functions
        2.1.2 Expression Processing
            2.1.2.1 Document Order
            2.1.2.2 Typed Value
        2.1.3 Types
            2.1.3.1 Type Checking
            2.1.3.2 SequenceType
            2.1.3.3 Type Conversions
            2.1.3.4 Fallbacks
    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 Steps
            2.3.1.1 Axes
            2.3.1.2 Node Tests
        2.3.2 Qualifiers
            2.3.2.1 Predicates
            2.3.2.2 Dereferences
        2.3.3 Unabbreviated Syntax
        2.3.4 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 Expressions on Datatypes
    2.12 Validate Expressions

Appendices

A Complete BNF
    A.1 Grammar
    A.2 Precedence Order
    A.3 Lexical structure
        A.3.1 Lexical States
B Type Promotion and Operator Mapping
    B.1 Type Promotion
    B.2 Operator Mapping
C References
    C.1 Normative References
    C.2 Non-normative References
    C.3 Background References
    C.4 Informative Material
D Glossary
E Conformance
F Backwards Compatibility with XPath 1.0 (Non-Normative)
G XPath 2.0 and XQuery 1.0 Issues (Non-Normative)
H Revision Log (Non-Normative)
    H.1 10 Apr 2002
    H.2 20 Dec 2001


1 Introduction

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:

[Ed. Note: A future version of this document will include links between terms (in bold font) and their definitions.]

2 Expressions

2.1 Basics

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
|  ValidateExpr
|  CastExpr
|  RootedPathExpr
|  RelativePathExpr
|  PrimaryExpr
|  StepExpr

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. 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 either a sequence or the error value. A sequence is an ordered collection of zero or more items. An item is either an atomic value or a node. An atomic value is a value in the value space of an XML Schema atomic type, as defined in [XML Schema] (that is, a simple type that is not a list type or a union type). A node conforms to one of the seven node kinds described in [XQuery 1.0 and XPath 2.0 Data Model]. 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.

Error is a special value indicating that an error has been encountered during the evaluation of an expression. Except as noted in this document, if any operand of an expression is the error value, the value of the expression is also the error value.

A sequence containing exactly one item is called a singleton sequence. An item is identical to a singleton sequence containing that item. Sequences are never nested--for example, combining the values 1, (2, 3), and ( ) into a single sequence results in the sequence (1, 2, 3). A sequence containing zero items is called an empty sequence.

In this document, the namespace prefixes xs: and xsi: are considered to be bound to the XML Schema namespaces http://www.w3.org/2001/XMLSchema and http://www.w3.org/2001/XMLSchema-instance, respectively (as described in [XML Schema]), and the prefix xf: is considered to be bound to the namespace of XPath/XQuery functions and operators, http://www.w3.org/2002/04/xquery-operators (described in [XQuery 1.0 and XPath 2.0 Functions and Operators]). In some cases, where the meaning is clear and namespaces are not important to the discussion, built-in XML Schema typenames such as integer and string will be used without a namespace prefix.

2.1.1 Expression Context

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

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

2.1.1.1 Static Context

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

XPath requires the information in the static context to be provided by the language environment in which the expression is being processed. Static context consists of the following components:

  • Type exception policy. This is one of the values strict or flexible. The value indicates the action that should be taken when a type exception is raised. If the policy is strict, the error value will be returned. If the policy is flexible, then a fallback conversion will be invoked; the error value will be returned only if the fallback conversion fails.

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

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

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

  • In-scope schema definitions. This is a set of (QName, type definition) pairs. It defines the set of types that are available for reference within the expression. It includes the built-in schema types and all globally-declared types in imported schemas.

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

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

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

2.1.1.2 Evaluation Context

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

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

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

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

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

  • The context size is the number of items in the sequence of items currently being processed. Its value is always an integer greater than zero. The context size is returned by the expression last(). When an expression E1/E2, E1[E2], or E1 sortby 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.

  • 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 as the base for any rooted path expression, as well being used implicitly by 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:current-dateTime function. If invoked multiple times during the execution of a query, this function always returns the same result.

  • Input sequence. The input sequence is sequence of nodes that can be accessed by the input function. It might be thought of as an "implicit input". The content of the input sequence is determined in an implementation-dependent way.

2.1.1.3 Input Functions

XPath has three functions that provide access to input data. These functions are of particular importance because they provide the only way in which an expression can reference a document or a collection of documents. The three input functions are described informally here, and in more detail in [XQuery 1.0 and XPath 2.0 Functions and Operators].

The input sequence is a part of the evaluation context for an expression. The way in which nodes are assigned to the input sequence is implementation-dependent. For instance, one implementation might provide a fixed mapping from a directory system to the input sequence, another implementation might provide a graphical user interface that allows users to choose a data source for the input sequence, and a third implementation might support UNIX-style pipes, allowing the output of one query to become the input sequence for another query.

The input function returns the input sequence. For example, the expression input()//customer returns all the customer elements that are descendants of nodes in the input sequence. If no input sequence has been bound, the input function returns the error value.

The collection function returns the nodes found in a collection. A collection may be any sequence of nodes. A collection is identified by a string, which must be a valid URI. For example, the expression collection("www.example.com/invoices")//customer identifies all the customer elements that are descendants of nodes found in the collection whose URI is www.example.com/invoices.

The document function, when its first argument is a string containing a single URI that refers to an XML document, returns the root of that document. The document function can also be used to address multiple documents or document fragments; see [XQuery 1.0 and XPath 2.0 Functions and Operators] for details.

2.1.2 Expression Processing

XPath is defined in terms of the [XQuery 1.0 and XPath 2.0 Data Model] (referred to in this document simply as the Data Model), which represents information in the form of nodes, atomic values, and the error value. Before an XPath expression can be processed, the input documents to be operated on by the expression must be represented in the Data Model. For example, an XML document can be converted to the Data Model by the following steps:

  1. The document can be parsed using an XML parser.

  2. The parsed document can be validated against one or more schemas. This process, which is described in [XML Schema], results in an abstract information structure called the Post-Schema Validation Infoset (PSVI). If a document has no associated schema, it can be validated against a permissive default schema that accepts any well-formed document.

  3. The PSVI can be transformed into the Data Model by a process described in [XQuery 1.0 and XPath 2.0 Data Model].

The above steps provide an example of how a Data Model instance might be constructed. A Data Model instance might also be synthesized directly from a relational database, or constructed in some other way. XPath is defined in terms of operations on the Data Model, but it does not place any constraints on how the input Data Model instance is constructed.

Each element or attribute node in the Data Model can be annotated with a dynamic type. If the Data Model was derived from an input XML document, the types of the elements and attributes are derived from schema validation. A newly constructed element or attribute node has no type annotation, but can be given one by a validate expression. The type of an element or attribute indicates its range of values--for example, an attribute named version might have the type xs:decimal, indicating that it contains a decimal value.

The value of an attribute is represented directly within the attribute node. An attribute node whose type is unknown (such as might occur in a schemaless document) is annotated with the type xs:anySimpleType.

The value of an element is represented by the children of the element node, which may include text nodes and other element nodes. The type annotation of an element node indicates how the values in its child text nodes are to be interpreted. An element containing text of unknown type, possibly interleaved with comments and/or processing instructions (such as might occur in a schemaless document), is annotated with the type xs:anySimpleType. However, if an element of unknown type contains subelements, it is annotated with the type xs:anyType.

Atomic values in the Data Model also carry type annotations. An atomic value of unknown type is annotated with the type xs:anySimpleType. Under certain circumstances (such as during processing of an arithmetic operator), an atomic value of xs:anySimpleType may be cast into a more specific type (such as xs:double).

This document provides a user-oriented description of how various kinds of expressions are processed. For each expression, the operands and result are instances of the Data Model. The details of transforming XML documents into the Data Model are described in [XQuery 1.0 and XPath 2.0 Data Model]. Transformation of a Data Model instance into an XML document is currently an open issue.

Two Data Model terms are described here briefly because they are of particular importance for the processing of expressions: document order and typed value. For a more detailed explanation of these terms, see [XQuery 1.0 and XPath 2.0 Data Model].

2.1.2.1 Document Order

Document order defines a total ordering among all the nodes seen by the language processor. Within a given source document, the document node is the first node, followed by element nodes, text nodes, comment nodes, and processing instruction nodes in the order of their representation in the XML document (after expansion of entities). Element nodes occur before their children. The namespace nodes of an element immediately follow the element node, in implementation-defined order. The attribute nodes of an element immediately follow its namespace nodes, and are also in implementation-defined order.

Each input document, and each node or node hierarchy constructed during expression processing, is a separate data model fragment. Document order among data model fragments is implementation-defined but stable within a query.

2.1.2.2 Typed Value

Every node has a typed value, which is a sequence of atomic values. The typed value of any node can be extracted by calling the data function with the node as argument. The typed value for the various kinds of nodes is defined as follows:

  1. The typed value of a document, namespace, comment, or processing instruction node is the error value.

  2. The typed value of a text node is the string content of the node, as an instance of xs:anySimpleType.

  3. The typed value of an element or attribute node that has no type annotation is a sequence of atomic values that is stored in the Data Model.

  4. The typed value of an element or attribute node whose type annotation denotes either a simple type or a complex type with simple content is a sequence of atomic values that is obtained by applying the type annotation to the content of the node, as in the following examples:

    • Example: N is an element node of type hatsizelist, which is a complex type that includes a country attribute. The content of the type hatsizelist is a sequence of items of type hatsize, which is derived from xs:decimal. In XML Schema, this content is considered to have a simple type. The typed value of N is a sequence of values of type hatsize.

    • Example: A is an attribute of type IDREFS, a list type derived from IDREF, and its value is "bar baz faz". The typed value of A is a sequence of three atomic values of type IDREF.

  5. The typed value of an element node whose type annotation denotes a complex type with complex content is the error value.

2.1.3 Types

XPath is a strongly typed language with a type system based on [XML Schema]. The built-in types of XPath include the node kinds of XML (such as element, attribute, and text nodes), the built-in atomic types of [XML Schema] (such as xs:integer and xs:string), and the following special derived types: xs:dayTimeDuration and xs:yearMonthDuration (described in [XQuery 1.0 and XPath 2.0 Functions and Operators]).

When the type of a value is not appropriate for the context in which it is used, a type exception is raised. Languages that are based on XPath 2.0 may handle type exceptions with either a strict or a flexible policy, as described in 2.1.3.4 Fallbacks.

Like XML Schema, XPath distinguishes named types from anonymous types. The set of named types includes all the built-in types and all user-defined simple or complex types for which the type declaration contains a name. Named types are associated with values in one of the following ways:

  • A literal value has a named type; for example, the type of the value 47 is xs:integer.

  • The constructor functions described in [XQuery 1.0 and XPath 2.0 Functions and Operators] return values with named types; for example, xf:date("2002-5-31") returns a value of type xs:date.

  • When an instance of the Data Model is constructed from a validated document, type names assigned by a schema processor are preserved in the Data Model.

  • The validate expression invokes schema validation within a query, assigning type names in the same way that a schema processor would.

  • The cast expression creates an atomic value with a specific named type.

  • Some functions, such as data(), extract typed values from the nodes of a document, preserving the named types of these values.

The XPath type system is formally defined in [XQuery 1.0 Formal Semantics]. This section presents a summary of types from a user's perspective.

2.1.3.1 Type Checking

XPath provides two kinds of type checking, called static type checking and dynamic type checking.

Static type checking is performed during the query analysis phase (also known as "compile time.") Static type checking of an expression is based on the expression itself and on the in-scope schema definitions. Static type checking does not depend on the actual values found in any input document. The purpose of static type checking is to provide early detection of type errors and to compute the type of a query result.

During static type checking, each expression is assigned a static type. In some cases, the static type is derived from the lexical form of the expression; for example, the static type of the literal 5 is xs:integer. In other cases, the static type of an expression is inferred according to rules based on the static types of its operands; for example, the static type of the expression size < 5 is xs:boolean. The static type of an expression may be either a named type or a structural description--for example, xs:boolean? denotes an optional occurrence of the xs:boolean type. The rules for inferring the static types of various expressions are described in [XQuery 1.0 Formal Semantics]. During the analysis phase, if an operand of an expression is found to have a static type that is not appropriate for that operand, a static error is raised. If static type checking raises no errors and assigns a static type T to an expression, then execution of the expression on valid input data is guaranteed to produce either a value of type T or the error value.

Dynamic type checking is performed during the query execution phase (also known as "run time.") Dynamic checking depends on the actual values found in input documents. At run time, a dynamic type is associated with each value as it is computed. The dynamic type of a value may be more specific than the static type of the expression that computed it (for example, the static type of an expression might be "zero or more integers or strings," but at run time its value may have the dynamic type "integer.") If an operand of an expression is found to have a dynamic type that is not appropriate for that operand, a type exception is raised.

The dynamic type of a value may be either a structural type (such as "sequence of integers") or a named type. In many cases, a value that has a structural type can be given a named type by means of a validate expression, which matches the value against known types in the in-scope schema definitions.

It is possible for static type checking of an expression to raise a static type error, even though the expression might evaluate successfully on some valid input data. For example, an expression might contain a function that requires an element as its parameter, and static type checking might infer the static type of the function parameter to be an optional element. In this case, a static type error would result, even though the function call would be successful for input data in which the optional element is present.

It is also possible for an expression to return the error value, even though static type checking of the expression raised no error. For example, an expression may contain a cast of a string into an integer, which is statically valid. However, if the actual value of the string at run time cannot be cast into an integer, the error value will result. Similarly, an expression may apply an arithmetic operator to a value extracted from a schemaless document. This is not a static error, but at run time, if the value cannot be successfully cast to a numeric type, the error value will result.

If an implementation can determine by static analysis that an expression will necessarily return the error value (for example, because it contains a division by the constant zero), the implementation is allowed to report this error at query analysis time (as well as at query execution time).

At user option, static type checking can be disabled. Also, a conformance level may be defined for which implementions need not provide static type checking.

2.1.3.2 SequenceType

When it is necessary to refer to a type in an XPath expression, the syntax shown below is used. This syntax production is called "SequenceType", since it describes the type of an XPath value, which is a sequence.

[48]   SequenceType   ::=   (ItemType OccurrenceIndicator) |  "empty"
[49]   ItemType   ::=   (("element" |  "attribute") ElemOrAttrType?)
|  "node"
|  "processing-instruction"
|  "comment"
|  "text"
|  "document"
|  "item"
|  AtomicType
|  "unknown"
|  "atomic" "value"
[50]   ElemOrAttrType   ::=   SchemaType |  (QName SchemaContext?)
[51]   SchemaType   ::=   QName? "of" "type" QName
[45]   SchemaContext   ::=   "in" SchemaGlobalContext ("/" SchemaContextStep)*
[46]   SchemaGlobalContext   ::=   QName |  ("type" QName)
[47]   SchemaContextStep   ::=   QName
[52]   AtomicType   ::=   QName
[53]   OccurrenceIndicator   ::=   ("*" |  "+" |  "?")?

Here are some examples of SequenceTypes that might be used in XPath expressions:

  • xs:date refers to the built-in Schema type date

  • attribute? refers to an optional attribute

  • element refers to any element

  • element office:letter refers to an element 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 atomic values

During processing of a query, it is sometimes necessary to determine whether a given value matches a type that was declared using the SequenceType syntax. This process is known as SequenceType matching. For example, an instance of expression returns true if a given value matches a given type, or false if it does not.

SequenceType matching between a given value and a given SequenceType is performed as follows:

If the SequenceType is empty, the match succeeds only if the value is an empty sequence. If the SequenceType is an ItemType with no OccurrenceIndicator, the match succeeds only if the value contains precisely one item and that item matches the ItemType (see below). If the SequenceType contains an ItemType and an OccurrenceIndicator, the match succeeds only if the number of items in the value matches the OccurrenceIndicator and each of these items matches the ItemType. As a consequence of these rules, a value that is an empty sequence matches any SequenceType whose occurrence indicator is * or ?.

An OccurrenceIndicator indicates the number of items in a sequence, as follows:

  • ? indicates zero or one items

  • * indicates zero or more items

  • + indicates one or more items

The process of matching a given item against a given ItemType is performed as follows (remember that an item may be a node or an atomic value):

  1. The ItemType item matches any item. For example, item matches the value 1 or the value <a/>.

  2. The following ItemTypes match atomic values:

    1. atomic value matches any atomic value.

    2. A named atomic type matches a value if the dynamic type of the value is the same as the named atomic type or is derived from the named atomic type by restriction. For example, the ItemType xs:decimal matches the value 12.34 (a decimal literal); it also matches a value whose dynamic type is shoesize, if shoesize is a user-defined atomic type derived from xs:decimal.

    3. unknown matches an atomic value whose most specific type is xs:anySimpleType.

  3. The following ItemTypes match nodes:

    1. node matches any node.

    2. text matches any text node.

    3. processing-instruction matches any processing instruction node.

    4. comment matches any comment node.

    5. document matches any document node.

    6. element matches an element node. Optionally, element may be followed by ElemOrAttrType,which places further constraints on the node (see below).

    7. attribute matches an attribute node. Optionally, attribute may be followed by ElemOrAttrType,which places further constraints on the node (see below).

An ElemOrAttrType may be used to place a constraint on the name or type of an element or attribute, as follows:

  1. One form of ElemOrAttrType, denoted by the phrase "of type", specifies the required type of the element or attribute node. The required type must be the QName of a simple or complex type that is found in the in-scope schema definitions. The match is successful only if the given element or attribute has a type annotation that is the same as the required type or is known (in the in-scope schema definitions) to be derived from the required type. For example, element of type Employee matches an element node that has been validated and has received the type annotation Employee. Similarly, attribute of type xs:integer matches an attribute node that has been validated and has received the type annotation xs:integer.

  2. Another form of ElemOrAttrType is simply a QName, which is interpreted as the required name of the element or attribute. The QName must be an element or attribute name that is found in the in-scope schema definitions. The match is successful only if the given element or attribute has the required name and also conforms to the schema definition for the required name. This can be verified in either of the following ways:

    1. If the schema definition for the required name has a named type, the given element or attribute must have a type annotation that is the same as that named type or is known (in the in-scope schema definitions) to be derived from that named type. For example, suppose that a schema declares the element named location to have the type State. Then the SequenceType element location will match a given element only if its name is location and its type annotation is State or some named type that is derived from State.

    2. If the schema definition for the required name has an anonymous (unnamed) type definition, the actual content of the given element or attribute must structurally comply with this type definition. For example, suppose that a schema declares the element named shippingAddress to have an anonymous complex type consisting of a street element followed by a city element. Then the SequenceType element shippingAddress will match a given element only if its name is shippingAddress and its content is a street element followed by a city element.

  3. The above two forms of ElemOrAttrType may be combined to specify both the required name and the required type of an element or attribute node, as in element person of type Employee or attribute color of type xs:integer.

In some cases, the required name of an element or attribute node may be locally declared (that is, declared inside a complex type in some schema.) In this case, the ElemOrAttrType may specify the SchemaContext in which the required name is to be interpreted. For example, element shippingAddress in invoice/customer matches an element node that conforms to the schema definition of the element name shippingAddress, as it would be interpreted inside a customer element that is inside an invoice element. The first QName in the SchemaContext must be found in the in-scope schema definitions.

[Ed. Note: The effect of substitution groups on SequenceType matching is an open issue.]

2.1.3.3 Type Conversions

Some expressions do not require their operands to exactly match the expected type. For example, function parameters and returns expect a value of a particular type, but allow some basic conversions to be performed, such as extraction of atomic values from nodes, promotion of numeric values, and implicit casting of untyped values. The conversion rules for function parameters and returns are discussed in 2.2.4 Function Calls. Other operators that provide special conversion rules include arithmetic operators, which are discussed in 2.5 Arithmetic Expressions, and value comparisons, which are discussed in 2.6.1 Value Comparisons.

Type conversions sometimes depend on a process called atomization, which is used when an optional atomic value is expected. When atomization is applied to a given value, the result is either a single atomic value, an empty sequence, or a type exception. Atomization is defined as follows:

  • If the value is a single atomic value or an empty sequence, atomization simply returns the value.

  • If the value is a single node, the typed value of the node is extracted and returned; however, if the typed value is a sequence containing more than one item, a type exception is raised.

  • In any other case, atomization raises a type exception.

2.1.3.4 Fallbacks

The action taken when a type exception is raised depends on the language environment in which the XPath expression is being evaluated. A language environment may choose either a strict or a flexible type exception policy. If the policy is strict, a type exception is treated as an error. If the policy is flexible, the language environment must handle type exceptions by applying a fixed set of rules called fallback conversions. The purpose of fallback conversions is to provide backward compatibility with the behavior of XPath Version 1.0.

This means that some language environments may be more permissive than others about type conversions. In general, XPath expressions will be portable from one language environment to another only if they make no reliance on fallback conversions. However, if an expression evaluates without raising an error in two different language environments, it will always return the same result.

A type exception is raised when a given value does not conform to its required type. A language environment that implements fallback conversions must resolve this conflict by applying the following rules, in order:

  1. If the required type is anything other than an atomic type or a single node, the error value is returned.

  2. If the required type is boolean, and the given value is an empty sequence, the given value is converted to boolean false.

  3. 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.

  4. 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, the error value is returned.

  5. Otherwise if the given value is a sequence containing more than one item, only the first item is retained. If this item is a node, its typed value is extracted. If the typed value of the node is a sequence of more than one atomic value, only the first of these atomic values is retained. The resulting (supplied or extracted) atomic value is converted to the required type according to the rules in the following table:

    boolean typestring typenumber typeother atomic type
    boolean valueN/ABoolean 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.Return the error value
    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/AUse 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 value0, +0, -0, and NaN, is converted to boolean false, anything else is converted to boolean true.Use the string value of the atomic value, as defined in the data model.N/AAttempt to cast the value to the given atomic type, using the tables defined in [XQuery 1.0 and XPath 2.0 Functions and Operators]. If a cast cannot be done, return the error value; otherwise a warning should be given.
    other atomic valueAttempt 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, return the error value. 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, return the error value. 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, return the error value. If precision is lost, a warning should be given.Attempt to cast the value to the given atomic type, using the tables defined in [XQuery 1.0 and XPath 2.0 Functions and Operators]. If a cast cannot be done, return the error value; 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.

2.2 Primary Expressions

Primary expressions are the basic primitives of the language. They include literals, variables, function calls, and the use of parentheses to control precedence of operators. The use of qualifiers in primary expressions is discussed in 2.3.2 Qualifiers.

[23]   PrimaryExpr   ::=   (Literal |  FunctionCall |  Variable |  ParenthesizedExpr) Qualifiers

2.2.1 Literals

A literal is a direct syntactic representation of an atomic value. XPath supports two kinds of literals: string literals and numeric literals.

[42]   Literal   ::=   NumericLiteral |  StringLiteral
[41]   NumericLiteral   ::=   IntegerLiteral |  DecimalLiteral |  DoubleLiteral
[141]   IntegerLiteral   ::=   [0-9]+
[142]   DecimalLiteral   ::=   ("." [0-9]+) |  ([0-9]+ "." [0-9]*)
[143]   DoubleLiteral   ::=   (("." [0-9]+) |  ([0-9]+ ("." [0-9]*)?)) ([e] | [E]) ([+] | [-])? [0-9]+
[155]   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 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 an item whose primitive value is the decimal value 12.0 and whose type is the built-in derived type xs:positiveInteger.

2.2.2 Variables

A variable evaluates to the value to which the variable's QName is bound in the evaluation context. If the variable's QName is not bound, the value of the variable is the error value. 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 before executing the function body.

XPath also allows variables to be bound in the host language environment.

[132]   Variable   ::=   "$" QName

2.2.3 Parenthesized Expressions

Parentheses may be used to enforce a particular evaluation order in expressions that contain multiple operators. For example, the expression (2 + 4) * 5 evaluates to thirty, since the parenthesized expression (2 + 4) is evaluated first and its result is multiplied by five. Without parentheses, the expression 2 + 4 * 5 evaluates to twenty-two, because the multiplication operator has higher precedence than the addition operator.

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

2.2.4 Function Calls

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

[44]   FunctionCall   ::=   QName "(" (Expr ("," Expr)*)? ")"

A function call expression is evaluated as follows:

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

  2. Each argument value is converted to the declared type of the corresponding function parameter, using the function conversion rules listed below.

  3. The function is executed using the converted argument values. The result is a value of the function's declared return type.

The function conversion rules are used to convert an argument value to its required type; that is, to the declared type of the function parameter. The required type is expressed as a SequenceType. The function conversion rules are as follows:

  1. If the required type is an AtomicType:

    Atomization is applied to the given value. If the resulting atomic value is of type xs:anySimpleType, an attempt is made to cast it to the required type; if the cast fails, the function call returns the error value. If the atomic value has a type that can be promoted to the required type using the promotion rules in B.1 Type Promotion, the promotion is done. After applying the above rules, if the resulting value does not conform to the required type, the function call returns the error value.

  2. If the required type is a sequence or optional occurrence of AtomicType:

    If the given value contains any nodes, these nodes are replaced by their typed values. If the cardinality of the resulting sequence does not match the cardinality of the required type, a type exception is raised. Otherwise, each item is converted to the required AtomicType using the conversion rule for AtomicType.

  3. If the required type is any other SequenceType:

    SequenceType Matching is used to determine if the type of the given value matches the required type. If not, the function call returns the error value.

A core library of functions is defined in [XQuery 1.0 and XPath 2.0 Functions and Operators]. Functions in this library may be invoked without a namespace prefix by assigning the default function namespace to the namespace of the function library.

The comma operator in XPath serves two purposes: it separates the arguments in a function call, and it separates items in an expression that constructs a sequence (see 2.4.1 Constructing Sequences). To distinguish these two uses, parentheses can be used to delimit the individual arguments of a function call. Here are some examples of function calls in which arguments that are literal sequences are delimited with parentheses:

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

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

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

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

2.2.5 Comments

XPath comments can be used to provide informative annotation. These comments are lexical constructs only, and do not affect the processing of an expression.

[56]   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 "}".

2.3 Path Expressions

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

[22]   RelativePathExpr   ::=   Expr  ("/" |  "//")  Expr
[21]   RootedPathExpr   ::=   ("/" Expr?) |  ("//" Expr)

A relative path expression consists of two expressions, separated by / or //. This section describes the meaning of /; the use of // is described in 2.3.4 Abbreviated Syntax.

We will refer to the expression on the left side of / as E1 and the expression on the right side of / as E2. The expression E1 is evaluated, and if the result is not a sequence of nodes, the error value is returned. Each node resulting from the evaluation of E1 then serves in turn to provide an inner focus for an evaluation of E2, as described in 2.1.1.2 Evaluation Context. Each evaluation of E2 must result in a sequence of nodes; otherwise, the error value is returned. The sequences of nodes resulting from all the evaluations of E2 are merged, eliminating duplicate node identities and sorting the results in document order.

As an example of a relative path expression, child::div1/child::para selects the para element children of the div1 element children of the context node, or, in other words, the para element grandchildren of the context node that have div1 parents.

A rooted path expression consists of / or //, followed by an expression. If the rooted path expression begins with /, the following expression is optional. This section describes the meaning of /; the use of // is described in 2.3.4 Abbreviated Syntax.

A / by itself selects the context document. A / followed by an expression E1 establishes an inner focus in which the context node is set equal to the context document, and the context position and context length are set to 1. The expression E1 is then evaluated. If the value of E1 is a sequence of nodes, the result of the rooted path expression is this sequence of nodes, in document order, after elimination of duplicates based on nodeid. If the value of E1 is not a sequence of nodes, the error value is returned.

2.3.1 Steps

[24]   StepExpr   ::=   (ForwardStep |  ReverseStep) Qualifiers
[36]   ForwardStep   ::=   (ForwardAxis NodeTest) |  AbbreviatedForwardStep
[37]   ReverseStep   ::=   (ReverseAxis NodeTest) |  AbbreviatedReverseStep

A step is an expression that returns a sequence of nodes, in document order and without duplicates. Steps are often used inside path expressions. A step might be thought of as beginning at the context node, navigating to those nodes that are reachable from the context node via a predefined axis, and selecting some subset of the reachable nodes. A step has three parts:

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

  • a node test, which specifies the node kind and/or name of the nodes selected by the step.

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

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

The unabbreviated syntax for an step consists of the axis name and node test separated by a double colon, followed by zero or more 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 qualifier.

The node sequence selected by a step is found by generating an initial node sequence from the axis and node test, and then applying each of the qualifiers in turn. The initial node sequence consists of the nodes reachable from the context node via the specified axis that have the node kind and/or name specified by the node test. For example, the step 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 node, 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. Qualifiers are described in 2.3.2 Qualifiers. Examples of steps are provided in 2.3.3 Unabbreviated Syntax and 2.3.4 Abbreviated Syntax.

2.3.1.1 Axes
[26]   ForwardAxis   ::=   "child" "::"
|  "descendant" "::"
|  "attribute" "::"
|  "self" "::"
|  "descendant-or-self" "::"
|  "following-sibling" "::"
|  "following" "::"
|  "namespace" "::"
[27]   ReverseAxis   ::=   "parent" "::"
|  "ancestor" "::"
|  "preceding-sibling" "::"
|  "preceding" "::"
|  "ancestor-or-self" "::"

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.

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

2.3.1.2 Node Tests

A node test is a condition that must be true for each node selected by a step. The condition may be based on the kind of the node (element, attribute, text, document, comment, processing instruction, or namespace) or on the name of the node.

[28]   NodeTest   ::=   KindTest |  NameTest
[29]   NameTest   ::=   QName |  Wildcard
[30]   Wildcard   ::=   "*" |  ":"? NCName ":" "*" |  "*" ":" NCName
[31]   KindTest   ::=   ProcessingInstructionTest
|  CommentTest
|  TextTest
|  AnyKindTest
[32]   ProcessingInstructionTest   ::=   "processing-instruction" "(" StringLiteral? ")"
[33]   CommentTest   ::=   "comment" "(" ")"
[34]   TextTest   ::=   "text" "(" ")"
[35]   AnyKindTest   ::=   "node" "(" ")"

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

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

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

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

A node test that is a QName is true if and only if the kind of the node is the principal node kind and the expanded-name of the node is equal to the expanded-name specified by the QName. For example, child::para selects the para element children of the context node; if the context node has no para children, it selects an empty set of nodes. attribute::href selects the href attribute of the context node; if the context node has no href attribute, it selects an empty set of nodes.

A QName in a node test is expanded into an expanded-name using the in-scope namespaces in the expression context. An unprefixed QName used as a nametest has the namespaceURI associated with the default element namespace in the expression context. It is 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 kind. For example, child::* will select all element children of the context node, and attribute::* will select all attributes of the context node.

A node test can have the form NCName:*. In this case, the prefix is expanded in the same way as with a QName, using the context namespace declarations. It is 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 node kind whose expanded-name has the namespace URI to which the prefix expands, regardless of the local part of the name.

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

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

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

2.3.2 Qualifiers

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 nodes into the nodes that they reference.

[40]   Qualifiers   ::=   (("[" Expr "]") |  ("=>" NameTest))*
2.3.2.1 Predicates

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

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

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

  2. If the value of the predicate expression is an atomic value of a numeric type, the predicate truth value is true if and only if the value of the predicate expression is equal to the context position.

  3. If the value of the predicate expression is an atomic value of type Boolean, the predicate truth value is equal to the value of the predicate expression.

  4. If the value of the predicate expression is a sequence that contains at least one node and does not contain any item that is not a node, the predicate truth value is true. The predicate truth value in this case does not depend on the content of the node(s). [Ed. Note: This rule is pending approval by the XSLT Working Group.]

  5. In any other case, a type exception is raised.

Here are some examples of steps that contain predicates:

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

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

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

    child::employee[secretary]

As noted in 2.2 Primary Expressions, a predicate can also be used with a primary expression that is not a step, as illustrated in the following example:

  • List all the integers from 1 to 100 that are divisible by 5.

    (1 to 100)[. mod 5 eq 0]
2.3.2.2 Dereferences

A dereference operates on a node sequence, mapping element and/or attribute nodes into the nodes that they reference. Every node in the input sequence of the dereference must be an element or attribute node whose typed value is of type IDREF or IDREFS; otherwise the error value is returned. The dereference generates a new sequence consisting of the element nodes that are referenced by the IDREF values in the input sequence. An element node is referenced by an IDREF value if it has an ID-type attribute whose value matches the IDREF value, and it is in the same document as the node containing the IDREF value. The referenced nodes are 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 and duplicate node-ids are eliminated.

Here are some examples of steps that contain dereferences:

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

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

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

2.3.3 Unabbreviated Syntax

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

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

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

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

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

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

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

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

  • ancestor::div selects all div ancestors of the context node

  • ancestor-or-self::div selects the div ancestors of the context node and, if the context node is a div element, the context node as well

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

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

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

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

  • / selects the context document (the document node that is an ancestor of the context node)

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

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

  • child::para[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

2.3.4 Abbreviated Syntax

[38]   AbbreviatedForwardStep   ::=   "." |  ("@" NameTest) |  NodeTest
[39]   AbbreviatedReverseStep   ::=   ".."

The abbreviated syntax permits the following abbreviations:

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

  2. There is also an abbreviation for attributes: attribute:: can be abbreviated by @. For example, a path expression para[@type="warning"] is short for child::para[attribute::type="warning"] and so selects para children with a type attribute with value equal to warning.

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

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

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

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

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

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

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

  • para selects the para element children of the context node

  • * selects all element children of the context node

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

  • @name selects the name attribute of the context node

  • @* selects all the attributes of the context node

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

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

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

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

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

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

  • //list/member selects all the member elements in the same document as the context node that have an list parent

  • . selects the context node

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

  • .. selects the parent of the context node

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

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

  • para[@type="warning"][5] selects the fifth para child of the context node that has a typeattribute with value warning

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

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

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

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

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

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

2.4 Sequence Expressions

XPath supports operators to construct and combine sequences. A sequence is an ordered collection of zero or more items. An item may be an atomic value or a node. An item is identical to a sequence of length one containing that item. Sequences are never nested--for example, combining the values 1, (2, 3), and ( ) into a single sequence results in the sequence (1, 2, 3).

2.4.1 Constructing Sequences

[43]   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)

2.4.2 Combining Sequences

[16]   UnionExpr   ::=   Expr  ("union" |  "|")  Expr
[17]   IntersectExceptExpr   ::=   Expr  ("intersect" |  "except")  Expr

XPath provides several operators for combining sequences of nodes. The union and | operators are equivalent. They take two node sequences as operands and return a sequence containing all the nodes that occur in either of the operands. The intersect operator takes two node sequences as operands and returns a sequence containing all the nodes that occur in both operands. The except operator takes two node sequences as operands and returns a sequence containing all the nodes that occur in the first operand but not in the second operand. All of these operators return their result sequences in document order without duplicates based based on nodeid. If an operand of union, intersect, or except contains an item that is not a node, the error value is returned.

Here are some examples of expressions that combine sequences. Assume the existence of three element nodes that we will refer to by symbolic names A, B, and C. Assume that $seq1 is bound to a sequence containing A and B, $seq2 is also bound to a sequence containing A and B, and $seq3 is bound to a sequence containing B and C. Then:

  • $seq1 union $seq1 evaluates to a sequence containing A and B.

  • $seq2 union $seq3 evaluates to a sequence containing A, B, and C.

  • $seq1 intersect $seq1 evaluates to a sequence containing A and B.

  • $seq2 intersect $seq3 evaluates to a sequence containing B only.

  • $seq1 except $seq2 evaluates to the empty sequence.

  • $seq2 except $seq3 evaluates to a sequence containing A only.

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

2.5 Arithmetic Expressions

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.

An arithmetic expression is evaluated by applying the following rules, in order, until an error is encountered or a value is computed:

  1. Atomization is applied to each operand, resulting in a single atomic value or an empty sequence for each operand.

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

  3. If an operand has the type xs:anySimpleType, it is cast to xs:double. If the cast fails, the error value is returned.

  4. If the two operands have different types, and these types can be promoted to a common type using the promotion rules in B.1 Type Promotion, the operands are both promoted to their least common type. For example, if the first operand is of type hatsize which is derived from xs:decimal, and the second operand is of type shoesize which is derived from xs:integer, then both operands are promoted to the type xs:decimal.

  5. If the operand type(s) are valid for the given operator, the operator is applied to the operand(s), resulting in an atomic value or an error (for example, an error might result from dividing by zero.) The combinations of atomic types that are accepted by the various arithmetic operators, and their respective result types, are listed in B.2 Operator Mapping. If the operand type(s) are not valid for the given operator, a type exception is raised.

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 date values results in a value of type xs:dayTimeDuration:

    $emp/hiredate - $emp/birthdate
  • This example illustrates the difference between a subtraction operator and a hyphen:

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

    -($bellcost + $whistlecost)

2.6 Comparison Expressions

Comparison expressions allow two values to be compared. XPath provides four kinds of comparison expressions, c