View Old View New View Both View Only Previous Next

This draft contains only sections that have differences from the version that it modified.

W3C

XML Path Language (XPath) 4.0 WG Review Draft

W3C Editor's Draft 23 February 2026

This version:
https://qt4cg.org/specifications/xpath-40/
Most recent version of XPath:
https://qt4cg.org/specifications/xpath-40/
Most recent Recommendation of XPath:
https://www.w3.org/TR/2017/REC-xpath-31-20170321/
Editor:
Michael Kay, Saxonica <mike@saxonica.com>

Please check the errata for any errors or issues reported since publication.

See also translations.

This document is also available in these non-normative formats: XML.


Abstract

XPath 4.0 is an expression language that allows the processing of values conforming to the data model defined in [XQuery and XPath Data Model (XDM) 4.0][XDM 4.0]. The name of the language derives from its most distinctive feature, the path expression, which provides a means of hierarchic addressing of the nodes in an XML tree. As well as modeling the tree structure of XML, the data model also includes atomic items, function items, maps, arrays, and sequences. This version of XPath supports JSON as well as XML, and adds many new functions in [XQuery and XPath Functions and Operators 4.0].

XPath 4.0 is a superset of XPath 3.1. A detailed list of changes made since XPath 3.1 can be found in I Change Log.

Status of this Document

This is a draft prepared by the QT4CG (officially registered in W3C as the XSLT Extensions Community Group). Comments are invited.

Dedication

The publications of this community group are dedicated to our co-chair, Michael Sperberg-McQueen (1954–2024).

Michael was central to the development of XML and many related technologies. He brought a polymathic breadth of knowledge and experience to everything he did. This, combined with his indefatigable curiosity and appetite for learning, made him an invaluable contributor to our project, along with many others. We have lost a brilliant thinker, a patient teacher, and a loyal friend.


1 Introduction

Changes in 4.0 

  1. Use the arrows to browse significant changes since the 3.1 version of this specification.

  2. Sections with significant changes are marked Δ in the table of contents.

XPath was originally designed as an expression language to address the nodes of XML trees; it has since been extended to address a variety of non-XML data sources. XPath gets its name from its use of a path notation for navigating through the hierarchical structure of an XML document; similar capabilities for navigating JSON structures were added in versions 3.0 and 3.1. XPath uses a compact, non-XML syntax, allowing XPath expressions to be embedded within URIs and to be used as XML attribute values. XPath is designed to be embedded in (or invoked from) other host languages, including both languages specialized towards XML processing (such as [XSL Transformations (XSLT) Version 4.0][XSLT 4.0] and XSD), and general purpose programming languages such as Java, C#, Python, and Javascript. The interface between XPath and its host language is formalized with an abstract definition of a static and dynamic context, made available by the host language to the XPath processor.

[Definition: A host language for XPath is any environment that provides capabilities for XPath expressions to be defined and evaluated, and that supplies a static and dynamic context for their evaluation. ]

[Definition: XPath 4.0 operates on the abstract, logical structure of an XML document or JSON object rather than its surface syntax. This logical structure, known as the data model, is defined in [XQuery and XPath Data Model (XDM) 4.0][XDM 4.0].]

XPath 4.0 is a subset of XQuery 4.0. In general, any expression that is syntactically valid and executes successfully in both XPath 4.0 and XQuery 4.0 will return the same result in both languages. There are a few exceptions to this rule:

Because these languages are so closely related, their grammars and language descriptions are generated from a common source to ensure consistency.

XPath 4.0 also depends on and is closely related to the following specifications:

Note:

The XML-based syntax for XQuery known as XQueryX is no longer maintained.

This document specifies a grammar for XPath 4.0, using the same basic EBNF notation used in [XML 1.0]. Unless otherwise noted (see A.3 Lexical structure), whitespace is not significant in expressions. Grammar productions are introduced together with the features that they describe, and a complete grammar is also presented in the appendix [A XPath 4.0 Grammar]. The appendix is the normative version.

In the grammar productions in this document, named symbols are underlined and literal text is enclosed in double quotes. For example, the following productions describe the syntax of a static function call:

FunctionCall::=EQNameArgumentList
/* xgc: reserved-function-names */
/* gn: parens */
EQName::=QName | URIQualifiedName
ArgumentList::="(" ((PositionalArguments ("," KeywordArguments)?) | KeywordArguments)? ")"
PositionalArguments::=(Argument ++ ",")
Argument::=ExprSingle | ArgumentPlaceholder
ExprSingle::=ForExpr
| LetExpr
| QuantifiedExpr
| IfExpr
| OrExpr
ArgumentPlaceholder::="?"
KeywordArguments::=(KeywordArgument ++ ",")
KeywordArgument::=EQName ":=" Argument

The productions should be read as follows: A function call consists of an EQName followed by an ArgumentList. The argument list consists of an opening parenthesis, an optional list of one or more arguments (separated by commas), and a closing parenthesis.

This document normatively defines the static and dynamic semantics of XPath 4.0. In this document, examples and material labeled as “Note” are provided for explanatory purposes and are not normative.

2 Basics

2.1 Terminology

Changes in 4.0  

  1. The EBNF operators ++ and ** have been introduced, for more concise representation of sequences using a character such as "," as a separator. The notation is borrowed from Invisible XML.  [Issue 1366 PR 1498]

The basic building block of XPath 4.0 is the expression, which is a string of [Unicode] characters; the version of Unicode to be used is implementation-defined. 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 4.0 allows expressions to be nested with full generality.

Note:

This specification contains no assumptions or requirements regarding the character set encoding of strings of [Unicode] characters.

Like XML, XPath 4.0 is a case-sensitive language. Keywords in XPath 4.0 use lower-case characters and are not reserved—that is, names in XPath 4.0 expressions are allowed to be the same as language keywords, except for certain unprefixed function-names listed in A.4 Reserved Function Names.

In this specification the phrases must, must not, should, should not, may, required, and recommended, when used in normative text and rendered in small capitals, are to be interpreted as described in [RFC2119].

Certain aspects of language processing are described in this specification as implementation-defined or implementation-dependent.

  • [Definition: Implementation-defined indicates an aspect that may differ between implementations, but must be specified by the implementer for each particular implementation.]

  • [Definition: Implementation-dependent indicates an aspect that may differ between implementations, is not specified by this or any W3C specification, and is not required to be specified by the implementer for any particular implementation.]

A language aspect described in this specification as implementation-defined or implementation dependent may be further constrained by the specifications of a host language in which XPath is embedded.

2.1.3 Values

Changes in 4.0  

  1. The term atomic value has been replaced by atomic item.   [Issue 1337 PR 1361 2 August 2024]

  2. The terms XNode and JNode are introduced; the existing term node remains in use as a synonym for XNode where the context does not specify otherwise.   [Issue 2025 PR 2031 13 June 2025]

[Definition: In the data model, a value is always a sequence.]

[Definition: A sequence is an ordered collection of zero or more items.]

[Definition: An item is either an atomic item, a node, or a function item.]

[Definition: An atomic item is a value in the value space of an atomic type, as defined in [XML Schema 1.0] or [XML Schema 1.1].]

[Definition: An XNode is an instance of one of the node kinds defined in [XDM 4.0] section Section 7.1 XML NodesDM.] Each XNode has a unique node identity, a typed value, and a string value. In addition, some XNodes have a name. The typed value of an XNode is a sequence of zero or more atomic items. The string value of an XNode is a value of type xs:string. The name of an XNode is a value of type xs:QName.

[Definition: Except where the context indicates otherwise, the term node is used as a synonym for XNode.]

[Definition: A function item is an item that can be called using a dynamic function call.]

Maps (see 4.13.1 Maps) and arrays (see 4.13.2 Arrays) are specific kinds of function items.

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

[Definition: The term XDM instance is used, synonymously with the term value, to denote an unconstrained sequence of items.]

2.1.4 Namespaces and QNames

[Definition: A namespace binding is a pair comprising a namespace prefix (which is either an xs:NCName or empty), and a namespace URI.]

Element nodes have a property called in-scope namespaces. [Definition: The in-scope namespaces property of an element node is a set of namespace bindings, each of which associates a namespace prefix with a URI.] For a given element, one namespace binding may have an empty prefix; the URI of this namespace binding is referred to as the default in-scope namespace for the element.

In [XML Path Language (XPath) Version 1.0][XPath 1.0], the in-scope namespaces of an element node are represented by a collection of namespace nodes arranged on a namespace axis. As of XPath 2.0, the namespace axis is deprecated and need not be supported by a host language. A host language that does not support the namespace axis need not represent namespace bindings in the form of nodes.

[Definition: The default in-scope namespace of an element node] is the namespace URI to which the empty prefix is bound in the element’s in-scope namespaces. In the absence of an explicit binding for the empty prefix, the default in-scope namespace is absentDM.

[Definition: An expanded QName is a triple: its components are a prefix, a local name, and a namespace URI. In the case of a name in no namespace, the namespace URI and prefix are both absent. In the case of a name in the default namespace, the prefix is absent.] When comparing two expanded QNames, the prefixes are ignored: the local name parts must be equal under the Unicode codepoint collation ([Functions and Operators 4.0] section Section 5.3.1 CollationsFO), and the namespace URI parts must either both be absent, or must be equal under the Unicode codepoint collation.

Note:

The datumDM of an atomic item of type xs:QName is an expanded QName. However, the term expanded QName is also used for the names of constructs such as functions, variables, and types that are not themselves atomic items.

In the XPath 4.0 grammar, QNames representing the names of elements, attributes, functions, variables, types, or other such constructs are written as instances of the grammatical production EQName.

EQName::=QName | URIQualifiedName
URIQualifiedName::=BracedURILiteralNCName
/* ws: explicit */

The EQName production allows a QName to be written in one of three ways:

  • local-name only (for example, invoice).

    A name written in this form has no prefix, and the rules for determining the namespace depend on the context in which the name appears: the various rules used are summarized in 2.1.5 Expanding Lexical QNames. This form is a lexical QName.

  • prefix plus local-name (for example, my:invoice).

    In this case the prefix and local name of the QName are as written, and the namespace URI is inferred from the prefix by examining the statically known namespaces in the static context where the QName appears; the context must include a binding for the prefix. This form is a lexical QName.

  • URI plus local-name (for example, Q{http://example.com/ns}invoice).

    In this case the local name and namespace URI are as written, and the prefix is absent. This way of writing a QName is context-free, which makes it particularly suitable for use in expressions that are generated by software. This form is a URIQualifiedName. If the BracedURILiteral has no content (for example, Q{}invoice) then the namespace URI of the QName is absent.

[Definition: A lexical QName is a name that conforms to the syntax of the QName production].

The namespace URI value in a URIQualifiedName is whitespace normalized according to the rules for the xs:anyURI type in Section 3.2.17 anyURI XS1-2 or Section 3.3.17 anyURI XS11-2. It is a static error [err:XQST0070] if the namespace URI for an EQName is http://www.w3.org/2000/xmlns/.

Here are some examples of EQNames:

This document uses the following namespace prefixes to represent the namespace URIs with which they are listed. Although these prefixes are used within this specification to refer to the corresponding namespaces, not all of these bindings will necessarily be present in the static context of every expression, and authors are free to use different prefixes for these namespaces, or to bind these prefixes to different namespaces.

  • xs: http://www.w3.org/2001/XMLSchema

  • fn: http://www.w3.org/2005/xpath-functions

  • array: http://www.w3.org/2005/xpath-functions/array

  • map: http://www.w3.org/2005/xpath-functions/map

  • math: http://www.w3.org/2005/xpath-functions/math

  • err: http://www.w3.org/2005/xqt-errors (see 2.4.2 Identifying and Reporting Errors).

  • output: http://www.w3.org/2010/xslt-xquery-serialization

[Definition: Within this specification, the term URI refers to a Universal Resource Identifier as defined in [RFC3986] and extended in [RFC3987] with the new name IRI.] The term URI has been retained in preference to IRI to avoid introducing new names for concepts such as “Base URI” that are defined or referenced across the whole family of XML specifications.

Note:

In most contexts, processors are not required to raise errors if a URI is not lexically valid according to [RFC3986] and [RFC3987]. See 2.5.5 URI Literals for details.

2.2 Expression Context

[Definition: The expression context for a given expression consists of all the information that can affect the result of the expression.]

This information is organized into two categories called the static context and the dynamic context.

2.2.1 Static Context

Changes in 4.0  

  1. The default namespace for elements and types can be set to the value ##any, allowing unprefixed names in axis steps to match elements with a given local name in any namespace.   [Issue 296 PR 1181 30 April 2024]

  2. Parts of the static context that were there purely to assist in static typing, such as the statically known documents, were no longer referenced and have therefore been dropped.   [Issue 1343 PR 1344 23 September 2024]

  3. The context value static type, which was there purely to assist in static typing, has been dropped.   [Issue 1495 PR 1496 29 October 2024]

  4. Named record types used in the signatures of built-in functions are now available as standard in the static context.   [Issue 835 PR 1991 11 May 2025]

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

The individual components of the static context are described below.

In XPath 4.0, the static context for an expression is largely defined by the host language, that is, by the calling environment that causes an XPath expression to be evaluated. Most of the static context components are constant throughout an expression; the only exception is in-scope variables. (There are constructs in the language, such as the ForExpr and LetExpr, that add additional variables to the static context of their subexpressions.)

Some components of the static context, but not all, also affect the dynamic semantics of expressions. For example, casting of a string such as "xbrl:xbrl" to an xs:QName might expand the prefix xbrl to the namespace URI http://www.xbrl.org/2003/instance using the statically known namespaces from the static context; since the input string "xbrl:xbrl" is in general not known until execution time (it might be read from a source document), this means that the values of the statically known namespaces must be available at execution time.

  • [Definition: XPath 1.0 compatibility mode.This value is true if rules for backward compatibility with XPath Version 1.0 are in effect; otherwise it is false. ]

  • [Definition: Statically known namespaces. This is a mapping from prefix to namespace URI that defines all the namespaces that are known during static processing of a given expression.]

    The URI value is whitespace normalized according to the rules for the xs:anyURI type in Section 3.2.17 anyURI XS1-2 or Section 3.3.17 anyURI XS11-2.

    Note the difference between in-scope namespaces, which is a dynamic property of an element node, and statically known namespaces, which is a static property of an expression.

  • [Definition: Default namespace for elements and types. This is either a namespace URI, or the special value "##any", or absentDM. This indicates how unprefixed QNames are interpreted when they appear in a position where an element name or type name is expected.]

    • If the value is set to a namespace URI, this namespace is used for any such unprefixed QName. The URI value is whitespace-normalized according to the rules for the xs:anyURI type in Section 3.2.17 anyURI XS1-2 or Section 3.3.17 anyURI XS11-2.

    • The special value "##any" indicates that:

      • When an unprefixed QName is used as a name test for selecting named elements in an axis step, the name test will match an element having the specified local name, in any namespace or none.

      • When an unprefixed QName is used in a context where a type name is expected (but not as a function name), the default namespace is the xs namespace, http://www.w3.org/2001/XMLSchema.

      • In any other context, an unprefixed QName represents a name in no namespace.

    • If the value is absentDM, an unprefixed QName representing an element or type name is interpreted as being in no namespace.

  • [Definition: Default function namespace. This is either a namespace URI, or absentDM. The namespace URI, if present, is used for any unprefixed QName appearing in a position where a function name is expected.] The URI value is whitespace-normalized according to the rules for the xs:anyURI type in Section 3.2.17 anyURI XS1-2 or Section 3.3.17 anyURI XS11-2

    In its simplest form its value is simply a whitespace-normalized xs:anyURI value (most commonly, the URI http://www.w3.org/2005/xpath-functions) to be used as the default namespace for unprefixed function names. However, the use of a more complex algorithm is not precluded, for example an algorithm which searches multiple namespaces for a matching name.

  • [Definition: In-scope schema definitions is a generic term for all the element declarations, attribute declarations, and schema type definitions that are in scope during static analysis of an expression.] It includes the following three parts:

  • [Definition: In-scope variables. This is a mapping from expanded QNames to sequence types. It defines the set of variables that are available for reference within an expression. The expanded QName is the name of the variable, and the type is the static type of the variable.]

    An expression that binds a variable extends the in-scope variables, within the scope of the variable, with the variable and its type. Within the body of an inline function expression, the in-scope variables are extended by the names and types of the function parameters.

  • [Definition: In-scope named item types. This is a mapping from expanded QNames to named item types.]

    [Definition: A named item type is an ItemType identified by an expanded QName.]

    Named item types serve two purposes:

    • They allow frequently used item types, especially complex item types such as record types, to be given simple names, to avoid repeating the definition every time it is used.

    • They allow the definition of recursive types, which are useful for describing recursive data structures such as lists and trees. For details see 3.2.8.3.1 Recursive Record Types.

    Certain named item types (typically item types used in the signatures of built-in functions) are always available in the static context. These are defined in [Functions and Operators 4.0] section Section C Built-in named record typesFO.

    Note:

    Named item types can be defined in a host language such as XQuery 4.0 and in XSLT 4.0, but not in XPath 4.0 itself. They are available in XPath only if the host language provides the ability to define them.

  • [Definition: Statically known function definitions. This is a set of function definitions.]

    Function definitions are described in 2.2.1.1 Function Definitions.

  • [Definition: Statically known collations. This is an implementation-defined mapping from URI to collation. It defines the names of the collations that are available for use in processing expressions.] [Definition: A collation is a specification of the manner in which strings and URIs are compared and, by extension, ordered. For a more complete definition of collation, see [Functions and Operators 4.0] section Section 5.3 Comparison of stringsFO.]

  • [Definition: Static Base URI. This is an absolute URI, used to resolve relative URIs during static analysis. ] For example, it is used to resolve module location URIs in XQuery, and the URIs in xsl:import and xsl:include in XSLT. If E is a subexpression of F then the Static Base URI of E is the same as the Static Base URI of F. There are no constructs in XPath that require resolution of relative URI references during static analysis.

    Relative URI references are resolved as described in 2.5.6 Resolving a Relative URI Reference.

    At execution time, relative URIs supplied to functions such as fn:doc are resolved against the Executable Base URI, which may or may not be the same as the Static Base URI.

  • [Definition: Statically known decimal formats. This is a mapping from QNames to decimal formats, with one default format that has no visible name, referred to as the unnamed decimal format. Each format is available for use when formatting numbers using the fn:format-number function.]

    Decimal formats are described in 2.2.1.2 Decimal Formats.

2.2.1.1 Function Definitions

[Definition: A function definition contains information used to evaluate a static function call, including the name, parameters, and return type of the function.]

The properties of a function definition include:

  • The function name, which is an expanded QName.

  • Parameter definitions, specifically:

    The names of the parameters must be distinct.

    [Definition: A function definition has an arity range, which is a range of consecutive non-negative integers. If the function definition has M required parameters and N optional parameters, then its arity range is from M to M+N inclusive.]

    The static context may contain several function definitions with the same name, but the arity ranges of two such function definitions must not overlap. For example, if two function definitions A and B have the same function name, then:

    • It is acceptable for A to have two required parameters and no optional parameters, while B has three required parameters and one optional parameter.

    • It is not acceptable for A to have one required parameter while B has three optional parameters.

    Note:

    Implementations must ensure that no two function definitions have the same expanded QName and overlapping arity ranges (even if the signatures are consistent).

    XQuery and XSLT enforce this rule by defining a static error if the rule is violated; but further constraints may be needed if an API allows external functions to be added to the static context.

  • A return type (a sequence type)

  • The function category, which is one of application, system, or external:

    • [Definition: Application functions are function definitions written in a host language such as XQuery or XSLT whose syntax and semantics are defined in this family of specifications. Their behavior (including the rules determining the static and dynamic context) follows the rules for such functions in the relevant host language specification.] The most common application functions are functions written by users in XQuery or XSLT.

    • [Definition: System functions include the functions defined in [XQuery and XPath Functions and Operators 4.0], functions defined by the specifications of a host language, constructor functions for atomic types, and any additional functions provided by the implementation. System functions are sometimes called built-in functions.]

      The behavior of system functions follows the rules given for the individual function in this family of specifications, or in the specification of the particular processor implementation. A system function may have behavior that depends on the static or dynamic context of the caller (for example, comparing strings using the default collation from the dynamic context of the caller). Such functions are said to be context dependent.

    • [Definition: External functions can be characterized as functions that are neither part of the processor implementation, nor written in a language whose semantics are under the control of this family of specifications. The semantics of external functions, including any context dependencies, are entirely implementation-defined. In XSLT, external functions are called Section 24.1 Extension Functions XT30. ]

      For example, an implementation might provide a mechanism allowing external functions to be written in a language such as Java or Python. The way in which argument and return values are converted between the XDM type system and the type system of the external language is implementation-defined.

    [Definition: A function definition is said to be context dependent if its result depends on the static or dynamic context of its caller. A function definition may be context-dependent for some arities in its arity range, and context-independent for others: for example fn:name#0 is context-dependent while fn:name#1 is context-independent.]

    Note:

    Some system functions, such as fn:position, fn:last, and fn:static-base-uri, exist for the sole purpose of providing information about the static or dynamic context of their caller.

    Note:

    Application functions are context dependent only to the extent that they define optional parameters with default values that are context dependent.

  • A (possibly empty) set of function annotations

  • A body. The function body contains the logic that enables the function result to be computed from the supplied arguments and information in the static and dynamic context.

The function definitions present in the static context are available for reference from a static function call, or from a named function reference.

2.2.2 Dynamic Context

Changes in 4.0  

  1. The concept of the context item has been generalized, so it is now a context value. That is, it is no longer constrained to be a single item.   [Issue 129 PR 368 14 September 2023]

  2. The rules regarding the document-uri property of nodes returned by the fn:collection function have been relaxed.   [Issue 1161 PR 1265 11 June 2024]

[Definition: The dynamic context of an expression is defined as information that is needed for the dynamic evaluation of an expression, beyond any information that is needed from the static context.] If evaluation of an expression relies on some part of the dynamic context that is absentDM, a type error is raised [err:XPDY0002].

Note:

In previous versions of the specification, this was classified as a dynamic error. The change allows the error to be raised during static analysis when possible; for example a function written as fn($x) { @code } can now be reported as an error whether or not the function is actually evaluated. The actual error code remains unchanged for backwards compatibility reasons.

There are other cases where static detection of the error is not possible.

The individual components of the dynamic context are described below.

In general, the dynamic context for the outermost expression is supplied externally, often by some kind of application programming interface (API) allowing XPath 4.0 expressions to be invoked from a host language. Application Programming Interfaces are outside the scope of this specification. The dynamic context for inner subexpressions may be set by their containing expressions: for example in a mapping expression E1!E2, the value of the focus (part of the dynamic context) for evaluation of E2 is defined by the evaluation of E1.

Some aspects of the dynamic context are outside the direct control of the query author; they are defined by the implementation, which may or may not allow them to be configured by users. An example is available documents, which is an abstraction for the set of XML documents that can be retrieved by URI from within an expression. In some environments this may be the entire contents of the web; in others it may be constrained to documents that satisfy particular security constraints; and in some environments the set of available documents might even be empty. These components of the dynamic context are generally treated as being constant for the duration of the execution.

Further rules governing the semantics of these components can be found in B.2 Dynamic Context Components.

The components of the dynamic context are listed below.

[Definition: The first three components of the dynamic context (context value, context position, and context size) are called the focus of the expression. ] The focus enables the processor to keep track of which items are being processed by the expression. If any component in the focus is defined, both the context value and context position are known.

Note:

If any component in the focus is defined, context size is usually defined as well. However, when streaming, the context size cannot be determined without lookahead, so it may be undefined. If so, expressions like last() will raise a dynamic error because the context size is undefined.

[Definition: A fixed focus is a focus for an expression that is evaluated once, rather than being applied to a series of values; in a fixed focus, the context value is set to one specific value, the context position is 1, and the context size is 1.]

[Definition: A singleton focus is a fixed focus in which the context value is a singleton item.]. With a singleton focus, the context value is a single item, the context position is 1, and the context size is 1.

Certain language constructs, notably the path operatorE1/E2, the simple map operatorE1!E2, and the predicateE1[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 is used only for the evaluation of E2. Evaluation of E1 continues with its original focus unchanged.

  • [Definition: The context value is the value currently being processed.] In many cases (but not always), the context value will be a single item. [Definition: When the context value is a single item, it can also be referred to as the context item; when it is a single node, it can also be referred to as the context node.] The context value is returned by an expression consisting of a single dot (.). When an expression E1/E2 or E1[E2] is evaluated, each item in the sequence obtained by evaluating E1 becomes the context value in the inner focus for an evaluation of E2.

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

  • [Definition: The context size is the number of values in the series of values currently being processed.] Its value is always an integer greater than zero. The context size is returned by the expression fn:last(). When an expression E1/E2 or E1[E2] is evaluated, the context size in the inner focus for an evaluation of E2 is the number of items in the sequence obtained by evaluating E1.

  • [Definition: Variable values. This is a mapping from expanded QNames to values. It contains the same expanded QNames as the in-scope variables in the static context for the expression. The expanded QName is the name of the variable and the value is the dynamic value of the variable, which includes its dynamic type.]

  • [Definition: Dynamically known function definitions. This is a set of function definitions. It includes the statically known function definitions as a subset, but may include other function definitions that are not known statically. ]

    The function definitions in the dynamic context are used primarily by the fn:function-lookup function.

    If two function definitions in the dynamically known function definitions have the same name, then their arity ranges must not overlap.

    Note:

    The reason for allowing named functions to be available dynamically beyond those that are available statically is primarily to allow for cases where the run-time execution environment is significantly different from the compile-time environment. This could happen, for example, if a stylesheet or query is compiled within a web server and then executed in the web browser. The fn:function-lookup function allows dynamic discovery of resources that were not available statically.

  • [Definition: Current dateTime. This information represents an implementation-dependent point in time during the processing of an expression, and includes an explicit timezone. It can be retrieved by the fn:current-dateTime function. If called multiple times during the execution of an expression, this function always returns the same result.]

  • [Definition: Implicit timezone. This is the timezone to be used when a date, time, or dateTime value that does not have a timezone is used in a comparison or arithmetic operation. The implicit timezone is an implementation-defined value of type xs:dayTimeDuration. See Section 3.2.7.3 Timezones XS1-2 or Section 3.3.7 dateTime XS11-2 for the range of valid values of a timezone.]

  • [Definition: Executable Base URI. This is an absolute URI used to resolve relative URIs during the evaluation of expressions; it is used, for example, to resolve a relative URI supplied to the fn:doc or fn:unparsed-text functions. ]

    URIs are resolved as described in 2.5.6 Resolving a Relative URI Reference.

    The function fn:static-base-uri, despite its name, returns the value of the Executable Base URI.

    In many straightforward processing scenarios, the Executable Base URI in the dynamic context will be the same as the Static Base URI for the corresponding expression in the static context. There are situations, however, where they may differ:

    • Some processors may allow the static analysis of a query or stylesheet to take place on a development machine, while execution of the query or stylesheet happens on a test or production server. In this situation, resources needed during static analysis (such as other modules of the query or stylesheet) will be located on the development machine, by reference to the Static Base URI, while resources needed during execution (such as reference data files) will be located on the production machine, accessed via the Executable Base URI.

    • When the fn:static-base-uri function is called within the initializing expression of an optional parameter in a function declaration, it returns the executable base URI of the relevant function call. This allows a user-written function to accept two parameters: a required parameter containing a relative URI, and an optional parameter containing a base URI. The optional parameter can be given a default value of fn:static-base-uri(), allowing the code in the function body to resolve the relative URI against the executable base URI of the caller.

  • [Definition: Default collation. This identifies one of the collations in statically known collations as the collation to be used by functions and operators for comparing and ordering values of type xs:string and xs:anyURI (and types derived from them) when no explicit collation is specified.]

    Note:

    Although the default collation is defined (in 4.0) as a property of the dynamic context, its value will in nearly all cases be known statically. The reason it is defined in the dynamic context is to allow a call on the fn:default-collation function to be used when defining the default value of an optional parameter to a user-defined function. In this situation, the actual value supplied for the parameter is taken from the dynamic context of the relevant function call.

  • [Definition: Default language. This is the natural language used when creating human-readable output (for example, by the functions fn:format-date and fn:format-integer) if no other language is requested. The value is a language code as defined by the type xs:language.]

  • [Definition: Default calendar. This is the calendar used when formatting dates in human-readable output (for example, by the functions fn:format-date and fn:format-dateTime) if no other calendar is requested. The value is a string.]

  • [Definition: Default place. This is a geographical location used to identify the place where events happened (or will happen) when processing dates and times using functions such as fn:format-date, fn:format-dateTime, and fn:civil-timezone, if no other place is specified. It is used when translating timezone offsets to civil timezone names, and when using calendars where the translation from ISO dates/times to a local representation is dependent on geographical location. Possible representations of this information are an ISO country code or an Olson timezone name, but implementations are free to use other representations from which the above information can be derived. The only requirement is that it should uniquely identify a civil timezone, which means that country codes for countries with multiple timezones, such as the United States, are inadequate.]

  • [Definition: Available documents. This is a mapping of strings to document nodes. Each string represents the absolute URI of a resource. The document node is the root of a tree that represents that resource using the data model. The document node is returned by the fn:doc function when applied to that URI.] The set of available documents may be empty.

  • [Definition: Available text resources. This is a mapping of strings to text resources. Each string represents the absolute URI of a resource. The resource is returned by the fn:unparsed-text function when applied to that URI.] The set of available text resources may be empty.

  • [Definition: Available binary resources. This is a mapping of strings to binary resources. Each string represents the absolute URI of a resource. The resource is returned by the fn:unparsed-binary function when applied to that URI.] The set of available binary resources may be empty.

  • [Definition: Available collections. This is a mapping of strings to sequences of items. Each string represents the absolute URI of a resource. The sequence of items represents the result of the fn:collection function when that URI is supplied as the argument. ] The set of available collections may be empty.

    Ideally, for every document node D that is in the target of a mapping in available item collections, or that is the root of a tree containing such a node, the document-uri property of D should either be absent, or should be a URI U such that available documents contains a mapping from U to D.

    Note:

    That is to say, the document-uri property of nodes returned by the fn:collection function should be such that calling fn:doc with that URI returns the relevant node.

    It is not always possible to ensure this, especially in cases where dereferencing of document or collection URIs is configurable using configuration files or user-supplied resolver code.

  • [Definition: Default collection. This is the sequence of items that would result from calling the fn:collection function with no arguments.] The value of default collection may be initialized by the implementation.

  • [Definition: Available URI collections. This is a mapping of strings to sequences of URIs. The string represents the absolute URI of a resource which can be interpreted as an aggregation of a number of individual resources each of which has its own URI. The sequence of URIs represents the result of the fn:uri-collection function when that URI is supplied as the argument. ] There is no implication that the URIs in this sequence can be successfully dereferenced, or that the resources they refer to have any particular media type.

    Note:

    An implementation may maintain some consistent relationship between the available collections and the available URI collections, for example by ensuring that the result of fn:uri-collection(X)!fn:doc(.) is the same as the result of fn:collection(X). However, this is not required. The fn:uri-collection function is more general than fn:collection in that fn:collection allows access to nodes that might lack individual URIs, for example nodes corresponding to XML fragments stored in the rows of a relational database.

  • [Definition: Default URI collection. This is the sequence of URIs that would result from calling the fn:uri-collection function with no arguments.] The value of default URI collection may be initialized by the implementation.

  • [Definition: Environment variables. This is a mapping from names to values. Both the names and the values are strings. The names are compared using an implementation-defined collation, and are unique under this collation. The set of environment variables is implementation-defined and may be empty.]

    Note:

    A possible implementation is to provide the set of POSIX environment variables (or their equivalent on other operating systems) appropriate to the process in which the expression is evaluated.

2.3 Processing Model

Changes in 4.0  

  1. The static typing option has been dropped.   [Issue 1343 PR 1344 3 September 2024]

The semantics of XPath 4.0 are defined in terms of the data model and the expression context.

Processing_ModelclusterQT4XPath Expression ProcessingclusterEPExternal processingExecExecutionEngineXDMXPath DataModelExec->XDM DQ4SerializeSerializeXDM->Serialize DM4ASTAbstractSyntax TreeAST->Exec DQ1AST->AST SQ5StaticStaticContextStatic->AST SQ4DynamicDynamicContextStatic->Dynamic DQ2Dynamic->Exec DQ5SchemaIn-ScopeSchemaDefinitionsSchema->StaticXPathXPathXPath->AST SQ1XMLXMLPSVIInfoset/PSVIXML->PSVI DM1JSONJSONJSON->XDM DM2PSVI->XDM DM2DirectOther/DirectGenerationDirect->XDM DM3XSDXMLSchemaXSD->Schema SI1DirectXSDOther/DirectGenerationDirectXSD->Schema SI2HostHostEnvironmentHost->Static SQ2Host->Dynamic DQ3

Figure 1: Processing Model Overview

Figure 1 provides a schematic overview of the processing steps that are discussed in detail below. Some of these steps are completely outside the domain of XPath 4.0; in Figure 1, these are depicted outside the line that represents the boundaries of the language, an area labeled external processing. The external processing domain includes generation of XDM instances that represent the data to be queried (see 2.3.1 Data Model Generation), schema import processing (see 2.3.2 Schema Import Processing), and serialization. The area inside the boundaries of the language is known as the XPath processing domain, which includes the static analysis and dynamic evaluation phases (see 2.3.3 Expression Processing). Consistency constraints on the XPath processing domain are defined in 2.3.6 Consistency Constraints.

2.3.1 Data Model Generation

The input data for an expression must be represented as one or more XDM instances. This process occurs outside the domain of XPath 4.0, which is why Figure 1 represents it in the external processing domain.

In many cases the input data might originate as XML. Here are some steps by which an XML document might be converted to an XDM instance:

  1. A document may be parsed using an XML parser that generates an XML Information Set (see [XML Infoset]). The parsed document may then be validated against one or more schemas. This process, which is described in [XML Schema 1.0 Part 1] or [XML Schema 1.1 Part 1], results in an abstract information structure called the Post-Schema Validation Infoset (PSVI). If a document has no associated schema, its Information Set is preserved. (See DM1 in Figure 1)

  2. The Information Set or PSVI may be transformed into an XDM instance by a process described in [XQuery and XPath Data Model (XDM) 4.0][XDM 4.0]. (See DM2 in Figure 1)

The above steps provide an example of how an XDM instance might be constructed. An XDM instance might also be constructed in some other way (see DM3 in Figure 1), for example it might be synthesized directly from a relational database, or derived by parsing a JSON text or a CSV file. Whatever the origin, XPath 4.0 is defined in terms of the data model, but it does not place any constraints on how XDM instances are constructed.

The remainder of this section is concerned with the common case where XML data is being processed.

[Definition: Each element node and attribute node in an XDM instance has a type annotation (described in [XDM 4.0] section Section 4.1 Schema InformationDM). The type annotation of a node is a reference to a schema type. ] The type-name of a node is the name of the type referenced by its type annotation (but note that the type annotation can be a reference to an anonymous type). If the XDM instance was derived from a validated XML document as described in [XDM 4.0] section Section 7.3.3 Construction from a PSVIDM, the type annotations of the element and attribute nodes are derived from schema validation. XPath 4.0 does not provide a way to directly access the type annotation of an element or attribute node.

The value of an attribute is represented directly within the attribute node. An attribute node whose type is unknown (such as might occur in a schemaless document) is given the type annotationxs:untypedAtomic.

The value of an element is represented by the children of the element node, which may include text nodes and other element nodes. The type annotation of an element node indicates how the values in its child text nodes are to be interpreted. An element that has not been validated (such as might occur in a schemaless document) is annotated with the schema typexs:untyped. An element that has been validated and found to be partially valid is annotated with the schema type xs:anyType. If an element node is annotated as xs:untyped, all its descendant element nodes are also annotated as xs:untyped. However, if an element node is annotated as xs:anyType, some of its descendant element nodes may have a more specific type annotation.

2.3.4 Input Sources

XPath 4.0 has a set of functions that provide access to XML documents (fn:doc, fn:doc-available), collections (fn:collection, fn:uri-collection), text files (fn:unparsed-text, fn:unparsed-text-lines, fn:unparsed-text-available), and environment variables (fn:environment-variable, fn:available-environment-variables). These functions are defined in [Functions and Operators 4.0] section Section 14.6 Functions giving access to external informationFO.

An expression can access input data either by calling one of these input functions or by referencing some part of the dynamic context that is initialized by the external environment, such as a variable or context value.

Note:

The EXPath Community Group has developed a File Module, which some implementations use to perform file system related operations such as reading or writing files and directories. Multiple files can be read or written from a single query.

2.3.5 Serialization

[Definition: Serialization is the process of converting an XDM instance to a sequence of octets (step DM4 in Figure 1.), as described in [XSLT and XQuery Serialization 4.0].]

Note:

This definition of serialization is the definition used in this specification. Any form of serialization that is not based on [XSLT and XQuery Serialization 4.0] is outside the scope of the XPath 4.0 specification.

Serialization is outside the scope of the XPath specification, except to the extent that there is a function fn:serialize that enables serialization to be invoked.

2.4 Error Handling

2.4.3 Handling Dynamic Errors

Except as noted in this document, if any operand of an expression raises a dynamic error, the expression also raises a dynamic error. If an expression can validly return a value or raise a dynamic error, the implementation may choose to return the value or raise the dynamic error (see 2.4.4 Errors and Optimization). For example, the logical expression expr1 and expr2 may return the value false if either operand returns false, or may raise a dynamic error if either operand raises a dynamic error.

If more than one operand of an expression raises an error, the implementation may choose which error is raised by the expression. For example, in this expression:

($x div $y) + xs:decimal($z)

both the sub-expressions ($x div $y) and xs:decimal($z) may raise an error. The implementation may choose which error is raised by the + expression. Once one operand raises an error, the implementation is not required, but is permitted, to evaluate any other operands.

[Definition: In addition to its identifying QName, a dynamic error may also carry a descriptive string and one or more additional values called error values.] An implementation may provide a mechanism whereby an application-defined error handler can process error values and produce diagnostic messages. The host language may also provide error handling mechanisms.

A dynamic error may be raised by a system function or operator. For example, the div operator raises an error if its operands are xs:decimal values and its second operand is equal to zero. Errors raised by system functions and operators are defined in [XQuery and XPath Functions and Operators 4.0] or the host language.

A dynamic error can also be raised explicitly by calling the fn:error function, which always raises a dynamic error and never returns a value. This function is defined in [Functions and Operators 4.0] section Section 3.1.1 fn:errorFO. For example, the following function call raises a dynamic error, providing a QName that identifies the error, a descriptive string, and a diagnostic value (assuming that the prefix app is bound to a namespace containing application-defined error codes):

error( #app:err057, "Unexpected value", string($v) )

2.5 Concepts

This section explains some concepts that are important to the processing of XPath 4.0 expressions.

2.5.1 Document Order

An ordering called document order is defined among all the nodes accessible during processing of a given expression, which may consist of one or more trees (documents or fragments).

Document order applies both to XNodes (typically corresponding to nodes in an XML document, and generally referred to simply as nodes), and also to JNodesDM, often corresponding to the contents of a JSON source text. These are known collectively as GNodesDM (for "generalized node").

Document order is defined in [XDM 4.0] section Section 6.2 Document OrderDM, and its definition is repeated here for convenience. Document order is a total ordering, although the relative order of some nodes is implementation-dependent. [Definition: Informally, document order is the order in which nodes appear in the XML serialization of a document.] [Definition: Document order is stable, which means that the relative order of two nodes will not change during the processing of a given expression, even if this order is implementation-dependent.] [Definition: The node ordering that is the reverse of document order is called reverse document order.]

Within an XTreeDM, (that is, a tree consisting of XNodes), document order satisfies the following constraints:

  1. The root node precedes all other nodes.

  2. A parent node precedes its children (and therefore its descendants).

  3. The children of a node N precede the following siblings of N.

  4. Namespace nodes immediately follow the element node with which they are associated. The relative order of namespace nodes is stable but implementation-dependent.

  5. Attribute nodes immediately follow the namespace nodes of the element node with which they are associated. The relative order of attribute nodes is stable but implementation-dependent.

  6. The relative order of siblings is the order in which they occur in the children property of their parent node.

Similarly, within an JTreeDM, (that is, a tree consisting of JNodes), document order satisfies the following constraints:

  1. The root JNode precedes all other JNodes.

  2. A parent JNode precedes its children (and therefore its descendants).

  3. The children of a JNode N precede the following siblings of N.

  4. The children of a JNode that wraps an array follow the ordering of the members of the array.

  5. The children of a JNode that wraps a map follow the ordering of the entries in the map.

The relative order of nodes in distinct trees is stable but implementation-dependent, subject to the following constraint: If any node in a given tree T1 is before any node in a different tree T2, then all nodes in tree T1 are before all nodes in tree T2.

2.5.2 Typed Value and String Value

Every node (that is, every XNodeDM) has a typed value and a string value, except for nodes whose value is absentDM. [Definition: The typed value of a node is a sequence of atomic items and can be extracted by applying the Section 2.1.4 fn:dataFOdata function to the node.] [Definition: The string value of a node is a string and can be extracted by applying the Section 2.1.3 fn:stringFOstring function to the node.]

An implementation may store both the typed value and the string value of a node, or it may store only one of these and derive the other as needed. The string value of a node must be a valid lexical representation of the typed value of the node, but the node is not required to preserve the string representation from the original source document. For example, if the typed value of a node is the xs:integer value 30, its string value might be "30" or "0030".

The typed value, string value, and type annotation of a node are closely related. If the node was created by mapping from an Infoset or PSVI, the relationships among these properties are defined by rules in [XDM 4.0] section Section 4.1 Schema InformationDM.

The relationship between typed value and string value for various kinds of nodes is summarized and illustrated by examples below.

  1. For text and document nodes, the typed value of the node is the same as its string value, as an instance of the type xs:untypedAtomic. The string value of a document node is formed by concatenating the string values of all its descendant text nodes, in document order.

  2. The typed value of a comment, namespace, or processing instruction node is the same as its string value. It is an instance of the type xs:string.

  3. The typed value of an attribute node with the type annotationxs:anySimpleType or xs:untypedAtomic is the same as its string value, as an instance of xs:untypedAtomic. The typed value of an attribute node with any other type annotation is derived from its string value and type annotation using the lexical-to-value-space mapping defined in [XML Schema 1.0] or [XML Schema 1.1] Part 2 for the relevant type.

    Example: A1 is an attribute having string value "3.14E-2" and type annotation xs:double. The typed value of A1 is the xs:double value whose lexical representation is 3.14E-2.

    Example: A2 is an attribute with type annotation xs:IDREFS, which is a list datatype whose item type is the atomic datatype xs:IDREF. Its string value is "bar baz faz". The typed value of A2 is a sequence of three atomic items ("bar", "baz"", "faz""), each of type xs:IDREF. The typed value of a node is never treated as an instance of a named list type. Instead, if the type annotation of a node is a list type (such as xs:IDREFS), its typed value is treated as a sequence of the generalized atomic type from which it is derived (such as xs:IDREF).

  4. For an element node, the relationship between typed value and string value depends on the node’s type annotation, as follows:

    1. If the type annotation is xs:untyped or xs:anySimpleType or denotes a complex type with mixed content (including xs:anyType), then the typed value of the node is equal to its string value, as an instance of xs:untypedAtomic. However, if the nilled property of the node is true, then its typed value is the empty sequence.

      Example: E1 is an element node having type annotation xs:untyped and string value "1999-05-31". The typed value of E1 is "1999-05-31", as an instance of xs:untypedAtomic.

      Example: E2 is an element node with the type annotation formula, which is a complex type with mixed content. The content of E2 consists of the character H, a child element named subscript with string value "2", and the character O. The typed value of E2 is "H2O" as an instance of xs:untypedAtomic.

    2. If the type annotation denotes a simple type or a complex type with simple content, then the typed value of the node is derived from its string value and its type annotation in a way that is consistent with schema validation. However, if the nilled property of the node is true, then its typed value is the empty sequence.

      Example: E3 is an element node with the type annotation cost, which is a complex type that has several attributes and a simple content type of xs:decimal. The string value of E3 is "74.95". The typed value of E3 is 74.95, as an instance of xs:decimal.

      Example: E4 is an element node with the type annotation hatsizelist, which is a simple type derived from the atomic typehatsize, which in turn is derived from xs:integer. The string value of E4 is "7 8 9". The typed value of E4 is a sequence of three values (7, 8, 9), each of type hatsize.

      Example: E5 is an element node with the type annotation my:integer-or-string which is a union type with member types xs:integer and xs:string. The string value of E5 is "47". The typed value of E5 is 47 as a xs:integer, since xs:integer is the member type that validated the content of E5. In general, when the type annotation of a node is a union type, the typed value of the node will be an instance of one of the member types of the union.

      Note:

      If an implementation stores only the string value of a node, and the type annotation of the node is a union type, the implementation must be able to deliver the typed value of the node as an instance of the appropriate member type.

    3. If the type annotation denotes a complex type with empty content, then the typed value of the node is the empty sequence and its string value is the zero-length string.

    4. If the type annotation denotes a complex type with element-only content, then the typed value of the node is absentDM. The fn:data function raises a type error [err:FOTY0012]FO40 when applied to such a node. The string value of such a node is equal to the concatenated string values of all its text node descendants, in document order.

      Example: E6 is an element node with the type annotation weather, which is a complex type whose content type specifies element-only. E6 has two child elements named temperature and precipitation. The typed value of E6 is absentDM, and the fn:data function applied to E6 raises an error.

2.5.3 Atomization

The semantics of some XPath 4.0 operators depend on a process called atomization. Atomization is applied to a value when the value is used in a context in which a sequence of atomic items is required. The result of atomization is either a sequence of atomic items or a type error [err:FOTY0012]FO40. [Definition: Atomization of a sequence is defined as the result of invoking the fn:data function, as defined in [Functions and Operators 4.0] section Section 2.1.4 fn:dataFO.]

The semantics of fn:data are repeated here for convenience. The result of fn:data is the sequence of atomic items produced by applying the following rules to each item in the input sequence:

  • If the item is an atomic item, it is returned.

  • If the item is a node (specifically, an XNode), its typed value is returned (a type error [err:FOTY0012]FO40 is raised if the node has no typed value.)

  • If the item is a JNodeDM, its ·content· property is atomized and the result is returned.

  • If the item is a function item (other than an array) or map a type error [err:FOTY0013]FO40 is raised.

  • If the item is an array $a, atomization is defined as $a?* ! fn:data(.), which is equivalent to atomizing the members of the array.

    Note:

    This definition recursively atomizes members that are arrays. Hence, the result of atomizing the array [ [ 1, 2, 3 ], [ 4, 5, 6 ] ] is the sequence (1, 2, 3, 4, 5, 6).

Atomization is used in processing many expressions that are designed to operate on atomic items, including:

  • Arithmetic expressions

  • Comparison expressions

  • Function calls and returns

  • Cast expressions

Atomization plays an important role in the coercion rules used when converting a supplied argument in a function call to the type declared in the function signature.

2.5.4 Effective Boolean Value

Under certain circumstances (some of which are listed below), it is necessary to find the effective boolean value of a value. [Definition: The effective boolean value of a value is defined as the result of applying the fn:boolean function to the value, as defined in Section 8.3.1 fn:booleanFO.]

The dynamic semantics of fn:boolean are repeated here for convenience:

  1. If its operand is an empty sequence, fn:boolean returns false.

  2. If its operand is a sequence whose first item is a GNodeDM, fn:boolean returns true.

  3. If its operand is a singleton value of type xs:boolean or derived from xs:boolean, fn:boolean returns the value of its operand unchanged.

  4. If its operand is a singleton value of type xs:string, xs:anyURI, xs:untypedAtomic, or a type derived from one of these, fn:boolean returns false if the operand value has zero length; otherwise it returns true.

  5. If its operand is a singleton value of any numeric type or derived from a numeric type, fn:boolean returns false if the operand value is NaN or is numerically equal to zero; otherwise it returns true.

  6. In all other cases, fn:boolean raises a type error [err:FORG0006]FO40.

    Note:

    For instance, fn:boolean raises a type error if the operand is a function, a map, or an array.

The effective boolean value of a sequence is computed implicitly during processing of the following types of expressions:

Note:

The definition of effective boolean value is not used when casting a value to the type xs:boolean, for example in a cast expression. It also plays no role in the coercion rules used when passing a value to a function whose signature declares a parameter of type xs:boolean.

3 Types

As noted in 2.1.3 Values, every value in XPath 4.0 is regarded as a sequence of zero, one, or more items. The type system of XPath 4.0, described in this section, classifies the kinds of value that the language can handle, and the operations permitted on different kinds of value.

The type system of XPath 4.0 is related to the type system of [XML Schema 1.0] or [XML Schema 1.1] in two ways:

This chapter of the specification starts by defining sequence types and item types, which describe the range of values that can be bound to variables, used in expressions, or passed to functions. It then describes how these relate to schema types, that is, the simple and complex types defined in an XSD schema.

Note:

In many situations the terms item type and sequence type are used interchangeably to refer either to the type itself, or to the syntactic construct that designates the type: so in the expression $x instance of xs:string*, the construct xs:string* uses the SequenceType syntax to designate a sequence type whose instances are sequences of strings. When more precision is required, the specification is careful to use the terms item type and sequence type to refer to the actual types, while using the production names ItemType and SequenceType to refer to the syntactic designators of these types.

3.2 Item Types

[Definition: An item type is a type that can be expressed using the ItemType syntax, which forms part of the SequenceType syntax. Item types match individual items.]

Note:

While this definition is adequate for the purpose of defining the syntax of XPath 4.0, it ignores the fact that there are also item types that cannot be expressed using XPath 4.0 syntax: specifically, item types that reference an anonymous simple type or complex type defined in a schema. Such types can appear as type annotations on nodes following schema validation.

In most cases, the set of items matched by an item type consists either exclusively of atomic items, exclusively of nodes, or exclusively of function itemsDM. Exceptions include the generic types item(), which matches all items, xs:error, which matches no items, and choice item types, which can match any combination of types.

[Definition: An item type designator is a syntactic construct conforming to the grammar rule ItemType. An item type designator is said to designate an item type.]

Note:

Two item type designators may designate the same item type. For example, element() and element(*) are equivalent, as are attribute(A) and attribute(A, xs:anySimpleType).

Lexical QNames appearing in an item type designator are expanded using the default type namespace rule. Equality of QNames is defined by the eq operator.

ItemType::=RegularItemType | FunctionType | TypeName | ChoiceItemType
RegularItemType::=AnyItemTest | NodeKindTest | GNodeType | JNodeType | MapType | ArrayType | RecordType | EnumerationType
AnyItemTest::="item" "(" ")"
NodeKindTest::=DocumentTest
| ElementTest
| AttributeTest
| SchemaElementTest
| SchemaAttributeTest
| PITest
| CommentTest
| TextTest
| NamespaceNodeTest
| AnyNodeKindTest
DocumentTest::="document-node" "(" (ElementTest | SchemaElementTest | NameTestUnion)? ")"
ElementTest::="element" "(" (NameTestUnion ("," TypeName "?"?)?)? ")"
SchemaElementTest::="schema-element" "(" ElementName ")"
NameTestUnion::=(NameTest ++ "|")
NameTest::=EQName | Wildcard
AttributeTest::="attribute" "(" (NameTestUnion ("," TypeName)?)? ")"
SchemaAttributeTest::="schema-attribute" "(" AttributeName ")"
PITest::="processing-instruction" "(" (NCName | StringLiteral)? ")"
StringLiteral::=AposStringLiteral | QuotStringLiteral
/* ws: explicit */
CommentTest::="comment" "(" ")"
TextTest::="text" "(" ")"
NamespaceNodeTest::="namespace-node" "(" ")"
AnyNodeKindTest::="node" "(" ")"
GNodeType::="gnode" "(" ")"
JNodeType::="jnode" "(" SequenceType? ")"
MapType::=AnyMapType | TypedMapType
ArrayType::=AnyArrayType | TypedArrayType
RecordType::=AnyRecordType | TypedRecordType
EnumerationType::="enum" "(" (StringLiteral ++ ",") ")"
FunctionType::=AnyFunctionType
| TypedFunctionType
TypeName::=EQName
EQName::=QName | URIQualifiedName
ChoiceItemType::="(" (ItemType ++ "|") ")"

This section defines the syntax and semantics of different ItemTypes in terms of the values that they match.

Note:

For an explanation of the EBNF grammar notation (and in particular, the operators ++ and **), see A.1 EBNF.

An item type designator written simply as an EQName (that is, a TypeName) is interpreted as follows:

  1. If the name is written as a lexical QName, then it is expanded using the default type namespace rule.

  2. If the expanded name matches a named item type in the static context, then it is taken as a reference to the corresponding item type. The rules that apply are the rules for the expanded item type definition.

  3. Otherwise, it must match the name of a type in the in-scope schema types in the static context: specifically, an atomic type or a pure union type. See 3.5 Schema Types for details.

    Note:

    A name in the xs namespace will always fall into this category, since the namespace is reserved. See 2.1.4 Namespaces and QNames.

  4. If the name cannot be resolved to a type, a static error is raised [err:XPST0051].

3.2.8 Function, Map, and Array Types

The following sections describe the syntax for item types for functions, including arrays and maps.

The subtype relation among these types is described in the various subsections of 3.3.2 Subtypes of Item Types.

3.2.8.1 Function Types

Changes in 4.0  

  1. The keyword fn is allowed as a synonym for function in function types, to align with changes to inline function declarations.  [Issue 1192 PR 1197 21 May 2024]

  2. The terms FunctionType, ArrayType, MapType, and RecordType replace FunctionTest, ArrayTest, MapTest, and RecordTest, with no change in meaning.

  3. Parameter names may be included in a function signature; they are purely documentary.   [Issue 1136 PR 1696 12 January 2025]

A FunctionType matches selected function items, potentially checking their signatureDM (which includes the types of the arguments and results).

FunctionType::=AnyFunctionType
| TypedFunctionType
AnyFunctionType::=("function" | "fn") "(" "*" ")"
TypedFunctionType::=("function" | "fn") "(" (TypedFunctionParam ** ",") ")" "as" SequenceType
TypedFunctionParam::=("$" EQName "as")? SequenceType
EQName::=QName | URIQualifiedName
SequenceType::=("empty-sequence" "(" ")")
| (ItemTypeOccurrenceIndicator?)

The keywords function and fn are synonyms.

An AnyFunctionType matches any function item, including a map or an array. For example, the following expressions all return true:

  • fn:name#1 instance of function(*)

  • fn { @id } instance of function(*)

  • fn:random-number-generator() instance of function(*)

  • [ 1, 2, 3 ] instance of fn(*)

  • {} instance of fn(*)

A TypedFunctionType matches a function item if the function’s type signature (as defined in [XDM 4.0] section Section 8.1 Function ItemsDM) is a subtype of the TypedFunctionType.

Note:

The keywords function and fn are synonymous.

If parameter names are included in a TypedFunctionType, they are purely documentary and have no semantic effect. In particular, they play no part in deciding whether a particular function item matches the function type, and they never appear as keywords in function calls. For example the construct function($x as node()) as xs:string designates exactly the same type as function(node()) as xs:string.

Any parameter names that are supplied must be distinct [err:XQST0039].

A TypedFunctionType may also match certain maps and arrays, as described in 3.2.8.2 Map Types and 3.2.8.4 Array Types

Here are some examples of expressions that use a TypedFunctionType:

  • fn:count#1 instance of function(item()*) as xs:integer returns true, because the signature of the function item fn:count#1 is function(item()*) as xs:integer.

  • fn:count#1 instance of function(xs:string*) as item() returns true, because the signature of the function item fn:count#1 is a subtype of function(xs:string*) as item().

    Note:

    The same type might also be written fn($x as xs:int, $y as xs:int) as xs:int.

  • function(xs:anyAtomicType) as item()* matches any map, or any other function item with the required signature.

  • function(xs:integer) as item()* matches any array, or any other function item with the required signature.

3.4 Coercion Rules

Changes in 4.0  

  1. The term "function conversion rules" used in 3.1 has been replaced by the term "coercion rules".   [ PR 254 29 November 2022]

  2. The coercion rules allow “relabeling” of a supplied atomic item where the required type is a derived atomic type: for example, it is now permitted to supply the value 3 when calling a function that expects an instance of xs:positiveInteger.   [Issue 117 PR 254 29 November 2022]

  3. The coercion rules now allow any numeric type to be implicitly converted to any other, for example an xs:double is accepted where the required type is xs:decimal.   [Issue 980 PR 911 30 January 2024]

  4. The coercion rules now allow conversion in either direction between xs:hexBinary and xs:base64Binary.   [Issues 130 480 PR 815 7 November 2023]

  5. The coercion rules now apply recursively to the members of an array and the entries in a map.   [Issue 1318 PR 1501 29 October 2024]

  6. The coercion rules now reorder the entries in a map when the required type is a record type.   [Issue 1862 PR 1874 25 March 2025]

[Definition: The coercion rules are rules used to convert a supplied value to a required type, for example when converting an argument of a function call to the declared type of the function parameter. ] The required type is expressed as a sequence type. The effect of the coercion rules may be to accept the value as supplied, to convert it to a value that matches the required type, or to reject it with a type error.

This section defines how the coercion rules operate; the situations in which the rules apply are defined elsewhere, by reference to this section.

Note:

In previous versions of this specification, the coercion rules were referred to as the function conversion rules. The terminology has changed because the rules are not exclusively associated with functions or function calling.

If the required type is empty-sequence(), no coercion takes place (the supplied value must be an empty sequence, or a type error occurs).

In all other cases, the required sequence typeT comprises a required item typeR and an optional occurrence indicator. The coercion rules are then applied to a supplied value V and the required type T as follows:

  1. If XPath 1.0 compatibility mode is true and V is not an instance of the required type T, then the conversions defined in 3.4.1 XPath 1.0 Compatibility Rules are applied to V. Then:

  2. Each item in V is processed against the required item type R using the item coercion rules defined in 3.4.2 Item Coercion Rules, and the results are sequence-concatenated into a single sequence V′.

  3. A type error is raised if the cardinality of V′ does not match the required cardinality of T [err:XPTY0004].

3.4.4 Function Coercion

Changes in 4.0  

  1. Function coercion now allows a function with arity N to be supplied where a function of arity greater than N is expected. For example this allows the function true#0 to be supplied where a predicate function is required.

  2. It has been clarified that function coercion applies even when the supplied function item matches the required function type. This is to ensure that arguments supplied when calling the function are checked against the signature of the required function type, which might be stricter than the signature of the supplied function item.   [Issue 1020 PRs 1023 1128 9 April 2024]

Function coercion is a transformation applied to function items during application of the coercion rules. [Definition: Function coercion wraps a function item in a new function whose signature is the same as the expected type. This effectively delays the checking of the argument and return types until the function is called.]

Given a function F, and an expected function type T, function coercion proceeds as follows:

  1. If F has higher arity than T, a type error is raised [err:XPTY0004]

  2. If F has lower arity than T, then F is wrapped in a new function that declares and ignores the additional argument; the following steps are then applied to this new function.

    For example, if T is function(node(), xs:boolean) as xs:string, and the supplied function is fn:name#1, then the supplied function is effectively replaced by function($n as node(), $b as xs:boolean) as xs:string { fn:name($n) }

    Note:

    This mechanism makes it easier to design versatile and extensible higher-order functions. For example, in previous versions of this specification, the second argument of the fn:filter function expected an argument of type function(item()) as xs:boolean. This has now been extended to function(item(), xs:integer) as xs:boolean, but existing code continues to work, because callback functions that are not interested in the value of the second argument simply ignore it.

  3. A type error is raised [err:XPTY0004] if, for any parameter type, or for the result type, the relevant type in the signature of the supplied function and the relevant type in the expected function type are substantively disjoint.

    For example, the types xs:integer and xs:string are substantively disjoint, so a function with signature function(xs:integer) as xs:boolean cannot be supplied where the expected type is function(xs:string) as xs:boolean.

  4. Function coercion then returns a new function item with the following properties (as defined in [XDM 4.0] section Section 8.1 Function ItemsDM):

    • name: The name of F(if not absent).

    • identity: A new function identity distinct from the identity of any other function item.

    • signature: Annotations is set to the annotations of F. TypedFunctionType is set to the expected type.

    • implementation: In effect, a FunctionBody that calls F, passing it the parameters of this new function, in order.

    • nonlocal variable bindings: An empty mapping.

These rules have the following consequences:

  • SequenceType matching of the function’s arguments and result are delayed until that function is called.

  • When the coerced function is called, the supplied arguments must match the parameter typed defined in T; it is not sufficient to match the parameter types defined in F.

  • The coercion rules rules applied to the function’s arguments and result are defined by the SequenceType it has most recently been coerced to. Additional coercion rules could apply when the wrapped function is called.

  • If an implementation has static type information about a function, that can be used to type check the function’s argument and return types during static analysis.

  • When function coercion is applied to a map or an array, the resulting function is not a map or array, and cannot be used as such. For example, the expression

    let $f as function(xs:integer) as xs:boolean := { 0: false(), 1: true() }
    return $f?0

    raises a type error, because a lookup expression requires the left hand operand to be a map or array, and $f is neither.

  • When function types are used as alternatives in a choice item type, the supplied function is coerced to the first alternative for which coercion does not raise a type error. In this situation it is important to write the alternatives in order, with the most specific first.

Note:

The semantics of function coercion are specified in terms of wrapping the functions. Static typing may be able to reduce the number of places where this is actually necessary. However, it cannot be assumed that because a supplied function is an instance of the required function type, no function coercion is necessary: the supplied function might not perform all required checks on the types of its arguments.

Since maps and arrays are also functions in XPath 4.0, function coercion applies to them as well. For instance, consider the following expression:

let $m := {
  "Monday" : true(),
  "Wednesday" : false(),
  "Friday" : true()
}
let $days := ("Monday", "Tuesday", "Wednesday", "Thursday", "Friday")
return filter($days, $m)

The map $m is an instance of function(xs:anyAtomicType?) as item()*. When the fn:filter() function is called, the following occurs to the map:

  1. The map $m is treated as a function equivalent to map:get($m, ?).

  2. The coercion rules result in applying function coercion to this function, wrapping it in a new function (M′) with the signature function(item(), xs:integer) as xs:boolean.

  3. When M′ is called by fn:filter(), coercion and SequenceType matching rules are applied to the argument, resulting in an item() value ($a) or a type error.

  4. The function map:get($m, ?) is called with $a as the argument; this returns either an xs:boolean or the empty sequence (call the result R).

  5. The wrapper function $p applies the coercion rules to R. If R is an xs:boolean the matching succeeds. When it is an empty sequence (in particular, $m does not contain a key for "Tuesday"), a type error is raised [err:XPTY0004], since the expected type is xs:boolean and the actual type is an empty sequence.

Consider the following expression:

let $m := {
   "Monday" : true(),
   "Wednesday" : false(),
   "Friday" : true(),
}
let $days := ("Monday", "Wednesday", "Friday")
return filter($days, $m)

In this case the result of the expression is the sequence ("Monday", "Friday"). But if the input sequence included the string "Tuesday", the filter operation would fail with a type error.

Note:

Function coercion applies even if the supplied function matches the required type.

For example, consider this case:

declare function local:filter(
  $s as item()*, 
  $p as function(xs:string) as xs:boolean
) as item()* {
  $s[$p(.)]
};

let $f := function($a) { $a mod 2 = 0 }
return local:filter(1 to 10, $f)

Here the supplied function $f is an instance of the required type, because its signature defaults the argument type to item()*, which is a supertype of xs:string. The expression $s[$p(.)] could in principle succeed. However, function coercion ensures that the supplied function is wrapped in a function that requires the argument to be of type xs:string, so the call fails with a type error when the wrapping function is invoked supplying an xs:integer as the argument.

3.5 Schema Types

[Definition: A schema type is a complex type or simple type as defined in the [XML Schema 1.0] or [XML Schema 1.1] specifications, including built-in types as well as user-defined types.]

Every schema type is either a complex type or a simple type; simple types are further subdivided into list types, union types, and atomic types (see [XML Schema 1.0] or [XML Schema 1.1] for definitions and explanations of these terms.)

A schema type can appear as a type annotation on an element or attribute node. The type annotation on an element node can be a complex type or a simple type; the type annotation on an attribute node is always a simple type. Non-instantiable types such as xs:NOTATION or xs:anyAtomicType never appear as type annotations, but their derived types can be so used. Union types never appear as type annotations; when an element or attribute is validated against a union type, the resulting type annotation will be one of the types in the transitive membership of the union type.

[Definition: An atomic type is a simple schema type whose {variety}XS11-1 is atomic.]

An atomic type is either a built-in atomic type (defined either in the XSD specification or in this specification), or it is a user-defined atomic type included in an imported schema.

The in-scope schema types in the static context are initialized with a set of predefined schema types that is determined by the host language. This set may include some or all of the schema types in the namespace http://www.w3.org/2001/XMLSchema, represented in this document by the namespace prefix xs. The schema types in this namespace are defined in [XML Schema 1.0] or [XML Schema 1.1] and augmented by additional types defined in [XQuery and XPath Data Model (XDM) 4.0][XDM 4.0]. An implementation that has based its type system on [XML Schema 1.0] is not required to support the xs:dateTimeStamp or xs:error types.

The schema types defined in [XDM 4.0] section Section 4.1.4 Predefined TypesDM are summarized below.

  1. [Definition: xs:untyped is used as the type annotation of an element node that has not been validated, or has been validated in skip mode.] No predefined schema types are derived from xs:untyped.

  2. [Definition: xs:untypedAtomic is an atomic type that is used to denote untyped atomic data, such as text that has not been assigned a more specific type.] An attribute that has been validated in skip mode is represented in the data model by an attribute node with the type annotationxs:untypedAtomic. No predefined schema types are derived from xs:untypedAtomic.

  3. [Definition: xs:dayTimeDuration is derived by restriction from xs:duration. The lexical representation of xs:dayTimeDuration is restricted to contain only day, hour, minute, and second components.]

  4. [Definition: xs:yearMonthDuration is derived by restriction from xs:duration. The lexical representation of xs:yearMonthDuration is restricted to contain only year and month components.]

  5. [Definition: xs:anyAtomicType is an atomic type that includes all atomic items (and no values that are not atomic). Its base type is xs:anySimpleType from which all simple types, including atomic, list, and union types, are derived. All primitive atomic types, such as xs:decimal and xs:string, have xs:anyAtomicType as their base type.]

    Note:

    xs:anyAtomicType will not appear as the type of an actual value in an XDM instance.

  6. [Definition: xs:error is a simple type with no value space. It is defined in Section 3.16.7.3 xs:error XS11-1 and can be used in the 3.1 Sequence Types to raise errors.]

The relationships among the schema types in the xs namespace are illustrated in Figure 2. A more complete description of the XPath 4.0 type hierarchy can be found in [Functions and Operators 4.0] section Section 1.8 Type SystemFO.

Type Hierarchy Diagram

Figure 2: Hierarchy of Schema Types used in XPath 4.0.

4 Expressions

This section discusses each of the basic kinds of expression. Each kind of expression has a name such as PathExpr, which is introduced on the left side of the grammar production that defines the expression. Since XPath 4.0 is a composable language, each kind of expression is defined in terms of other expressions whose operators have a higher precedence. In this way, the precedence of operators is represented explicitly in the grammar.

The order in which expressions are discussed in this document does not reflect the order of operator precedence. In general, this document introduces the simplest kinds of expressions first, followed by more complex expressions. For the complete grammar, see Appendix [A XPath 4.0 Grammar].

The highest-level symbol in the XPath grammar is XPath.

XPath::=Expr
Expr::=(ExprSingle ++ ",")
ExprSingle::=ForExpr
| LetExpr
| QuantifiedExpr
| IfExpr
| OrExpr
ForExpr::=ForClauseForLetReturn
LetExpr::=LetClauseForLetReturn
QuantifiedExpr::=("some" | "every") (QuantifierBinding ++ ",") "satisfies" ExprSingle
IfExpr::="if" "(" Expr ")" (UnbracedActions | BracedAction)
OrExpr::=AndExpr ("or" AndExpr)*

The XPath 4.0 operator that has lowest precedence is the comma operator, which is used to combine two operands to form a sequence. As shown in the grammar, a general expression (Expr) can consist of multiple ExprSingle operands, separated by commas.

The name ExprSingle denotes an expression that does not contain a top-level comma operator (despite its name, an ExprSingle may evaluate to a sequence containing more than one item.)

The symbol ExprSingle is used in various places in the grammar where an expression is not allowed to contain a top-level comma. For example, each of the arguments of a function call must be a ExprSingle, because commas are used to separate the arguments of a function call.

After the comma, the expressions that have next lowest precedence are ForExpr, LetExpr, QuantifiedExpr, IfExpr, and OrExpr. Each of these expressions is described in a separate section of this document.

4.2 Primary Expressions

[Definition: A primary expression is an instance of the production PrimaryExpr. Primary expressions are the basic primitives of the language. They include literals, variable references, context value references, and function calls. A primary expression may also be created by enclosing any expression in parentheses, which is sometimes helpful in controlling the precedence of operators.] Map and Array Constructors are described in 4.13.1 Maps and 4.13.2 Arrays.

PrimaryExpr::=Literal
| VarRef
| ParenthesizedExpr
| ContextValueRef
| FunctionCall
| FunctionItemExpr
| MapConstructor
| ArrayConstructor
| StringTemplate
| UnaryLookup
Literal::=NumericLiteral | StringLiteral | QNameLiteral
VarRef::="$" EQName
ParenthesizedExpr::="(" Expr? ")"
ContextValueRef::="."
FunctionCall::=EQNameArgumentList
/* xgc: reserved-function-names */
/* gn: parens */
FunctionItemExpr::=NamedFunctionRef | InlineFunctionExpr
NamedFunctionRef::=EQName "#" IntegerLiteral
/* xgc: reserved-function-names */
InlineFunctionExpr::=MethodAnnotation* ("function" | "fn") FunctionSignature? FunctionBody
MapConstructor::="map"? "{" (MapConstructorEntry ** ",") "}"
ArrayConstructor::=SquareArrayConstructor | CurlyArrayConstructor
StringTemplate::="`" (StringTemplateFixedPart | StringTemplateVariablePart)* "`"
/* ws: explicit */
UnaryLookup::=Lookup

4.2.1 Literals

Literal::=NumericLiteral | StringLiteral | QNameLiteral
NumericLiteral::=IntegerLiteral | HexIntegerLiteral | BinaryIntegerLiteral | DecimalLiteral | DoubleLiteral
StringLiteral::=AposStringLiteral | QuotStringLiteral
/* ws: explicit */
QNameLiteral::="#" EQName

[Definition: A literal is a direct syntactic representation of an atomic item.] XPath 4.0 supports three kinds of literals: numeric literals, string literals, and QName literals.

4.2.1.1 Numeric Literals

Changes in 4.0  

  1. Numeric literals can now be written in hexadecimal or binary notation; and underscores can be included for readability.   [Issue 429 PR 433 25 April 2023]

NumericLiteral::=IntegerLiteral | HexIntegerLiteral | BinaryIntegerLiteral | DecimalLiteral | DoubleLiteral
IntegerLiteral::=Digits
/* ws: explicit */
Digits::=DecDigit ((DecDigit | "_")* DecDigit)?
/* ws: explicit */
DecDigit::=[0-9]
/* ws: explicit */
HexIntegerLiteral::="0x" HexDigits
/* ws: explicit */
HexDigits::=HexDigit ((HexDigit | "_")* HexDigit)?
/* ws: explicit */
HexDigit::=[0-9a-fA-F]
/* ws: explicit */
BinaryIntegerLiteral::="0b" BinaryDigits
/* ws: explicit */
BinaryDigits::=BinaryDigit ((BinaryDigit | "_")* BinaryDigit)?
/* ws: explicit */
BinaryDigit::=[01]
/* ws: explicit */
DecimalLiteral::=("." Digits) | (Digits "." Digits?)
/* ws: explicit */
DoubleLiteral::=(("." Digits) | (Digits ("." Digits?)?)) [eE] [+-]? Digits
/* ws: explicit */

The value of a numeric literal is determined as follows (taking the rules in order):

  1. Underscore characters are stripped out. Underscores may be included in a numeric literal to aid readability, but have no effect on the value. For example, 1_000_000 is equivalent to 1000000.

    Note:

    Underscores must not appear at the beginning or end of a sequence of digits, only in intermediate positions. Multiple adjacent underscores are allowed.

  2. A HexIntegerLiteral represents a non-negative integer expressed in hexadecimal: for example 0xffff represents the integer 65535, and 0xFFFF_FFFF represents the integer 4294967295.

  3. A BinaryIntegerLiteral represents a non-negative integer expressed in binary: for example 0b101 represents the integer 5, and 0b1111_1111 represents the integer 255.

  4. The value of a numeric literal containing no . and no e or E character is an atomic item of type xs:integer; the value is obtained by casting from xs:string to xs:integer as specified in [Functions and Operators 4.0] section Section 23.2 Casting from xs:string and xs:untypedAtomicFO.

  5. The value of a numeric literal containing . but no e or E character is an atomic item of type xs:decimal; the value is obtained by casting from xs:string to xs:decimal as specified in [Functions and Operators 4.0] section Section 23.2 Casting from xs:string and xs:untypedAtomicFO.

  6. The value of a numeric literal containing an e or E character is an atomic item of type xs:double; the value is obtained by casting from xs:string to xs:double as specified in [Functions and Operators 4.0] section Section 23.2 Casting from xs:string and xs:untypedAtomicFO.

Note:

The value of a numeric literal is always non-negative. An expression may appear to include a negative number such as -1, but this is technically an arithmetic expression comprising a unary minus operator followed by a numeric literal.

Note:

The effect of the above rules is that in the case of an integer or decimal literal, a dynamic error [err:FOAR0002]FO40 will generally be raised if the literal is outside the range of values supported by the implementation (other options are available: see [Functions and Operators 4.0] section Section 4.2 Arithmetic operators on numeric valuesFO for details.)

The XML Schema specification allows implementations to impose a limit (which must not be less than 18 digits) on the size of integer and decimal values. The full range of values of built-in subtypes of xs:integer, such as xs:long and xs:unsignedLong, can be supported only if the limit is 20 digits or higher. Negative numbers such as the minimum value of xs:long (-9223372036854775808) are technically unary expressions rather than literals, but implementations may prefer to ensure that they are expressible.

Here are some examples of numeric literals:

  • 12 denotes the xs:integer value twelve.

  • 1_000_000 denotes the xs:integer value one million.

  • 12.5 denotes the xs:decimal value twelve and one half.

  • 3.14159_26535_89793e0 is an xs:double value representing the mathematical constant π to 15 decimal places.

  • 125E2 denotes the xs:double value twelve thousand, five hundred.

  • 0xffff denotes the xs:integer value 65535.

  • 0b1000_0001 denotes the xs:integer value 129.

4.2.1.4 Constants of Other Types

The xs:boolean values true and false can be constructed by calls to the system functionsfn:true() and fn:false(), respectively.

Values of other simple types can be constructed by calling the constructor function for the given type. The constructor functions for XML Schema built-in types are defined in [Functions and Operators 4.0] section Section 22.1 Constructor functions for XML Schema built-in atomic typesFO. In general, the name of a constructor function for a given type is the same as the name of the type (including its namespace). For example:

  • xs:integer("12") returns the integer value twelve.

  • xs:date("2001-08-25") returns an item whose type is xs:date and whose value represents the date 25th August 2001.

  • xs:dayTimeDuration("PT5H") returns an item whose type is xs:dayTimeDuration and whose value represents a duration of five hours.

Constructor functions can also be used to create special values that have no literal representation, as in the following examples:

  • xs:float("NaN") returns the special floating-point value, "Not a Number."

  • xs:double("INF") returns the special double-precision value, "positive infinity."

Constructor functions are available for all simple types, including union types. For example, if my:dt is a user-defined union type whose member types are xs:date, xs:time, and xs:dateTime, then the expression my:dt("2011-01-10") creates an atomic item of type xs:date. The rules follow XML Schema validation rules for union types: the effect is to choose the first member type that accepts the given string in its lexical space.

It is also possible to construct values of various types by using a cast expression. For example:

  • 9 cast as hatsize returns the atomic item 9 whose type is hatsize.

4.5 Functions

Functions in XPath 4.0 arise in two ways:

The functions defined by a statically known function definition can be invoked using a static function call. Function items corresponding to these definitions can also be obtained, as dynamic values, by evaluating a named function reference. Function items can also be obtained using the fn:function-lookup function: in this case the function name and arity do not need to be known statically, and the function definition need not be present in the static context, so long as it is in the dynamic context.

Static and dynamic function calls are described in the following sections.

4.5.1 Static Function Calls

The static context for an expression includes a set of statically known function definitions. Every function definition in the static context has a name (which is an expanded QName) and an arity range, which is a range of permitted arities for calls on that function. Two function definitions having the same name must not have overlapping arity ranges. This means that for a given static function call, it is possible to identify the target function definition in the static context unambiguously from knowledge of the function name and the number of supplied arguments.

A static function call is bound to a function definition in the static context by matching the name and arity. If the function call has P positional arguments followed by K keyword arguments, then the required arity is P+K, and the static context must include a function definition whose name matches the expanded QName in the function call, and whose arity range includes this required arity. This is the function chosen to be called. The result of the function is obtained by evaluating the expression that forms its implementation, with a dynamic context that provides values for all the declared parameters, initialized as described in 4.5.1.2 Evaluating Static Function Calls below.

Similarly, a function reference of the form f#N binds to a function definition in the static context whose name matches f where MinP ≤ N and MaxP ≥ N. The result of evaluating a function reference is a function item which can be called using a dynamic function call. Function items are never variadic and their arguments are always supplied positionally. For example, the function reference fn:concat#3 returns a function item with arity 3, which is always called by supplying three positional arguments, and whose effect is the same as a static call on fn:concat with three positional arguments.

The detailed rules for evaluating static function calls and function references are defined in subsequent sections.

4.5.1.2 Evaluating Static Function Calls

This section applies to static function calls where none of the arguments is an ArgumentPlaceholder. For function calls involving placeholders, see 4.5.4 Partial Function Application.

When a static function call FC is evaluated with respect to a static context SC and a dynamic context DC, the result is obtained as follows:

  1. The function definitionFD to be used is found in the statically known function definitions of SC.

    The required arity is the total number of arguments in the function call, including both positional and keyword arguments.

    There can be at most one function definitionFD in the statically known function definitions component of SC whose function name matches the expanded QName in FC and whose arity range includes the arity of FC’s ArgumentList.

    If there is no such function definition, a static error [err:XPST0017] is raised.

  2. Each parameter in the function definitionFD is matched to an argument expression as follows:

    1. If there are N positional arguments in the function call FC, then the corresponding argument expressions are matched pairwise to the first N parameters in the declaration. For this purpose the required parameters and optional parameters in FD are concatenated into a single list, in order.

    2. Any keyword arguments in FC are then matched to parameters (whether required or optional) in FD by comparing the keyword used in FC with the paramater name declared in FD. Each keyword must match the name of a declared parameter [err:XPST0017], and this must be one that has not already been matched to a positional argument. [err:XPST0017].

    3. If any required parameter has not been matched to any argument in FC by applying the above rules, a static error is reported [err:XPST0017]

    4. If any optional parameter has not been matched to any argument in FC by applying the above rules, then the parameter is matched to the default value expression for that parameter in FD.

  3. Each argument expression established by the above rules is evaluated with respect to DC. The order of argument evaluation is implementation dependent and it is not required that an argument be evaluated if the function body can be evaluated without evaluating that argument.

    Note:

    All argument expressions, including default value expressions, are evaluated in the dynamic context of the function call. It is therefore possible to use a default value expression such as ., or /, or fn:current-dateTime(), whose value depends on the dynamic context of the function call.

    If the expression used for the default value of a parameter has no dependencies on the dynamic context, then an implementation may choose to reuse the same value on repeated function calls rather than re-evaluating it on each function call.

    Note:

    This is relevant, for example, if the expression constructs new nodes.

  4. The result of evaluating the argument expression is converted to the required type (the declared type associated with the corresponding parameter in the function declaration, defaulting to item()*) by applying the coercion rules.

    This applies both to explicitly supplied arguments, and to values obtained by evaluating default value expressions. In both cases a type error will be raised if the value (after coercion) does not match the required type.

  5. The result of the function call is obtained as follows:

    • FD’s body is invoked in an implementation-dependent way. The processor makes the following information available to that invocation:

      • The converted argument values;

      • If the function is context dependent, the static context SC and dynamic context DC of the function call.

    • The result is converted to the required type (the declared return type in the function declaration, defaulting to item()*) by applying the coercion rules.

      The result of applying the coercion rules is either an instance of FD’s return type or a dynamic error. This result is then the result of evaluating FC.

      Note:

      A host language may define alternative rules for processing the result, especially in the case of external functions implemented using a non-XDM type system.

    • Errors raised by system functions are defined in [XQuery and XPath Functions and Operators 4.0].

    • Errors raised by host-language-dependent functions are implementation-defined.

    Example: A System Function

    The following function call uses the function [Functions and Operators 4.0] section Section 2.1.5 fn:base-uriFO. Use of SC and DC and errors raised by this function are all defined in [XQuery and XPath Functions and Operators 4.0].

    base-uri()

4.5.2 Function Items

A function item is an XDM value that can be bound to a variable, or manipulated in various ways by XPath 4.0 expressions. The most significant such expression is a dynamic function call, which supplies values of arguments and evaluates the function to produce a result.

The syntax of dynamic function calls is defined in 4.5.3 Dynamic Function Calls.

A number of constructs can be used to produce a function item, notably:

These constructs are described in detail in the following sections, or in [XQuery and XPath Functions and Operators 4.0].

4.5.4 Partial Function Application

[Definition: A static or dynamic function call is a partial function application if one or more arguments is an ArgumentPlaceholder.]

The rules for partial function application in static function calls and dynamic function calls have a great deal in common, but they are stated separately below for clarity.

Partial function application delivers function items, whose arity is equal to the number of placeholders in the call.

A static partial function application always delivers one function item. A dynamic partial function application delivers one function item for each function item in the input.

More specifically, each function item in the result of the partial function application is a partially applied function. [Definition: A partially applied function is a function created by partial function application.]

For static function calls, the result is obtained as follows:

  1. The function definitionFD to be partially applied is determined in the same way as for a static function call without placeholders, as described in 4.5.1.1 Static Function Call Syntax. For this purpose an ArgumentPlaceholder contributes to the count of arguments.

  2. The parameters of FD are classified into three categories:

    • Parameters that map to a placeholder, referred to as placeholder parameters.

    • Parameters for which an explicit value is given in the function call (either positionally or by keyword), referred to as explicitly supplied parameters.

    • Parameters (which are necessarily optional parameters) for which no corresponding argument is supplied, either as a placeholder or with an explicit value. These are referred to as defaulted parameters.

    Note:

    A partial function application need not have any explicitly supplied parameters. For example, the partial function application fn:string(?) is allowed; it has exactly the same effect as the named function referencefn:string#1.

  3. Explicitly supplied parameters and defaulted parameters are evaluated and converted to the required type using the rules for a static function call. This may result in an error being raised.

    A type error is raised if any of the explicitly supplied or defaulted parameters, after applying the coercion rules, does not match the required type of the corresponding parameter.

    In addition, a dynamic error may be raised if any of the explicitly supplied or defaulted parameters does not match other constraints on the value of that parameter (for example, if the value supplied for a parameter expecting a regular expression is not a valid regular expression); or if the processor is able to establish that evaluation of the resulting function will fail for any other reason (for example, if an error is raised while evaluating a subexpression in the function body that depends only on explicitly supplied and defaulted parameters).

    In all cases the error code is the same as for a static function call supplying the same invalid value(s).

    In the particular case where all the supplied arguments are placeholders, the error behavior should be the same as for an equivalent named function reference: for example, fn:id#1 fails if there is no context node, and fn:id(?)should fail likewise.

  4. The result is a partially applied function having the following properties (which are defined in [XDM 4.0] section Section 8.1 Function ItemsDM):

    • name: The name of FD if all parameters map to placeholders, that is, if the partial function application is equivalent to the corresponding named function reference. Otherwise, the name is absent.

    • identity: A new function identity distinct from the identity of any other function item.

    • arity: The number of placeholders in the function call.

    • signature: The parameters in the returned function are the parameters of FD that have been identified as placeholder parameters, retaining the order in which the placeholders appear in the function call. The result type of the returned function is the same as the result type of FD.

      An implementation which can determine a more specific signature (for example, through use of type analysis) is permitted to do so.

    • annotations: The annotations of FD.

    • body: The body of FD.

    • captured context: The static and dynamic context of the function call, augmented, for each explicitly supplied parameter and each defaulted parameter, with a binding of the converted argument value to the corresponding parameter name.

    Note:

    A partial function application can be used to change the order of parameters, for example fn:contains(substring := ?, value := ?) returns a function item that is equivalent to fn:contains#2, but with the order of arguments reversed.

    Example: Partial Application of a System Function

    The following partial function application creates a function item that computes the sum of squares of a sequence.

    let $sum-of-squares := fold-right(?, 0, function($a, $b) { $a*$a + $b })
    return $sum-of-squares(1 to 3)

    $sum-of-squares is an anonymous function. It has one parameter, named $seq, which is taken from the corresponding parameter in fn:fold-right (the other two parameters are fixed). The implementation is the implementation of fn:fold-right, which is a context-independent system function. The nonlocal bindings contain the fixed bindings for the second and third parameters of fn:fold-right.

For dynamic function calls, the result is obtained as follows:

  1. The base expression of the function call is evaluated. If this is not of type function(*)* (a sequence of zero or more function items) then a type error is raised.

  2. The result of the dynamic function call is the sequence concatenation of the results of partial applying each function item, retaining order. That is, the result of F(X, Y, ...) is for $FI in F return $FI(X, Y, ...). The result of a dynamic function call applied to a single function item FI is defined by the rules that follow.

  3. An ArgumentPlaceholder contributes to the count of arguments.

  4. The parameters of FI are classified into two categories:

    • Parameters that map to a placeholder, referred to as placeholder parameters.

    • Parameters for which an explicit value is given in the function call, referred to as supplied parameters.

    Note:

    A partial function application need not have any explicitly supplied parameters. For example, if $f is a function with arity 2, then the partial function application $f(?, ?) returns a function that has exactly the same effect as $f.

  5. Arguments corresponding to supplied parameters are evaluated and converted to the required type of the parameter, using the rules for dynamic function calls.

    A type error is raised if any of the supplied parameters, after applying the coercion rules, does not match the required type.

    In addition, a dynamic error may be raised if any of the supplied parameters does not match other constraints on the value of that parameter (for example, if the value supplied for a parameter expecting a regular expression is not a valid regular expression); or if the processor is able to establish that evaluation of the resulting function will fail for any other reason (for example, if an error is raised while evaluating a subexpression in the function body that depends only on explicitly supplied parameters).

    In both cases the error code is the same as for a dynamic function call supplying the same invalid value.

  6. The result of the partial function application is a partially applied function with the following properties (which are defined in [XDM 4.0] section Section 8.1 Function ItemsDM):

    • name: Absent.

    • arity: The number of placeholders in the function call.

    • signature: The signature of FI, removing the types of supplied parameters. An implementation which can determine a more specific signature (for example, through use of type analysis) is permitted to do so.

    • annotations: The annotations of FI.

    • body: The body of FI.

    • captured context: the captured context of FI, augmented, for each supplied parameter, with a binding of the converted argument value to the corresponding parameter name.

    Note:

    In a dynamic partial function application, argument keywords are not available, so it is not possible to change the order of parameters.

    Example: Partial Application of an Anonymous Function

    In the following example, $f is an anonymous function, and $paf is a partially applied function created from $f.

    let $f := function($seq, $delim) { fold-left($seq, "", concat(?, $delim, ?)) }
    let $paf := $f(?, ".")
    return $paf(1 to 5)

    $paf is also an anonymous function. It has one parameter, named $delim, which is taken from the corresponding parameter in $f (the other parameter is fixed). The implementation of $paf is the implementation of $f, which is fn:fold-left($seq, "", fn:concat(?, $delim, ?)). This implementation is associated with the SC and DC of the original expression in $f. The nonlocal bindings associate the value "." with the parameter $delim.

Partial function application never returns a map or an array. If $f is a map or an array, then $f(?) is a partial function application that returns a function, but the function it returns is neither a map nor an array.

Example: Partial Application of a Map

The following partial function application converts a map to an equivalent function that is not a map.

let $a := { "A": 1, "B": 2 }(?)
return $a("A")

4.5.5 Named Function References

NamedFunctionRef::=EQName "#" IntegerLiteral
/* xgc: reserved-function-names */
EQName::=QName | URIQualifiedName
IntegerLiteral::=Digits
/* ws: explicit */
Digits::=DecDigit ((DecDigit | "_")* DecDigit)?
/* ws: explicit */
DecDigit::=[0-9]
/* ws: explicit */

[Definition: A named function reference is an instance of the production NamedFunctionRef: it is an expression (written name#arity) which evaluates to a function item, the details of the function item being based on the properties of a function definition in the static context.]

The name and arity of the required function are known statically.

The EQName is expanded using the default function namespace rule.

The expanded QName and arity must correspond to a function definition present in the static context. More specifically, for a named function reference F#N, there must be a function definition in the statically known function definitions whose name matches F, and whose arity range includes N. Call this function definitionFD.

If FD is context dependent for the given arity, then the returned function item has a captured context comprising the static and dynamic context of the named function reference.

Note:

In practice, it is necessary to retain only those parts of the static and dynamic context that can affect the outcome. These means it is unnecessary to retain parts of the context that no system function depends on (for example, local variables), or parts that are invariant within an execution scope (for example, the implicit timezone).

Example: A Context-Dependent Named Function Reference

Consider:

let $f := <foo/>/fn:name#0 return <bar/>/$f()

The function fn:name(), with no arguments, returns the name of the context node. The function item delivered by evaluating the expression fn:name#0 returns the name of the element that was the context node at the point where the function reference was evaluated (that is, the <foo> element). This expression therefore returns "foo", not "bar".

An error is raised if the identified function depends on components of the static or dynamic context that are not present, or that have unsuitable values. For example [err:XPDY0002] is raised for the expression fn:name#0 if the context item is absent, and [err:FODC0001]FO is raised for the call fn:id#1 if the context item is not a node in a tree that is rooted at a document node. The error that is raised is the same as the error that would be raised by the corresponding function if called with the same static and dynamic context.

If the expanded QName and arity in a named function reference do not match the name and arity range of a function definition in the static context, a static error is raised [err:XPST0017].

The value of a NamedFunctionRef is a function itemFI obtained from FD as follows:

  • name: The name of FD.

  • identity:

    • If FD is context dependent for the given arity, then a new function identity distinct from the identity of any other function item.

      Note:

      In the general case, a function reference to a context-dependent function will produce different results every time it is evaluated, because the resulting function item has a captured context (see [XDM 4.0] section Section 8.1 Function ItemsDM) that includes the dynamic context of the particular evaluation. Optimizers, however, are allowed to detect cases where the captured context happens to be the same, or where any variations are immaterial, and where it is therefore safe to return the same function item each time. This might be the case, for example, where the only context dependency of a function is on the default collation, and the default collation for both evaluations is known to be the same.

    • Otherwise, a function identity that is the same as that produced by the evaluation of any other named function reference with the same function name and arity.

      This rule applies even across different execution scopesFO: for example if a parameter to a call to fn:transform is set to the result of the expression fn:abs#1, then the function item passed as the parameter value will be identical to that obtained by evaluating the expression fn:abs#1 within the target XSLT stylesheet.

      This rule also applies when the target function definition is nondeterministicFO. For example all evaluations of the named function reference map:keys#2 return identical function items, even though two evaluations of map:keys with the same arguments may produce different results.

  • arity: As specified in the named function reference.

  • signature: Formed from the required types of the first A parameters of FD, and the function result type of FD.

  • annotations: The annotations of FD.

  • body: The body of FD.

  • captured context: Comprises the static and dynamic context of the named function reference, augmented with bindings of the names of parameters of FD beyond the A’th parameter, to their respective default values.

    Note:

    In practice, it is necessary to retain only the parts of the context that the function actually depends on (if any).

Note:

Consider the system function fn:format-date, which has an arity range of 2 to 5. The named function reference fn:format-date#3 returns a function item whose three parameters correspond to the first three parameters of fn:format-date; the remaining two arguments will take their default values. To obtain an arity-3 function that binds to arguments 1, 2, and 5 of fn:format-date, use the partial function application format-date(?, ?, place := ?).

The following are examples of named function references:

  • fn:abs#1 references the fn:abs function which takes a single argument.

  • fn:concat#5 references the fn:concat function which takes 5 arguments.

  • local:myfunc#2 references a function named local:myfunc which takes 2 arguments.

Note:

Function items, as values in the data model, have a fixed arity, and a dynamic function call always supplies the arguments positionally. In effect, the result of evaluating my:func#3 is the same as the result of evaluating the inline function expression fn($x, $y, $z) { my:func($x, $y, $z) }, except that the returned function has a name (it retains the name my:func).

4.5.6 Inline Function Expressions

Changes in 4.0  

  1. In inline function expressions, the keyword function may be abbreviated as fn.   [Issue 1192 PR 1197 21 May 2024]

  2. New abbreviated syntax is introduced (focus function) for simple inline functions taking a single argument. An example is fn { ../@code }  [Issue 503 PR 521 30 May 2023]

InlineFunctionExpr::=MethodAnnotation* ("function" | "fn") FunctionSignature? FunctionBody
MethodAnnotation::="%method"
FunctionSignature::="(" ParamList ")" TypeDeclaration?
ParamList::=(VarNameAndType ** ",")
VarNameAndType::="$" EQNameTypeDeclaration?
EQName::=QName | URIQualifiedName
TypeDeclaration::="as" SequenceType
SequenceType::=("empty-sequence" "(" ")")
| (ItemTypeOccurrenceIndicator?)
FunctionBody::=EnclosedExpr
EnclosedExpr::="{" Expr? "}"

[Definition: An inline function expression is an instance of the construct InlineFunctionExpr. When evaluated, an inline function expression creates an anonymous function whose properties are defined directly in the inline function expression.] An inline function expression defines the names and types of the parameters to the function, the type of the result, and the body of the function.

An inline function expression whose FunctionSignature is omitted is known as a focus function. Focus functions are described in 4.5.6.1 Focus Functions.

[Definition: An anonymous function is a function item with no name. Anonymous functions may be created, for example, by evaluating an inline function expression or by partial function application.]

The keywords function and fn are synonymous.

The syntax allows the names and types of the function argument to be declared, along with the type of the result:

function($x as xs:integer, $y as xs:integer) as xs:integer { $x + $y }

The types can be omitted, and the keyword can be abbreviated:

fn($x, $y) { $x + $y }

A zero-arity function can be written as, for example, fn() { current-date() }.

If a function parameter is declared using a name but no type, its default type is item()*. If the result type is omitted, its default result type is item()*.

The parameters of an inline function expression are considered to be variables whose scope is the function body. It is a static error [err:XQST0039] for an inline function expression to have more than one parameter with the same name.

The static context for the function body is inherited from the location of the inline function expression.

The variables in scope for the function body include all variables representing the function parameters, as well as all variables that are in scope for the inline function expression.

Note:

Function parameter names can mask variables that would otherwise be in scope for the function body.

The result of an inline function expression is a single function item with the following properties (as defined in [XDM 4.0] section Section 8.1 Function ItemsDM):

  • name: Absent.

  • identity: A new function identity distinct from the identity of any other function item.

  • signature: A FunctionType constructed from the SequenceTypes in the InlineFunctionExpr. An implementation which can determine a more specific signature (for example, through use of type analysis of the function’s body) is permitted to do so.

  • annotations:

  • body: The FunctionBody of the InlineFunctionExpr.

  • captured context: the static context is the static context of the inline function expression. The dynamic context has an absent focus, and a set of variable bindings comprising the variable values component of the dynamic context of the InlineFunctionExpr.

The following are examples of some inline function expressions:

  • This example creates a function that takes no arguments and returns a sequence of the first 6 primes:

    function() as xs:integer+ { 2, 3, 5, 7, 11, 13 }
  • This example creates a function that takes two xs:double arguments and returns their product:

    fn($a as xs:double, $b as xs:double) as xs:double { $a * $b }
  • This example creates and invokes a function that captures the value of a local variable in its scope:

    let $incrementors := (
      for $x in 1 to 10
      return function($y) as xs:integer { $x + $y }
    )
    return $incrementors[2](4)

    The result of this expression is 6

4.6 Path Expressions

Changes in 4.0  

  1. Path expressions are extended to handle JNodes (found in trees of maps and arrays) as well as XNodes (found in trees representing parsed XML).   [Issue 2054 ]

PathExpr::=AbsolutePathExpr
| RelativePathExpr
/* xgc: leading-lone-slash */
AbsolutePathExpr::=("/" RelativePathExpr?) | ("//" RelativePathExpr)
RelativePathExpr::=StepExpr (("/" | "//") StepExpr)*

[Definition: A path expression is either an absolute path expression or a relative path expression ]

[Definition: An absolute path expression is an instance of the production AbsolutePathExpr: it consists of either (a) the operator / followed by zero or more operands separated by / or // operators, or (b) the operator // followed by one or more operands separated by / or // operators.]

[Definition: A relative path expression is a non-trivial instance of the production RelativePathExpr: it consists of two or more operand expressions separated by / or // operators.]

[Definition: The operands of a path expression are conventionally referred to as steps.]

Note:

The term step must not be confused with axis step. A step can be any kind of expression, often but not necessarily an axis step, while an axis step can be used in any expression context, not necessarily as a step in a path expression.

A path expression is typically used to locate GNodes within GTrees.

Note:

Note the terminology:

The following definitions are copied from the data model specification, for convenience:

  • [Definition: A tree that is rooted at a parentless JNode is referred to as a JTree.]

  • [Definition: A tree that is rooted at a parentless XNode is referred to as an XTree.]

  • [Definition: The term generic node or GNode is a collective term for XNodes (more commonly called simply nodes) representing the parts of an XML document, and JNodes, often used to represent the parts of a JSON document.]

  • [Definition: A JNode is a kind of item used to represent a value within the context of a tree of maps and arrays. A root JNode represents a map or array; a non-root JNode represents a member of an array or an entry in a map.]

[Definition: The term GTree means JTree or XTree.]

Absolute path expressions (those starting with an initial / or //), start their selection from the root GNode of a GTree; relative path expressions (those without a leading / or //) start from the context value.

4.6.4 Axis Steps

AxisStep::=(AbbreviatedStep | FullStep) Predicate*
AbbreviatedStep::=".." | ("@" NodeTest) | SimpleNodeTest
FullStep::=AxisNodeTest
Axis::=("ancestor" | "ancestor-or-self" | "attribute" | "child" | "descendant" | "descendant-or-self" | "following" | "following-or-self" | "following-sibling" | "following-sibling-or-self" | "namespace" | "parent" | "preceding" | "preceding-or-self" | "preceding-sibling" | "preceding-sibling-or-self" | "self") "::"
NodeTest::=UnionNodeTest | SimpleNodeTest
Predicate::="[" Expr "]"
Expr::=(ExprSingle ++ ",")

[Definition: An axis step is an instance of the production AxisStep: it is an expression that returns a sequence of GNodes that are reachable from a starting GNode via a specified axis. An axis step has three parts: an axis, which defines the direction of movement for the step, a node test, which selects GNodes based on their properties, and zero or more predicates which are used to filter the results.]

Note:

An axis step is an expression in its own right. While axis steps are often used as the operands of path expressions, they can also appear in other contexts (without a / or // operator); equally, the operands of a path expression can be any expression, not restricted to an axis step.

If the context value for an axis step includes a map or array, this is implicitly converted to a JNode as if by applying the fn:jnode function. If, after this conversion, the sequence contains a value that is not a GNode, a type error is raised [err:XPTY0020]. The result of evaluating the axis step is a sequence of zero or more GNodes.

The axis stepS is equivalent to ./S. Thus, if the context value is a sequence containing multiple GNodes, the semantics of a axis step are equivalent to a path expression in which the step is always applied to a single GNode. The following description therefore explains the semantics for the case where the context value is a single GNode, called the origin.

Note:

The equivalence of a axis stepS to the path expression./S means that the resulting GNode sequence is returned in document order.

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

The unabbreviated syntax for an axis step consists of the axis name and node test separated by a double colon. The result of the step consists of the GNodes reachable from the origin via the specified axis that match the node test. For example, the step child::para selects the para element children of the origin XNode: child is the name of the axis, and para is the name of the element nodes to be selected on this axis. The available axes are described in 4.6.4.1 Axes. The available node tests are described in 4.6.4.2 Node Tests. Examples of steps are provided in 4.6.6 Unabbreviated Syntax and 4.6.7 Abbreviated Syntax.

4.6.4.1 Axes

Changes in 4.0  

  1. Four new axes have been defined: preceding-or-self, preceding-sibling-or-self, following-or-self, and following-sibling-or-self.   [Issue 1519 PR 1532 29 October 2024]

Axis::=("ancestor" | "ancestor-or-self" | "attribute" | "child" | "descendant" | "descendant-or-self" | "following" | "following-or-self" | "following-sibling" | "following-sibling-or-self" | "namespace" | "parent" | "preceding" | "preceding-or-self" | "preceding-sibling" | "preceding-sibling-or-self" | "self") "::"

An axis is essentially a function that takes a GNode (the origin) as input, and delivers a sequence of GNodes (always from within the same GTree as the origin) as its result.

XPath defines a 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 origin.

    If the origin is an XNode, these are the XNodes returned by the [XDM 4.0] section Section 7.5.3 children AccessorDM accessor.

    Note:

    In an XTree, only document nodes and element nodes have children. If the origin is any other kind of XNode, or if the origin is an empty document or element node, then the child axis returns an empty sequence. The children of a document node or element node may be element, processing instruction, comment, or text nodes. Attribute, namespace, and document nodes can never appear as children.

    If the origin is a JNode, these are the JNodes returned by the [TITLE OF DM40 SPEC, TITLE OF dm-jnode-children SECTION]DM40 accessor.

  • The descendant axis is defined as the transitive closure of the child axis; it contains the descendants of the origin (the children, the children of the children, and so on).

    More formally, $node/descendant::gnode() delivers the result of fn:transitive-closure($node, fn { child::gnode() }).

  • The descendant-or-self axis contains the origin and the descendants of the origin.

    More formally, $node/descendant-or-self::gnode() delivers the result of $node/(. | descendant::gnode()).

  • The parent axis returns the parent of the origin.

    If the origin is an XNode, this is the result of the [XDM 4.0] section Section 7.5.11 parent AccessorDM accessor.

    If the origin is a JNode, this is the value of the ·parent· property of the origin.

    If the GNode has no parent, the axis returns an empty sequence.

    Note:

    An attribute node may have an element node as its parent, even though the attribute node is not a child of the element node.

  • The ancestor axis is defined as the transitive closure of the parent axis; it contains the ancestors of the origin (the parent, the parent of the parent, and so on).

    More formally, $node/ancestor::gnode() delivers the result of fn:transitive-closure($node, fn { parent::gnode() }).

    Note:

    The ancestor axis includes the root GNode of the GTree in which the origin is found, unless the origin is itself the root GNode.

  • The ancestor-or-self axis contains the origin and the ancestors of the origin; thus, the ancestor-or-self axis will always include the root.

    More formally, $node/ancestor-or-self::gnode() delivers the result of $node/(. | ancestor::gnode()).

  • The following-sibling axis returns the origin’s following siblings, that is, those children of the origin’s parent that occur after the origin in document order. If the origin is an attribute or namespace node, the following-sibling axis is empty.

    More formally, $node/following-sibling::gnode() delivers the result of fn:siblings($node)[. >> $node]).

  • The following-sibling-or-self axis contains the origin, together with the contents of the following-sibling axis.

    More formally, $node/following-sibling-or-self::gnode() delivers the result of fn:siblings($node)[not(. << $node)]

  • The preceding-sibling axis returns the origin’s preceding siblings, that is, those children of the origin’s parent that occur before the context node in document order. If the origin is an attribute or namespace node, the preceding-sibling axis is empty.

    More formally, $node/preceding-sibling::gnode() delivers the result of fn:siblings($node)[. << $node].

  • The preceding-sibling-or-self axis contains the origin, together with the contents of the preceding-sibling axis.

    More formally, $node/preceding-sibling-or-self::gnode() delivers the result of fn:siblings($node)[not(. >> $node).

  • The following axis contains all descendants of the root of the GTree in which the origin is found, are not descendants of the origin, and occur after the origin in document order.

    More formally, $node/following::gnode() delivers the result of $node/ancestor-or-self::gnode()/following-sibling::gnode()/descendant-or-self::gnode()

  • The following-or-self axis contains the origin, together with the contents of the following axis.

    More formally, $node/following-or-self::gnode() delivers the result of $node/(. | following::gnode()).

  • The preceding axis returns all descendants of the root of the GTree in which the origin is found, are not ancestors of the origin, and occur before the origin in document order.

    More formally, $node/preceding::gnode() delivers the result of $node/ancestor-or-self::gnode()/preceding-sibling::gnode()/descendant-or-self::gnode().

  • The preceding-or-self axis returns the origin, together with the contents of the preceding axis.

    More formally, $node/preceding-or-self::gnode() delivers the result of $node/(. | preceding::gnode()).

  • The attribute axis is defined only for XNodes. It returns the attributes of the origin, which are the nodes returned by the [XDM 4.0] section Section 7.5.1 attributes AccessorDM; the axis will be empty unless the context node is an element.

    If the attribute axis is applied to a JNode, a type error [err:XPTY0004] is raised.

  • The self axis contains just the origin itself.

    The self axis is primarily useful when testing whether the origin satisfies particular conditions, for example if ($x[self::chapter]).

    More formally, $node/self::gnode() delivers the result of $node.

  • The namespace axis is defined only for XNodes. It returns the namespace nodes of the origin, which are the nodes returned by the [XDM 4.0] section Section 7.5.7 namespace-nodes AccessorDM; this axis is empty unless the origin is an element node. The namespace axis is deprecated as of XPath 2.0. If XPath 1.0 compatibility mode is true, the namespace axis must be supported. If XPath 1.0 compatibility mode is false, then support for the namespace axis is implementation-defined. An implementation that does not support the namespace axis when XPath 1.0 compatibility mode is false must raise a static error [err:XPST0010] if it is used. Applications needing information about the in-scope namespaces of an element should use the function fn:in-scope-namespaces.

    If the namespace axis is applied to a JNode, a type error [err:XPTY0004] is raised.

Axes can be categorized as forward axes and reverse axes. An axis that only ever contains the origin 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.

The parent, ancestor, ancestor-or-self, preceding, preceding-or-self, preceding-sibling, and preceding-sibling-or-self axes are reverse axes; all other axes are forward axes.

The ancestor, descendant, following, preceding and self axes partition a GTree (ignoring attribute and namespace nodes): they do not overlap and together they contain all the GNodes in the GTree.

[Definition: 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.

4.7 Sequence Expressions

XPath 4.0 supports operators to construct, filter, and combine sequences of items. Sequences are never nested—for example, combining the values 1, (2, 3), and ( ) into a single sequence results in the sequence (1, 2, 3).

4.7.2 Range Expressions

RangeExpr::=AdditiveExpr ("to" AdditiveExpr)?
AdditiveExpr::=MultiplicativeExpr (("+" | "-") MultiplicativeExpr)*

[Definition: A range expression is a non-trivial instance of the production RangeExpr. A range expression is used to construct a sequence of integers.] Each of the operands is converted as though it was an argument of a function with the expected parameter type xs:integer?. If either operand is an empty sequence, or if the integer derived from the first operand is greater than the integer derived from the second operand, the result of the range expression is an empty sequence. If the two operands convert to the same integer, the result of the range expression is that integer. Otherwise, the result is a sequence containing the two integer operands and every integer between the two operands, in increasing order.

The following examples illustrate the semantics:

  • 1 to 4 returns the sequence 1, 2, 3, 4

  • 10 to 10 returns the singleton sequence 10

  • 10 to 1 returns the empty sequence

  • -13 to -10 returns the sequence -13, -12, -11, -10

More formally, a range expression is evaluated as follows:

  1. Each of the operands of the to operator is converted as though it was an argument of a function with the expected parameter type xs:integer?.

  2. If either operand is an empty sequence, or if the integer derived from the first operand is greater than the integer derived from the second operand, the result of the range expression is an empty sequence.

  3. If the two operands convert to the same integer, the result of the range expression is that integer.

  4. Otherwise, the result is a sequence containing the two integer operands and every integer between the two operands, in increasing order.

The following examples illustrate the use of range expressions.

This example uses a range expression as one operand in constructing a sequence. It evaluates to the sequence 10, 1, 2, 3, 4.

(10, 1 to 4)

This example selects the first four items from an input sequence:

$input[1 to 4]

This example returns the sequence (0, 0.1, 0.2, 0.3, 0.5):

$x = (1 to 5) ! . * 0.1

This example constructs a sequence of length one containing the single integer 10.

10 to 10

The result of this example is a sequence of length zero.

15 to 10

This example uses the fn:reverse function to construct a sequence of six integers in decreasing order. It evaluates to the sequence 15, 14, 13, 12, 11, 10.

reverse(10 to 15)

Note:

To construct a sequence of integers based on steps other than 1, use the fn:slice function, as defined in Section 14.1 General functions and operators on sequences FO31.

4.7.3 Combining GNode Sequences

UnionExpr::=IntersectExceptExpr (("union" | "|") IntersectExceptExpr)*
IntersectExceptExpr::=InstanceofExpr (("intersect" | "except") InstanceofExpr)*
InstanceofExpr::=TreatExpr ("instance" "of" SequenceType)?

XPath 4.0 provides the following operators for combining sequences of GNodes:

  • The union and | operators are equivalent. They take two node sequences as operands and return a sequence containing all the GNodes that occur in either of the operands.

  • The intersect operator takes two GNodes sequences as operands and returns a sequence containing all the GNodes that occur in both operands.

  • The except operator takes two node sequences as operands and returns a sequence containing all the GNodes that occur in the first operand but not in the second operand.

All these operators eliminate duplicate GNodes from their result sequences based on GNodes identity. The resulting sequence is returned in document order.

If an operand of union, intersect, or except contains an item that is not a GNode, a type error is raised [err:XPTY0004].

If an IntersectExceptExpr contains more than two InstanceofExpr operands, they are evaluated from left to right. With a UnionExpr, it makes no difference how operands are grouped, the results are the same.

Here are some examples of expressions that combine sequences. Assume the existence of three element nodes that we will refer to by symbolic names A, B, and C. Assume that the variables $seq1, $seq2 and $seq3 are bound to the following sequences of these nodes:

  • $seq1 is bound to (A, B)

  • $seq2 is bound to (A, B)

  • $seq3 is bound to (B, C)

Then:

  • $seq1 union $seq2 evaluates to the sequence (A, B).

  • $seq2 union $seq3 evaluates to the sequence (A, B, C).

  • $seq1 intersect $seq2 evaluates to the sequence (A, B).

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

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

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

The following example demonstrates the use of the except operator with JNodes:

let $m := jtree($map)
for $e in $m/child::* except $m/child::xx 
return ...

Note:

Because the jnode creates a new JTree root, calling it twice potentially creates two different trees, in which the JNodes have different identity. The expression $map/child::* except $map/child::xx might therefore have the wrong effect, because JNodes in two different trees are being compared. For more details see the specification of the jnode function.

In addition to the sequence operators described here, see [Functions and Operators 4.0] section Section 14 Processing sequencesFO for functions defined on sequences.

4.8 Arithmetic Expressions

Changes in 4.0  

  1. The symbols × and ÷ can be used for multiplication and division.

XPath 4.0 provides binary arithmetic operators for addition, subtraction, multiplication, division, and modulus:

AdditiveExpr::=MultiplicativeExpr (("+" | "-") MultiplicativeExpr)*
MultiplicativeExpr::=UnionExpr (("*" | "×" | "div" | "÷" | "idiv" | "mod") UnionExpr)*
UnionExpr::=IntersectExceptExpr (("union" | "|") IntersectExceptExpr)*

In addition, unary operators are provided for addition and subtraction:

UnaryExpr::=("-" | "+")* ValueExpr
ValueExpr::=SimpleMapExpr
SimpleMapExpr::=PathExpr ("!" PathExpr)*

A subtraction operator must be preceded by whitespace if it could otherwise be interpreted as part of the previous token. For example, a-b will be interpreted as a name, but a - b and a -b will be interpreted as arithmetic expressions. (See A.3.4 Whitespace Rules for further details on whitespace handling.)

The arithmetic operator symbols * and U+00D7 (MULTIPLICATION SIGN, ×) are interchangeable, and denote multiplication.

The arithmetic operator symbols div and U+00F7 (DIVISION SIGN, ÷) are interchangeable, and denote division.

If an AdditiveExpr contains more than two MultiplicativeExprs, they are grouped from left to right. So, for instance,

A - B + C - D

is equivalent to

((A - B) + C) - D

Similarly, the operands of a MultiplicativeExpr are grouped from left to right.

The first step in evaluating an arithmetic expression is to evaluate its operand (for a unary operator) or operands (for a binary operator). The order in which the operands are evaluated is implementation-dependent.

If XPath 1.0 compatibility mode is true, each operand is evaluated by applying the following steps, in order:

  1. Atomization is applied to the operand. The result of this operation is called the atomized operand.

  2. If the atomized operand is an empty sequence, the result of the arithmetic expression is the xs:double value NaN, and the implementation need not evaluate the other operand or apply the operator. However, an implementation may choose to evaluate the other operand in order to determine whether it raises an error.

  3. If the atomized operand is a sequence of length greater than one, any items after the first item in the sequence are discarded.

  4. If the atomized operand is now an instance of type xs:boolean, xs:string, xs:decimal (including xs:integer), xs:float, or xs:untypedAtomic, then it is converted to the type xs:double by applying the fn:number function. (Note that fn:number returns the value NaN if its operand cannot be converted to a number.)

If XPath 1.0 compatibility mode is false, each operand is evaluated by applying the following steps, in order:

  1. Atomization is applied to the operand. The result of this operation is called the atomized operand.

  2. If the atomized operand is an empty sequence, the result of the arithmetic expression is an empty sequence, and the implementation need not evaluate the other operand or apply the operator. However, an implementation may choose to evaluate the other operand in order to determine whether it raises an error.

  3. If the atomized operand is a sequence of length greater than one, a type error is raised [err:XPTY0004].

  4. If the atomized operand is of type xs:untypedAtomic, it is cast to xs:double. If the cast fails, a dynamic error is raised. [err:FORG0001]FO40

If, after this process, both operands of a binary arithmetic operator are instances of xs:numeric but have different primitive types, they are coerced to a common type by applying the following rules:

  1. If either of the items is of type xs:double, then both the values are cast to type xs:double.

  2. Otherwise, if either of the items is of type xs:float, then both the values are cast to type xs:float.

  3. Otherwise, no casting takes place: the values remain as xs:decimal.

After this preparation, the arithmetic expression is evaluated by applying the appropriate function listed in the table below. The definitions of these functions are found in [XQuery and XPath Functions and Operators 4.0].

Unary Arithmetic Operators
ExpressionType of AFunctionResult type
+ Axs:numericop:numeric-unary-plus(A)xs:numeric
- Axs:numericop:numeric-unary-minus(A)xs:numeric
Binary Arithmetic Operators
ExpressionType of AType of BFunctionResult type
A + Bxs:numericxs:numericop:numeric-add(A, B)xs:numeric
A + Bxs:datexs:yearMonthDurationop:add-yearMonthDuration-to-date(A, B)xs:date
A + Bxs:yearMonthDurationxs:dateop:add-yearMonthDuration-to-date(B, A)xs:date
A + Bxs:datexs:dayTimeDurationop:add-dayTimeDuration-to-date(A, B)xs:date
A + Bxs:dayTimeDurationxs:dateop:add-dayTimeDuration-to-date(B, A)xs:date
A + Bxs:timexs:dayTimeDurationop:add-dayTimeDuration-to-time(A, B)xs:time
A + Bxs:dayTimeDurationxs:timeop:add-dayTimeDuration-to-time(B, A)xs:time
A + Bxs:dateTimexs:yearMonthDurationop:add-yearMonthDuration-to-dateTime(A, B)xs:dateTime
A + Bxs:yearMonthDurationxs:dateTimeop:add-yearMonthDuration-to-dateTime(B, A)xs:dateTime
A + Bxs:dateTimexs:dayTimeDurationop:add-dayTimeDuration-to-dateTime(A, B)xs:dateTime
A + Bxs:dayTimeDurationxs:dateTimeop:add-dayTimeDuration-to-dateTime(B, A)xs:dateTime
A + Bxs:yearMonthDurationxs:yearMonthDurationop:add-yearMonthDurations(A, B)xs:yearMonthDuration
A + Bxs:dayTimeDurationxs:dayTimeDurationop:add-dayTimeDurations(A, B)xs:dayTimeDuration
A - Bxs:numericxs:numericop:numeric-subtract(A, B)xs:numeric
A - Bxs:datexs:dateop:subtract-dates(A, B)xs:dayTimeDuration
A - Bxs:datexs:yearMonthDurationop:subtract-yearMonthDuration-from-date(A, B)xs:date
A - Bxs:datexs:dayTimeDurationop:subtract-dayTimeDuration-from-date(A, B)xs:date
A - Bxs:timexs:timeop:subtract-times(A, B)xs:dayTimeDuration
A - Bxs:timexs:dayTimeDurationop:subtract-dayTimeDuration-from-time(A, B)xs:time
A - Bxs:dateTimexs:dateTimeop:subtract-dateTimes(A, B)xs:dayTimeDuration
A - Bxs:dateTimexs:yearMonthDurationop:subtract-yearMonthDuration-from-dateTime(A, B)xs:dateTime
A - Bxs:dateTimexs:dayTimeDurationop:subtract-dayTimeDuration-from-dateTime(A, B)xs:dateTime
A - Bxs:yearMonthDurationxs:yearMonthDurationop:subtract-yearMonthDurations(A, B)xs:yearMonthDuration
A - Bxs:dayTimeDurationxs:dayTimeDurationop:subtract-dayTimeDurations(A, B)xs:dayTimeDuration
A * Bxs:numericxs:numericop:numeric-multiply(A, B)xs:numeric
A * Bxs:yearMonthDurationxs:numericop:multiply-yearMonthDuration(A, B)xs:yearMonthDuration
A * Bxs:numericxs:yearMonthDurationop:multiply-yearMonthDuration(B, A)xs:yearMonthDuration
A * Bxs:dayTimeDurationxs:numericop:multiply-dayTimeDuration(A, B)xs:dayTimeDuration
A * Bxs:numericxs:dayTimeDurationop:multiply-dayTimeDuration(B, A)xs:dayTimeDuration
A idiv Bxs:numericxs:numericop:numeric-integer-divide(A, B)xs:integer
A div Bxs:numericxs:numericop:numeric-divide(A, B)numeric; but xs:decimal if both operands are xs:integer
A div Bxs:yearMonthDurationxs:numericop:divide-yearMonthDuration(A, B)xs:yearMonthDuration
A div Bxs:dayTimeDurationxs:numericop:divide-dayTimeDuration(A, B)xs:dayTimeDuration
A div Bxs:yearMonthDurationxs:yearMonthDurationop:divide-yearMonthDuration-by-yearMonthDuration(A, B)xs:decimal
A div Bxs:dayTimeDurationxs:dayTimeDurationop:divide-dayTimeDuration-by-dayTimeDuration(A, B)xs:decimal
A mod Bxs:numericxs:numericop:numeric-mod(A, B)xs:numeric

Note:

The operator symbol × is a synonym of *, while ÷ is a synonym of div.

If there is no entry in the table for the combination of operator and operands, then a type error is raised [err:XPTY0004].

Errors may also occur during coercion of the operands, or during evaluation of the identified function (for example, an error might result from dividing by zero).

Note:

XPath 4.0 provides three division operators:

Here are some examples of arithmetic expressions:

  • The first expression below returns the xs:decimal value -1.5, and the second expression returns the xs:integer value -1:

    -3 div 2
    -3 idiv 2
  • Subtraction of two date values results in a value of type xs:dayTimeDuration:

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

    $unit-price - $unit-discount
  • Unary operators have higher precedence than binary operators (other than !, /, and []), subject of course to the use of parentheses. Therefore, the following two examples have different meanings:

    -$bellcost + $whistlecost
    -($bellcost + $whistlecost)

Note:

Multiple consecutive unary arithmetic operators are permitted (though not useful).

Note:

Negation is not the same as subtraction from zero: if $x is positive zero, then -$x returns negative zero, wheras 0 - $x returns positive zero.

4.10 Comparison Expressions

Comparison expressions allow two values to be compared. XPath 4.0 provides three kinds of comparison expressions, called value comparisons, general comparisons, and GNode comparisons.

ComparisonExpr::=OtherwiseExpr ((ValueComp | GeneralComp | NodeComp) OtherwiseExpr)?
OtherwiseExpr::=StringConcatExpr ("otherwise" StringConcatExpr)*
ValueComp::="eq" | "ne" | "lt" | "le" | "gt" | "ge"
GeneralComp::="=" | "!=" | "<" | "<=" | ">" | ">="
NodeComp::="is" | "is-not" | NodePrecedes | NodeFollows
NodePrecedes::="<<" | "precedes"
NodeFollows::=">>" | "follows"

Note:

When an XPath expression is written within an XML document, the XML escaping rules for special characters must be followed; thus < must be written as &lt;.

For a summary of the differences between different ways of comparing atomic items in XPath 4.0, see G Atomic Comparisons: An Overview.

4.10.1 Value Comparisons

Changes in 4.0  

  1. The rules for value comparisons when comparing values of different types (for example, decimal and double) have changed to be transitive. A decimal value is no longer converted to double, instead the double is converted to a decimal without loss of precision. This may affect compatibility in edge cases involving comparison of values that are numerically very close.

The value comparison operators are eq, ne, lt, le, gt, and ge. Value comparisons are used for comparing single values.

The first step in evaluating a value comparison is to evaluate its operands. The order in which the operands are evaluated is implementation-dependent. Each operand is evaluated by applying the following steps, in order:

  1. Atomization is applied to each operand. The result of this operation is called the atomized operand.

  2. If an atomized operand is an empty sequence, the result of the value comparison is an empty sequence, and the implementation need not evaluate the other operand or apply the operator. However, an implementation may choose to evaluate the other operand in order to determine whether it raises an error.

  3. If an atomized operand is a sequence of length greater than one, a type error is raised [err:XPTY0004].

  4. If an atomized operand is of type xs:untypedAtomic, it is cast to xs:string.

    Note:

    The purpose of this rule is to make value comparisons transitive. Users should be aware that the general comparison operators have a different rule for casting of xs:untypedAtomic operands. Users should also be aware that transitivity of value comparisons may be compromised by loss of precision during type conversion (for example, two xs:integer values that differ slightly may both be considered equal to the same xs:float value because xs:float has less precision than xs:integer).

  5. If the two operands are instances of different primitive types (meaning the 19 primitive types defined in Section 3.2 Primitive datatypesXS2), then:

    1. If each operand is an instance of one of the types xs:string or xs:anyURI, then both operands are cast to type xs:string.

    2. If each operand is an instance of one of the types xs:decimal or xs:float, then both operands are cast to type xs:float.

    3. If each operand is an instance of one of the types xs:decimal, xs:float, or xs:double, then both operands are cast to type xs:double.

    4. Otherwise, a type error is raised [err:XPTY0004].

      Note:

      The primitive type of an xs:integer value for this purpose is xs:decimal.

  6. Expressions using operators other than eq and lt are rewritten as follows:

    A ne B becomes not(A eq B)
    A le B becomes A lt B or A eq B
    A gt B becomes B lt A
    A ge B becomes B lt A or B eq A

  7. Finally, if the types of the operands are a valid combination for the given operator, the operator is applied to the operands by applying the appropriate function from the table below.

Value Comparison Operators
ExpressionType(A)Type(B)FunctionResult type
A eq Bxs:numericxs:numericop:numeric-equal(A, B)xs:boolean
A eq Bxs:booleanxs:booleanop:boolean-equal(A, B)xs:boolean
A eq Bxs:stringxs:stringop:numeric-equal(fn:compare(A, B), 0)xs:boolean
A eq Bxs:datexs:dateop:date-equal(A, B)xs:boolean
A eq Bxs:timexs:timeop:time-equal(A, B)xs:boolean
A eq Bxs:dateTimexs:dateTimeop:dateTime-equal(A, B)xs:boolean
A eq Bxs:durationxs:durationop:duration-equal(A, B)xs:boolean
A eq Bxs:gYearxs:gYearop:gYear-equal(A, B)xs:boolean
A eq Bxs:gYearMonthxs:gYearMonthop:gYearMonth-equal(A, B)xs:boolean
A eq Bxs:gMonthxs:gMonthop:gMonth-equal(A, B)xs:boolean
A eq Bxs:gMonthDayxs:gMonthDayop:gMonthDay-equal(A, B)xs:boolean
A eq Bxs:gDayxs:gDayop:gDay-equal(A, B)xs:boolean
A eq B(xs:hexBinary | xs:base64Binary)(xs:hexBinary | xs:base64Binary)op:binary-equal(A, B)xs:boolean
A eq Bxs:QNamexs:QNameop:QName-equal(A, B)xs:boolean
A eq Bxs:NOTATIONxs:NOTATIONop:NOTATION-equal(A, B)xs:boolean
A lt Bxs:numericxs:numericop:numeric-less-than(A, B)xs:boolean
A lt Bxs:booleanxs:booleanop:boolean-less-than(A, B)xs:boolean
A lt Bxs:stringxs:stringop:numeric-less-than(fn:compare(A, B), 0)xs:boolean
A lt Bxs:datexs:dateop:date-less-than(A, B)xs:boolean
A lt Bxs:timexs:timeop:time-less-than(A, B)xs:boolean
A lt Bxs:dateTimexs:dateTimeop:dateTime-less-than(A, B)xs:boolean
A lt Bxs:yearMonthDurationxs:yearMonthDurationop:yearMonthDuration-less-than(A, B)xs:boolean
A lt Bxs:dayTimeDurationxs:dayTimeDurationop:dayTimeDuration-less-than(A, B)xs:boolean
A lt B(xs:hexBinary | xs:base64Binary)(xs:hexBinary | xs:base64Binary)op:binary-less-than(A, B)xs:boolean

The definitions of the operator functions are found in [XQuery and XPath Functions and Operators 4.0].

If the table contains no entry corresponding to the types of the operands, after evaluation, then a type error is raised [err:XPTY0004].

Here are some examples of value comparisons:

  • The following comparison atomizes the node(s) that are returned by the expression $book/author. The comparison is true only if the result of atomization is the value "Kennedy" as an instance of xs:string or xs:untypedAtomic. If the result of atomization is an empty sequence, the result of the comparison is an empty sequence. If the result of atomization is a sequence containing more than one value, a type error is raised [err:XPTY0004].

    $book1/author eq "Kennedy"
  • The following comparison is true because atomization converts an array to its member sequence:

    [ "Kennedy" ] eq "Kennedy"
  • The following path expression contains a predicate that selects products whose weight is greater than 100. For any product that does not have a weight subelement, the value of the predicate is the empty sequence, and the product is not selected. This example assumes that weight is a validated element with a numeric type.

    //product[weight gt 100]
  • The following comparison is true if my:hatsize and my:shoesize are both user-defined types that are derived by restriction from a primitive numeric type:

    my:hatsize(5) eq my:shoesize(5)
  • The following comparison is true. The eq operator compares two QNames by performing codepoint-comparisons of their namespace URIs and their local names, ignoring their namespace prefixes.

    QName("http://example.com/ns1", "this:color") eq
    QName("http://example.com/ns1", "that:color")

4.10.3 GNode Comparisons

Changes in 4.0  

  1. Operator is-not is introduced, as a complement to the operator is.   [  28 July 2025]

  2. Operators precedes and follows are introduced as synonyms for operators << and >>.   [  28 July 2025]

GNode comparisons are used to compare two GNodesDM (that is, XNodes or JNodesDM), by their identity or by their document order. The result of a GNode comparison is defined by the following rules:

  1. The operands of a GNode comparison are evaluated in implementation-dependent order.

  2. If either operand is an empty sequence, the result of the comparison is an empty sequence, and the implementation need not evaluate the other operand or apply the operator. However, an implementation may choose to evaluate the other operand in order to determine whether it raises an error.

  3. Each operand must be either a single GNode or an empty sequence; otherwise a type error is raised [err:XPTY0004].

  4. A comparison with the is operator is true if the values of two operands are the same GNode; otherwise it is false. See [XQuery and XPath Data Model (XDM) 4.0][XDM 4.0] for the definition of GNode identity.

  5. A comparison with the is-not operator is false if the values of two operands are the same GNode; otherwise it is true. See [XQuery and XPath Data Model (XDM) 4.0][XDM 4.0] for the definition of GNode identity.

  6. A comparison with the << or precedes operator returns true if the left operand GNode precedes the right operand GNode in document order; otherwise it returns false.

  7. A comparison with the >> or follows operator returns true if the left operand GNode follows the right operand GNode in document order; otherwise it returns false.

Here are some examples of GNode comparisons:

  • The following comparison is true only if the left and right sides each evaluate to exactly the same single node:

    /books/book[isbn = "1558604820"] is /books/book[call = "QA76.9 C3845"]
  • The following comparison is true only if the node identified by the left side occurs before the node identified by the right side in document order:

    /transactions/purchase[parcel = "28-451"] << /transactions/sale[parcel = "33-870"]
  • The following comparison is true only if the first integer among the members of an array precedes the first string. This expression compares two JNodes:

    let $A := ["Q", 3, "E", "R", "T", 5, "Y"]
    return $A ? child::~[xs:integer][1] precedes $A ? child::~[xs:string][1]

4.11 Logical Expressions

Changes in 4.0  

  1. The rules for “errors and optimization” have been tightened up to disallow many cases of optimizations that alter error behavior. In particular there are restrictions on reordering the operands of and and or, and of predicates in filter expressions, in a way that might allow the processor to raise dynamic errors that the author intended to prevent.   [Issues 71 2132 PR 230 15 November 2022]

[Definition: A logical expression is either an and expression or an or expression. If a logical expression does not raise an error, its value is always one of the boolean values true or false.]

OrExpr::=AndExpr ("or" AndExpr)*
AndExpr::=ComparisonExpr ("and" ComparisonExpr)*
ComparisonExpr::=OtherwiseExpr ((ValueComp | GeneralComp | NodeComp) OtherwiseExpr)?

[Definition: An and expression is a non-trivial instance of the production AndExpr.]

[Definition: An or expression is a non-trivial instance of the production OrExpr.]

In the absence of errors, an and expression returns true when both of its operands have an effective boolean value of true, while an or expression returns true when either or both of its operands have an effective boolean value of true.

The rules for error handling follow the principles defined in 2.4.5 Guarded Expressions. Specifically, an and expression returns false if the first operand has an effective boolean value of false, whether or not evaluation of the second operand raises an error; while an or expression returns true if the first operand has an effective boolean value of true, whether or not evaluation of the second operand raises an error.

Note:

This rule is consistent with the so-called “short-circuit” evaluation of logical operators defined in some procedural programming languages. However, unlike many such languages, the rule is concerned only with error behavior, and not with side-effects. A processor may evaluate the operands of a logical expression in any order, or in parallel, provided that the error semantics are respected. For example, an optimizer may choose to evaluate the second operand before evaluating the first, provided that any error in doing so is masked when the result can be determined from the value of the first operand.

The value of an and expression is determined by the effective boolean values (EBVs) of its operands, as shown in the following table:

AND:EBV2 = trueEBV2 = falseerror in EBV2
EBV1 = truetruefalseerror
EBV1 = falsefalsefalsefalse
error in EBV1errorerrorerror

The value of an or expression is determined by the effective boolean values (EBVs) of its operands, as shown in the following table:

OR:EBV2 = trueEBV2 = falseerror in EBV2
EBV1 = truetruetruetrue
EBV1 = falsetruefalseerror
error in EBV1errorerrorerror

Note:

XPath 1.0 defined the order of evaluation for and-expressions and or-expressions, thus ensuring “short-circuit” semantics. XPath 2.0 and XQuery 1.0 changed the rules to allow operands to be evaluated in either order, in the interests of optimization, while retaining “short-circuit” semantics when running XPath in 1.0 compatibility mode. The same rules were retained in the 3.0 and 3.1 versions of the specifications.

The disadvantage of that formulation was that it was not possible to use the first operand of a logical expression to guard against dynamic errors in the second; for example the expression $n instance of node() and exists($n/*) might legitimately fail in the case where $n is not a node.

The 4.0 specification therefore guarantees that this expression will not fail; but it does so without mandating an order of evaluation for the operands. Instead it mandates only that any error in evaluating the second operand (exists($n/*)) is masked if the first operand ($n instance of node()) is false.

Here are some examples of logical expressions:

  • The following expressions return true:

    1 eq 1 and 2 eq 2
    1 eq 1 or 2 eq 3
  • The following returns false: it is not allowed to raise an error.

    1 eq 2 and 3 idiv 0 = 1
  • The following expression returns true: it is not allowed to raise an error.

    1 eq 1 or 3 idiv 0 = 1
  • The following expression must raise a dynamic error:

    1 eq 1 and 3 idiv 0 = 1

In addition to and- and or-expressions, XPath 4.0 provides a function named fn:not that takes a general sequence as parameter and returns a boolean value. The fn:not function is defined in [XQuery and XPath Functions and Operators 4.0]. The fn:not function reduces its parameter to an effective boolean value. It then returns true if the effective boolean value of its parameter is false, and false if the effective boolean value of its parameter is true. If an error is encountered in finding the effective boolean value of its operand, fn:not raises the same error.

4.13 Maps and Arrays

Most modern programming languages have support for collections of key/value pairs, which may be called maps, dictionaries, associative arrays, hash tables, keyed lists, or objects (these are not the same thing as objects in object-oriented systems). In XPath 4.0, we call these maps. Most modern programming languages also support ordered lists of values, which may be called arrays, vectors, or sequences. In XPath 4.0, we have both sequences and arrays. Unlike sequences, an array is an item, and can appear as an item in a sequence.

Note:

The XPath 4.0 specification focuses on syntax provided for maps and arrays, especially constructors and lookup.

Some of the functionality typically needed for maps and arrays is provided by functions defined in [Functions and Operators 4.0] section Section 18 Processing mapsFO and [Functions and Operators 4.0] section Section 19 Processing arraysFO, including functions used to read JSON to create maps and arrays, serialize maps and arrays to JSON, combine maps to create a new map, remove map entries to create a new map, iterate over the keys of a map, convert an array to create a sequence, combine arrays to form a new array, and iterate over arrays in various ways.

4.13.1 Maps

Changes in 4.0  

  1. Ordered maps are introduced.  [Issue 1651 PR 1703 14 January 2025]

[Definition: A map is a function that associates a set of keys with values, resulting in a collection of key / value pairs.] [Definition: Each key / value pair in a map is called an entry.] [Definition: The value associated with a given key is called the associated value of the key.]

Maps and their properties are defined in the data model: see [XDM 4.0] section Section 8.2 Map ItemsDM. For an overview of the functions available for processing maps, see [Functions and Operators 4.0] section Section 18 Processing mapsFO.

Note:

Maps in XPath 4.0 are ordered. The effect of this property is explained in [XDM 4.0] section Section 8.2 Map ItemsDM. In an ordered map, the order of entries is predictable and depends on the order in which they were added to the map.

4.13.1.1 Map Constructors

Changes in 4.0  

  1. In map constructors, the keyword map is now optional, so map { 0: false(), 1: true() } can now be written { 0: false(), 1: true() }, provided it is used in a context where this creates no ambiguity.   [Issue 1070 PR 1071 26 March 2024]

  2. The order of key-value pairs in the map constructor is now retained in the constructed map.  [Issue 1651 PR 1703 14 January 2025]

  3. A general expression is allowed within a map constructor; this facilitates the creation of maps in which the presence or absence of particular keys is decided dynamically.  [Issue 2003 PR 2094 13 July 2025]

A map can be created using a MapConstructor.

Examples are:

{ "a": 1, "b": 2 }

which constructs a map with two entries, and

{ "a": 1, if ($condition) { map{ "b": 2 } } }

which constructs a map having either one or two entries depending on the value of $condition.

Both the keys and the values in a map constructor can be supplied as expressions rather than as constants.

MapConstructor::="map"? "{" (MapConstructorEntry ** ",") "}"
MapConstructorEntry::=ExprSingle (":" ExprSingle)?
ExprSingle::=ForExpr
| LetExpr
| QuantifiedExpr
| IfExpr
| OrExpr

Note:

The keyword map was required in earlier versions of the language; in XPath 4.0 it becomes optional. There may be cases where using the keyword improves readability.

In order to allow the map keyword to be omitted, an incompatible change has been made to XQuery computed element and attribute constructors: if the name of the constructed element or attribute is a language keyword, it must now be written using the QNameLiteral syntax, for example element #div {}.

Although the grammar allows a MapConstructor to appear within an EnclosedExpr (that is, between curly brackets), this may be confusing to readers, and using the map keyword in such cases may improve clarity. The keyword map is used in the second example above to avoid any confusion between the braces required for the then part of the conditional expression, and the braces required for the inner map constructor.

If the EnclosedExpr appears in a context such as a StringTemplate, the two adjacent left opening braces must at least be separated by whitespace.

When a MapConstructorEntry is written as two instances of ExprSingle separated by a colon, the first expression is evaluated and atomized to form a key, and the second expression is evaluated to form the corresponding value. The result is a single-entry mapDM which will be merged into the constructed map, as described below. A type error [err:XPTY0004] occurs if the result of the first expression (after atomization) is not a single atomic item. The result of the second expression is used as is.

When the MapConstructorEntry is written as a single instance of ExprSingle with no colon, it must evaluate to a sequence of zero or more map items ([err:XPTY0004]). However, the coercion rules also allow a JNode whose ·content· is a map (or a sequence of maps) to be supplied. These map items will be merged into the constructed map, as described below.

Each contained MapConstructorEntry thus delivers zero or more maps, and the result of the map constructor is a new map obtained by merging these component maps, in order, as if by the map:merge function.

[Definition: Two atomic items K1 and K2 have the same key value if fn:atomic-equal(K1, K2) returns true, as specified in [Functions and Operators 4.0] section Section 14.2.1 fn:atomic-equalFO ] If two or more entries have the same key value then a dynamic error is raised [err:XQDY0137]. The error may be raised statically if two or more entries can be determined statically to have the same key value.

The entry orderDM of the entries in the constructed map retains the order of the MapConstructorEntry entries in the input.

Example: Constructing a fixed map

The following expression constructs a map with seven entries:

{
  "Su" : "Sunday",
  "Mo" : "Monday",
  "Tu" : "Tuesday",
  "We" : "Wednesday",
  "Th" : "Thursday",
  "Fr" : "Friday",
  "Sa" : "Saturday"
}

 

Example: Constructing a map with conditional entries

The following expression constructs a map with either five or seven entries, depending on a supplied condition:

{
  "Mo" : "Monday",
  "Tu" : "Tuesday",
  "We" : "Wednesday",
  "Th" : "Thursday",
  "Fr" : "Friday",
  if ($include-weekends) {
    { "Sa" : "Saturday",
      "Su" : "Sunday"
    }
  }
}

This could also be written:

{
  "Mo" : "Monday",
  "Tu" : "Tuesday",
  "We" : "Wednesday",
  "Th" : "Thursday",
  "Fr" : "Friday",
  { "Sa" : "Saturday",
    "Su" : "Sunday"
  } [$include-weekends]
}

 

Example: Constructing a map to index nodes

The following expression (which uses two nested map constructors) constructs a map that indexes employees by the value of their @id attribute:

{ //employee ! {@id : .} }

 

Example: Constructing nested maps

Maps can nest, and can contain any XDM value. Here is an example of a nested map with values that can be string values, numeric values, or arrays:

{
  "book": {
    "title": "Data on the Web",
    "year": 2000,
    "author": [
      {
        "last": "Abiteboul",
        "first": "Serge"
      },
      {
        "last": "Buneman",
        "first": "Peter"
      },
      {
        "last": "Suciu",
        "first": "Dan"
      }
    ],
    "publisher": "Morgan Kaufmann Publishers",
    "price": 39.95
  }
}

Note:

The syntax deliberately mimics JSON, but there are a few differences. JSON constructs that are not accepted in XPath 4.0 map constructors include the keywords true, false, and null, and backslash-escaped characters such as "\n" in string literals. In an XPath 4.0 map constructor, of course, any literal value can be replaced with an expression.

Note:

In some circumstances, it is necessary to include whitespace before or after the colon of a MapConstructorEntry to ensure that it is parsed as intended.

For instance, consider the expression {a:b}. Although it matches the EBNF for MapConstructor, the “longest terminal” rule (see A.3 Lexical structure) requires that a:b be parsed as a QName, which is likely to result in an error indicating that the prefix a has not been declared. Changing the expression to {a :b} or {a: b} will prevent this, resulting in the intended parse.

Similarly, consider these three expressions:

{a:b:c}
{a:*:c}
{*:b:c}

In each case, the expression matches the EBNF in two different ways, but the “longest possible match” rule forces the parse in which the first subexpression is a:b, a:*, or *:b (respectively) and the second subexpression is c. To achieve the alternative parse (in which the first expression is merely a or *), insert whitespace before and/or after the first colon.

See A.3 Lexical structure.

Note:

There are also several functions that can be used to construct maps with a variable number of entries:

  • map:build takes any sequence as input, and for each item in the sequence, it computes a key and a value, by calling user-supplied functions.

  • map:merge takes a sequence of maps (often but not necessarily single-entry mapDM) and merges them into a single map.

Either of these functions can be used to build an index of employee elements using the value of the @id attribute as a key:

  • map:build(//employee, fn { @id })

  • map:merge(//employee ! { @id, . })

Both functions also provide control over:

  • The way in which duplicate keys are handled, and

  • The ordering of entries in the resulting map.

4.13.1.2 Maps as Functions

Maps are function items, and a dynamic function call can be used to look up the value associated with a key in a map. If $map is a map and $key is a key, then $map($key) is equivalent to map:get($map, $key). The semantics of such a function call are formally defined in [Functions and Operators 4.0] section Section 18.4.9 map:getFO.

Examples:

Note:

XPath 4.0 also provides an alternate syntax for map and array lookup that is more terse, supports wildcards, and allows lookup to iterate over a sequence of maps or arrays. See 4.13.3 Lookup Expressions for details.

Map lookups can be chained.

Examples: (These examples assume that $b is bound to the books map from the previous section)

  • The expression $b("book")("title") returns the string Data on the Web.

  • The expression $b("book")("author") returns the array of authors.

  • The expression $b("book")("author")(1)("last") returns the string Abiteboul.

    (This example combines 4.13.2.2 Arrays as Functions with map lookups.)

4.13.2 Arrays

4.13.2.2 Arrays as Functions

Arrays are function items, and a dynamic function call can be used to look up the value associated with position in an array. If $array is an array and $index is an integer corresponding to a position in the array, then $array($key) is equivalent to array:get($array, $key). The semantics of such a function call are formally defined in [Functions and Operators 4.0] section Section 19.2.11 array:getFO.

Examples:

  • [ 1, 2, 5, 7 ](4) evaluates to 7.

  • [ [ 1, 2, 3 ], [ 4, 5, 6 ] ](2) evaluates to [ 4, 5, 6 ].

  • [ [ 1, 2, 3 ], [ 4, 5, 6 ] ](2)(2) evaluates to 5.

  • [ 'a', 123, <name>Robert Johnson</name> ](3) evaluates to <name>Robert Johnson</name>.

  • array { (), (27, 17, 0) }(1) evaluates to 27.

  • array { (), (27, 17, 0) }(2) evaluates to 17.

  • array { "licorice", "ginger" }(20) raises a dynamic error [err:FOAY0001]FO40.

Note:

XPath 4.0 also provides an alternate syntax for map and array lookup that is more terse, supports wildcards, and allows lookup to iterate over a sequence of maps or arrays. See 4.13.3 Lookup Expressions for details.

4.17 Expressions on SequenceTypes

The instance of, cast, castable, and treat expressions are used to test whether a value conforms to a given type or to convert it to an instance of a given type.

4.17.2 Cast

CastExpr::=PipelineExpr ("cast" "as" CastTarget "?"?)?
PipelineExpr::=ArrowExpr ("->" ArrowExpr)*
CastTarget::=TypeName | ChoiceItemType | EnumerationType
TypeName::=EQName
EQName::=QName | URIQualifiedName
ChoiceItemType::="(" (ItemType ++ "|") ")"
ItemType::=RegularItemType | FunctionType | TypeName | ChoiceItemType
EnumerationType::="enum" "(" (StringLiteral ++ ",") ")"

Sometimes it is necessary to convert a value to a specific datatype. For this purpose, XPath 4.0 provides a cast expression that creates a new value of a specific type based on an existing value. A cast expression takes two operands: an input expression and a target type. The type of the atomized value of the input expression is called the input type. The target type must be a generalized atomic type. In practice this means it may be any of:

  • The name of an named item type defined in the static context, which in turn must refer to an item type in one of the following categories.

  • The name of a type defined in the in-scope schema types, which must be a simple type (of variety atomic, list or union) [err:XQST0052] . In addition, the target type cannot be xs:NOTATION, xs:anySimpleType, or xs:anyAtomicType

  • A ChoiceItemType representing a generalized atomic type (such as (xs:date | xs:dateTime)).

  • An EnumerationType such as enum("red", "green", "blue").

Otherwise, a static error is raised [err:XPST0080].

The optional occurrence indicator ? denotes that an empty sequence is permitted.

Casting a node to xs:QName can cause surprises because it uses the static context of the cast expression to provide the namespace bindings for this operation. Instead of casting to xs:QName, it is generally preferable to use the fn:QName function, which allows the namespace context to be taken from the document containing the QName.

The semantics of the cast expression are as follows:

  1. The input expression is evaluated.

  2. The result of the first step is atomized.

  3. If the result of atomization is a sequence of more than one atomic item, a type error is raised [err:XPTY0004].

  4. If the result of atomization is an empty sequence:

    1. If ? is specified after the target type, the result of the cast expression is an empty sequence.

    2. If ? is not specified after the target type, a type error is raised [err:XPTY0004].

  5. If the result of atomization is a single atomic item, the result of the cast expression is determined by casting to the target type as described in [Functions and Operators 4.0] section Section 23 CastingFO. When casting, an implementation may need to determine whether one type is derived by restriction from another. An implementation can determine this either by examining the in-scope schema definitions or by using an alternative, implementation-dependent mechanism such as a data dictionary. The result of a cast expression is one of the following:

    1. A value of the target type (or, in the case of list types, a sequence of values that are instances of the item type of the list type).

    2. A type error, if casting from the source type to the target type is not supported (for example attempting to convert an integer to a date).

    3. A dynamic error, if the particular input value cannot be converted to the target type (for example, attempting to convert the string "three" to an integer).

    Note:

    Casting to an enumeration type relies on the fact that an enumeration type is a generalized atomic type. So the expression cast $x as enum("red", "green") has the following effect:

    • If $x is an instance of xs:string, the expression returns $x unchanged if it is one of the permitted strings, and raises a dynamic error otherwise;

    • In other cases, the expression first casts $x to xs:string, and then proceeds as above.

4.17.4 Constructor Functions

For every simple type in the in-scope schema types (except xs:NOTATION and xs:anyAtomicType, and xs:anySimpleType, which are not instantiable), a constructor function is implicitly defined. In each case, the name of the constructor function is the same as the name of its target type (including namespace). The signature of the constructor function for a given type depends on the type that is being constructed, and can be found in [Functions and Operators 4.0] section Section 22 Constructor functionsFO.

There is also a constructor function for every named item type in the static context that expands either to a generalized atomic typeor to a RecordType.

All such constructor functions are classified as system functions.

Note:

The constructor function is present in the static context if and only if the corresponding type is present in the static context.

For XSLT, this means that a constructor function corresponding to an imported schema type is private to the stylesheet package, and a constructor function corresponding to an xsl:item-type declaration has the same visibility as the xsl:item-type declaration.

For XQuery, this means that a constructor function corresponding to an imported schema type is private to the query module, and a constructor function corresponding to a named item type declaration is %public or %private according to the annotations on the item type declaration.

[Definition: The constructor function for a given simple type is used to convert instances of other simple types into the given type. The semantics of the constructor function call T($arg) are defined to be equivalent to the expression $arg cast as T?.]

The following examples illustrate the use of constructor functions:

  • This example is equivalent to "2000-01-01" cast as xs:date?.

    xs:date("2000-01-01")
  • This example is equivalent to ($floatvalue * 0.2E-5) cast as xs:decimal?.

    xs:decimal($floatvalue * 0.2E-5)
  • This example returns an xs:dayTimeDuration value equal to 21 days. It is equivalent to "P21D" cast as xs:dayTimeDuration?.

    xs:dayTimeDuration("P21D")
  • If usa:zipcode is a user-defined atomic type in the in-scope schema types, then the following expression is equivalent to the expression ("12345" cast as usa:zipcode?).

    usa:zipcode("12345")
  • If my:chrono is a named item type that expands to (xs:date | xs:time | xs:dateTime), then the result of my:chrono("12:00:00Z") is the xs:time value 12:00:00Z.

  • If my:location is a named item type that expands to record(latitude as xs:double, longitude as xs:double), then the result of my:location(50.52, -3.02) is the map { 'latitude': 50.52e0, 'longitude': -3.02e0 }.

Note:

An instance of an atomic type whose name is in no namespace can be constructed by using a URIQualifiedName in either a cast expression or a constructor function call. Examples:

17 cast as Q{}apple
Q{}apple(17)

In either context, using an unqualified NCName might not work: in a cast expression, an unqualified name is it is interpreted according to the default namespace for elements and types, while an unqualified name in a constructor function call is resolved using the default function namespace which will often be inappropriate.

5 Conformance

Changes in 4.0  

  1. Support for higher-order functions is now a mandatory feature (in 3.1 it was optional).   [Issue 205 PR 326 1 February 2023]

  2. The static typing feature has been dropped.   [Issue 1343 PR 1344 3 September 2024]

  3. The module feature is no longer an optional feature; processing of library modules is now required.   [Issue 2022 PR 2026 28 May 2025]

This section defines the conformance criteria for an XPath 4.0 processor. In this section, the following terms are used to indicate the requirement levels defined in [RFC2119]. [Definition: MUST means that the item is an absolute requirement of the specification.] [Definition: MUST NOT means that the item is an absolute prohibition of the specification.] [Definition: MAY means that an item is truly optional.]

XPath is intended primarily as a component that can be used by other specifications. Therefore, XPath relies on specifications that use it (such as [XPointer] and [XSL Transformations (XSLT) Version 4.0][XSLT 4.0]) to specify conformance criteria for XPath in their respective environments. Specifications that set conformance criteria for their use of XPath MUST NOT change the syntactic or semantic definitions of XPath as given in this specification, except by subsetting and/or compatible extensions.

If a language is described as an extension of XPath, then every expression that conforms to the XPath grammar MUST behave as described in this specification.

C Implementation-Defined Items

The following items in this specification are implementation-defined:

  1. The version of Unicode that is used to construct expressions.

  2. The statically-known collations.

  3. The implicit timezone.

  4. The circumstances in which warnings are raised, and the ways in which warnings are handled.

  5. The method by which errors are reported to the external processing environment.

  6. Which version of XML and XML Names (e.g. [XML 1.0] and [XML Names] or [XML 1.1] and [XML Names 1.1]) and which version of XML Schema (e.g. [XML Schema 1.0] or [XML Schema 1.1]) is used for the definitions of primitives such as characters and names, and for the definitions of operations such as normalization of line endings and normalization of whitespace in attribute values. It is recommended that the latest applicable version be used (even if it is published later than this specification).

  7. How XDM instances are created from sources other than an Infoset or PSVI.

  8. Whether the implementation supports the namespace axis.

  9. Whether the type system is based on [XML Schema 1.0] or [XML Schema 1.1]. An implementation that has based its type system on XML Schema 1.0 is not required to support the use of the xs:dateTimeStamp constructor or the use of xs:dateTimeStamp or xs:error as TypeName in any expression.

  10. The signatures of functions provided by the implementation or via an implementation-defined API (see 2.2.1 Static Context).

  11. Any environment variables provided by the implementation.

  12. Any rules used for static typing (see 2.3.3.1 Static Analysis Phase).

  13. Any serialization parameters provided by the implementation

  14. What error, if any, is returned if an external function's implementation does not return the declared result type (see 2.3.6 Consistency Constraints).

D References

D.1 Normative References

RFC2119
S. Bradner. Key Words for use in RFCs to Indicate Requirement Levels. IETF RFC 2119. See http://www.ietf.org/rfc/rfc2119.txt.
RFC3986
T. Berners-Lee, R. Fielding, and L. Masinter. Uniform Resource Identifiers (URI): Generic Syntax. IETF RFC 3986. See http://www.ietf.org/rfc/rfc3986.txt.
RFC3987
M. Duerst and M. Suignard. Internationalized Resource Identifiers (IRIs). IETF RFC 3987. See http://www.ietf.org/rfc/rfc3987.txt.
ISO/IEC 10646
ISO (International Organization for Standardization). ISO/IEC 10646:2003. Information technology—Universal Multiple-Octet Coded Character Set (UCS), as, from time to time, amended, replaced by a new edition, or expanded by the addition of new parts. [Geneva]: International Organization for Standardization. (See http://www.iso.org for the latest version.)
Unicode
The Unicode Consortium. The Unicode Standard. Reading, Mass.: Addison-Wesley, 2003, as updated from time to time by the publication of new versions. See http://www.unicode.org/standard/versions/ for the latest version and additional information on versions of the standard and of the Unicode Character Database. The version of Unicode to be used is implementation-defined, but implementations are recommended to use the latest Unicode version.
XML 1.0
World Wide Web Consortium. Extensible Markup Language (XML) 1.0. W3C Recommendation. See http://www.w3.org/TR/REC-xml/. The edition of XML 1.0 must be no earlier than the Third Edition; the edition used is implementation-defined, but we recommend that implementations use the latest version.
XML 1.1
World Wide Web Consortium. Extensible Markup Language (XML) 1.1. W3C Recommendation. See http://www.w3.org/TR/xml11/
XML Base
World Wide Web Consortium. XML Base. W3C Recommendation. See http://www.w3.org/TR/xmlbase/
XML Names
World Wide Web Consortium. Namespaces in XML. W3C Recommendation. See http://www.w3.org/TR/REC-xml-names/
XML Names 1.1
World Wide Web Consortium. Namespaces in XML 1.1. W3C Recommendation. See http://www.w3.org/TR/xml-names11/
XML ID
World Wide Web Consortium. xml:id Version 1.0. W3C Recommendation. See http://www.w3.org/TR/xml-id/
XML Schema 1.0
World Wide Web Consortium. XML Schema, Parts 0, 1, and 2 (Second Edition). W3C Recommendation, 28 October 2004. See http://www.w3.org/TR/xmlschema-0/, http://www.w3.org/TR/xmlschema-1/, and http://www.w3.org/TR/xmlschema-2/.
XML Schema 1.1
World Wide Web Consortium. XML Schema, Parts 1, and 2. W3C Recommendation 5 April 2012. See http://www.w3.org/TR/xmlschema11-1/, and http://www.w3.org/TR/xmlschema11-2/.
XQuery and XPath Data Model (XDM) 4.0
XDM 4.0
XQuery and XPath Data Model (XDM) 4.0, XSLT Extensions Community Group, World Wide Web Consortium.
XQuery and XPath Functions and Operators 4.0
XQuery and XPath Functions and Operators 4.0, XSLT Extensions Community Group, World Wide Web Consortium.
XPath 4.0
XML Path Language (XPath) 4.0, XSLT Extensions Community Group, World Wide Web Consortium.
XSLT and XQuery Serialization 4.0
XSLT and XQuery Serialization 4.0, XSLT Extensions Community Group, World Wide Web Consortium.

D.2 Non-normative References

XQuery 3.1: An XML Query Language
XQuery 3.1: An XML Query Language, Jonathan Robie, Michael Dyck and Josh Spiegel, Editors. World Wide Web Consortium, 21 March 2017. This version is https://www.w3.org/TR/2017/REC-xquery-31-20170321/. The latest version is available at https://www.w3.org/TR/xquery-31/.
XQuery 1.0 and XPath 2.0 Formal Semantics
XQuery 1.0 and XPath 2.0 Formal Semantics (Second Edition), Jérôme Siméon, Denise Draper, Peter Frankhauser, et. al., Editors. World Wide Web Consortium, 14 December 2010. This version is https://www.w3.org/TR/2010/REC-xquery-semantics-20101214/. The latest version is available at https://www.w3.org/TR/xquery-semantics/.
XSL Transformations (XSLT) Version 4.0
XSLT 4.0
XSL Transformations (XSLT) Version 4.0, XSLT Extensions Community Group, World Wide Web Consortium.
XML Infoset
World Wide Web Consortium. XML Information Set (Second Edition). W3C Recommendation 4 February 2004. See http://www.w3.org/TR/xml-infoset/
XML Path Language (XPath) Version 1.0
XPath 1.0
XML Path Language (XPath) Version 1.0, James Clark and Steven DeRose, Editors. World Wide Web Consortium, 16 Nov 1999. This version is http://www.w3.org/TR/1999/REC-xpath-19991116. The latest version is available at http://www.w3.org/TR/xpath.
XML Path Language (XPath) Version 2.0
XPath 2.0
XML Path Language (XPath) 2.0 (Second Edition), Don Chamberlin, Anders Berglund, Scott Boag, et. al., Editors. World Wide Web Consortium, 14 December 2010. This version is https://www.w3.org/TR/2010/REC-xpath20-20101214/. The latest version is available at https://www.w3.org/TR/xpath20/.
XML Path Language (XPath) Version 3.0
XPath 3.0
XML Path Language (XPath) 3.0, Jonathan Robie, Don Chamberlin, Michael Dyck, John Snelson, Editors. World Wide Web Consortium, 08 April 2014. This version is https://www.w3.org/TR/2014/REC-xpath-30-20140408/. The latest version is available at https://www.w3.org/TR/xpath-30/.
XPointer
World Wide Web Consortium. XML Pointer Language (XPointer). W3C Last Call Working Draft 8 January 2001. See http://www.w3.org/TR/WD-xptr

F Glossary (Non-Normative)

absolute path expression

An absolute path expression is an instance of the production AbsolutePathExpr: it consists of either (a) the operator / followed by zero or more operands separated by / or // operators, or (b) the operator // followed by one or more operands separated by / or // operators.

and expression

An and expression is a non-trivial instance of the production AndExpr.

anonymous function

An anonymous function is a function item with no name. Anonymous functions may be created, for example, by evaluating an inline function expression or by partial function application.

application function

Application functions are function definitions written in a host language such as XQuery or XSLT whose syntax and semantics are defined in this family of specifications. Their behavior (including the rules determining the static and dynamic context) follows the rules for such functions in the relevant host language specification.

argument expression

An argument to a function call is either an argument expression or an ArgumentPlaceholder (?); in both cases it may either be supplied positionally, or identified by a name (called a keyword).

arity range

A function definition has an arity range, which is a range of consecutive non-negative integers. If the function definition has M required parameters and N optional parameters, then its arity range is from M to M+N inclusive.

array

An array is a function item that associates a set of positions, represented as positive integer keys, with values.

associated value

The value associated with a given key is called the associated value of the key.

atomic item

An atomic item is a value in the value space of an atomic type, as defined in [XML Schema 1.0] or [XML Schema 1.1].

atomic type

An atomic type is a simple schema type whose {variety}XS11-1 is atomic.

atomization

Atomization of a sequence is defined as the result of invoking the fn:data function, as defined in [Functions and Operators 4.0] section Section 2.1.4 fn:dataFO.

available binary resources

Available binary resources. This is a mapping of strings to binary resources. Each string represents the absolute URI of a resource. The resource is returned by the fn:unparsed-binary function when applied to that URI.

available documents

Available documents. This is a mapping of strings to document nodes. Each string represents the absolute URI of a resource. The document node is the root of a tree that represents that resource using the data model. The document node is returned by the fn:doc function when applied to that URI.

available item collections

Available collections. This is a mapping of strings to sequences of items. Each string represents the absolute URI of a resource. The sequence of items represents the result of the fn:collection function when that URI is supplied as the argument.

available text resources

Available text resources. This is a mapping of strings to text resources. Each string represents the absolute URI of a resource. The resource is returned by the fn:unparsed-text function when applied to that URI.

available uri collections

Available URI collections. This is a mapping of strings to sequences of URIs. The string represents the absolute URI of a resource which can be interpreted as an aggregation of a number of individual resources each of which has its own URI. The sequence of URIs represents the result of the fn:uri-collection function when that URI is supplied as the argument.

axis step

An axis step is an instance of the production AxisStep: it is an expression that returns a sequence of GNodes that are reachable from a starting GNode via a specified axis. An axis step has three parts: an axis, which defines the direction of movement for the step, a node test, which selects GNodes based on their properties, and zero or more predicates which are used to filter the results.

binding collection

The result of evaluating the binding expression in a for expression is called the binding collection

choice item type

A choice item type defines an item type that is the union of a number of alternatives. For example the type (xs:hexBinary | xs:base64Binary) defines the union of these two primitive atomic types, while the type (map(*) | array(*)) matches any item that is either a map or an array.

coercion rules

The coercion rules are rules used to convert a supplied value to a required type, for example when converting an argument of a function call to the declared type of the function parameter.

collation

A collation is a specification of the manner in which strings and URIs are compared and, by extension, ordered. For a more complete definition of collation, see [Functions and Operators 4.0] section Section 5.3 Comparison of stringsFO.

comma operator

A comma operator is a comma used specifically as the operator in a sequence expression.

complex terminal

A complex terminal is a variable terminal whose production rule references, directly or indirectly, an ordinary production rule.

constructor function

The constructor function for a given simple type is used to convert instances of other simple types into the given type. The semantics of the constructor function call T($arg) are defined to be equivalent to the expression $arg cast as T?.

content expression

In an enclosed expression, the optional expression enclosed in curly brackets is called the content expression.

context dependent

A function definition is said to be context dependent if its result depends on the static or dynamic context of its caller. A function definition may be context-dependent for some arities in its arity range, and context-independent for others: for example fn:name#0 is context-dependent while fn:name#1 is context-independent.

context node

When the context value is a single item, it can also be referred to as the context item; when it is a single node, it can also be referred to as the context node.

context position

The context position is the position of the context value within the series of values currently being processed.

context size

The context size is the number of values in the series of values currently being processed.

context value

The context value is the value currently being processed.

current dateTime

Current dateTime. This information represents an implementation-dependent point in time during the processing of an expression, and includes an explicit timezone. It can be retrieved by the fn:current-dateTime function. If called multiple times during the execution of an expression, this function always returns the same result.

data model

XPath 4.0 operates on the abstract, logical structure of an XML document or JSON object rather than its surface syntax. This logical structure, known as the data model, is defined in [XQuery and XPath Data Model (XDM) 4.0][XDM 4.0].

decimal-separator

decimal-separator(M, R) is used to separate the integer part of the number from the fractional part. The default value for both the marker and the rendition is U+002E (FULL STOP, PERIOD, .) .

default calendar

Default calendar. This is the calendar used when formatting dates in human-readable output (for example, by the functions fn:format-date and fn:format-dateTime) if no other calendar is requested. The value is a string.

default collation

Default collation. This identifies one of the collations in statically known collations as the collation to be used by functions and operators for comparing and ordering values of type xs:string and xs:anyURI (and types derived from them) when no explicit collation is specified.

default collection

Default collection. This is the sequence of items that would result from calling the fn:collection function with no arguments.

default element namespace rule

When an unprefixed lexical QName is expanded using the default element namespace rule, then it uses the default namespace for elements and types. If this is absent, or if it takes the special value ##any, then the no-namespace rule is used.

default function namespace

Default function namespace. This is either a namespace URI, or absentDM. The namespace URI, if present, is used for any unprefixed QName appearing in a position where a function name is expected.

default function namespace rule

When an unprefixed lexical QName is expanded using the default function namespace rule, it uses the default function namespace from the static context.

default in-scope namespace

The default in-scope namespace of an element node

default language

Default language. This is the natural language used when creating human-readable output (for example, by the functions fn:format-date and fn:format-integer) if no other language is requested. The value is a language code as defined by the type xs:language.

default namespace for elements and types

Default namespace for elements and types. This is either a namespace URI, or the special value "##any", or absentDM. This indicates how unprefixed QNames are interpreted when they appear in a position where an element name or type name is expected.

default place

Default place. This is a geographical location used to identify the place where events happened (or will happen) when processing dates and times using functions such as fn:format-date, fn:format-dateTime, and fn:civil-timezone, if no other place is specified. It is used when translating timezone offsets to civil timezone names, and when using calendars where the translation from ISO dates/times to a local representation is dependent on geographical location. Possible representations of this information are an ISO country code or an Olson timezone name, but implementations are free to use other representations from which the above information can be derived. The only requirement is that it should uniquely identify a civil timezone, which means that country codes for countries with multiple timezones, such as the United States, are inadequate.

default type namespace rule

When an unprefixed lexical QName is expanded using the default type namespace rule, it uses the default namespace for elements and types. If this is absent, the no-namespace rule is used. If the default namespace for elements and types has the special value ##any, then the lexical QName refers to a name in the namespace http://www.w3.org/2001/XMLSchema.

default URI collection

Default URI collection. This is the sequence of URIs that would result from calling the fn:uri-collection function with no arguments.

delimiting terminal symbol

The delimiting terminal symbols are: !!=#$%method()**:+,-->...///::*:::=<<<<===!>=>>>=>>??>?[@[]```{{{|||}}}×÷AposStringLiteralBracedURILiteralQuotStringLiteralStringLiteral

derives from

A schema typeS1 is said to derive fromschema typeS2 if any of the following conditions is true:

digit

digit(M) is a character used in the picture string to represent an optional digit; the default value is U+0023 (NUMBER SIGN, #) .

document order

Informally, document order is the order in which nodes appear in the XML serialization of a document.

dynamically known function definitions

Dynamically known function definitions. This is a set of function definitions. It includes the statically known function definitions as a subset, but may include other function definitions that are not known statically.

dynamic context

The dynamic context of an expression is defined as information that is needed for the dynamic evaluation of an expression, beyond any information that is needed from the static context.

dynamic error

A dynamic error is an error that must be detected during the dynamic evaluation phase and may be detected during the static analysis phase.

dynamic evaluation phase

The dynamic evaluation phase is the phase during which the value of an expression is computed.

dynamic function call

is

dynamic type

Every value matches one or more sequence types. A value is said to have a dynamic typeT if it matches (or is an instance of) the sequence type T.

effective boolean value

The effective boolean value of a value is defined as the result of applying the fn:boolean function to the value, as defined in Section 8.3.1 fn:booleanFO.

element name matching rule

When an unprefixed lexical QName is expanded using the element name matching rule rule, then it uses the default namespace for elements and types. If this is absent, then it uses the no-namespace rule. But if it takes the special value ##any, then the name is taken as matching any expanded QName with the corresponding local part, regardless of namespace: that is, the unprefixed name local is interpreted as *:local.

empty sequence

A sequence containing zero items is called an empty sequence.

enclosed expression

An enclosed expression is an instance of the EnclosedExpr production, which allows an optional expression within curly brackets.

entry

Each key / value pair in a map is called an entry.

enumeration type

An EnumerationType accepts a fixed set of string values.

environment variables

Environment variables. This is a mapping from names to values. Both the names and the values are strings. The names are compared using an implementation-defined collation, and are unique under this collation. The set of environment variables is implementation-defined and may be empty.

error value

In addition to its identifying QName, a dynamic error may also carry a descriptive string and one or more additional values called error values.

Executable Base URI

Executable Base URI. This is an absolute URI used to resolve relative URIs during the evaluation of expressions; it is used, for example, to resolve a relative URI supplied to the fn:doc or fn:unparsed-text functions.

expanded QName

An expanded QName is a triple: its components are a prefix, a local name, and a namespace URI. In the case of a name in no namespace, the namespace URI and prefix are both absent. In the case of a name in the default namespace, the prefix is absent.

exponent-separator

exponent-separator(M, R) is used to separate the mantissa from the exponent in scientific notation. The default value for both the marker and the rendition is U+0065 (LATIN SMALL LETTER E, e) .

expression context

The expression context for a given expression consists of all the information that can affect the result of the expression.

external function

External functions can be characterized as functions that are neither part of the processor implementation, nor written in a language whose semantics are under the control of this family of specifications. The semantics of external functions, including any context dependencies, are entirely implementation-defined. In XSLT, external functions are called Section 24.1 Extension Functions XT30.

filter expression

A filter expression is an instance of the construct FilterExpr: that is, it is an expression in the form E1[E2]. Its effect is to return those items from the value of E1 that satisfy the predicate in E2.

filter expression for maps and arrays

A filter expression for maps and arrays is an instance of the construct FilterExprAM: that is, it is an expression in the form E1?[E2]. Its effect is to evaluate E1 to return an array or map, and to select members of the array, or entries from the map, that satisfy the predicate in E2.

fixed focus

A fixed focus is a focus for an expression that is evaluated once, rather than being applied to a series of values; in a fixed focus, the context value is set to one specific value, the context position is 1, and the context size is 1.

focus

The first three components of the dynamic context (context value, context position, and context size) are called the focus of the expression.

focus function

A focus function is an inline function expression in which the function signature is implicit: the function takes a single argument of type item()* (that is, any value), and binds this to the context value when evaluating the function body, which returns a result of type item()*.

function coercion

Function coercion wraps a function item in a new function whose signature is the same as the expected type. This effectively delays the checking of the argument and return types until the function is called.

function definition

A function definition contains information used to evaluate a static function call, including the name, parameters, and return type of the function.

function item

A function item is an item that can be called using a dynamic function call.

generalized atomic type

A generalized atomic type is an item type whose instances are all atomic items. Generalized atomic types include (a) atomic types, either built-in (for example xs:integer) or imported from a schema, (b) pure union types, either built-in (xs:numeric and xs:error) or imported from a schema, (c) choice item types if their alternatives are all generalized atomic types, and (d) enumeration types.

GNode

The term generic node or GNode is a collective term for XNodes (more commonly called simply nodes) representing the parts of an XML document, and JNodes, often used to represent the parts of a JSON document.

grouping-separator

grouping-separator(M, R) is used to separate groups of digits (for example as a thousands separator). The default value for both the marker and the rendition is U+002C (COMMA, ,) .

GTree

The term GTree means JTree or XTree.

guarded

An expression E is said to be guarded by some governing condition C if evaluation of E is not allowed to fail with a dynamic error except when C applies.

host language

A host language for XPath is any environment that provides capabilities for XPath expressions to be defined and evaluated, and that supplies a static and dynamic context for their evaluation.

ignorable whitespace

Ignorable whitespace consists of any whitespace characters that may occur between terminals, unless these characters occur in the context of a production marked with a ws:explicit annotation, in which case they can occur only where explicitly specified (see A.3.4.2 Explicit Whitespace Handling).

implausible

Certain expressions, while not erroneous, are classified as being implausible, because they achieve no useful effect.

implementation defined

Implementation-defined indicates an aspect that may differ between implementations, but must be specified by the implementer for each particular implementation.

implementation dependent

Implementation-dependent indicates an aspect that may differ between implementations, is not specified by this or any W3C specification, and is not required to be specified by the implementer for any particular implementation.

implicit timezone

Implicit timezone. This is the timezone to be used when a date, time, or dateTime value that does not have a timezone is used in a comparison or arithmetic operation. The implicit timezone is an implementation-defined value of type xs:dayTimeDuration. See Section 3.2.7.3 Timezones XS1-2 or Section 3.3.7 dateTime XS11-2 for the range of valid values of a timezone.

infinity

infinity(R) is the string used to represent the double value infinity (INF); the default value is the string "Infinity"

inline function expression

An inline function expression is an instance of the construct InlineFunctionExpr. When evaluated, an inline function expression creates an anonymous function whose properties are defined directly in the inline function expression.

in-scope attribute declarations

In-scope attribute declarations. Each attribute declaration is identified either by an expanded QName (for a top-level attribute declaration) or by an implementation-dependent attribute identifier (for a local attribute declaration).

in-scope element declarations

In-scope element declarations. Each element declaration is identified either by an expanded QName (for a top-level element declaration) or by an implementation-dependent element identifier (for a local element declaration).

in-scope named item types

In-scope named item types. This is a mapping from expanded QNames to named item types.

in-scope namespaces

The in-scope namespaces property of an element node is a set of namespace bindings, each of which associates a namespace prefix with a URI.

in-scope schema definitions

In-scope schema definitions is a generic term for all the element declarations, attribute declarations, and schema type definitions that are in scope during static analysis of an expression.

in-scope schema type

In-scope schema types. Each schema type definition is identified either by an expanded QName (for a named type) or by an implementation-dependent type identifier (for an anonymous type). The in-scope schema types include the predefined schema types described in 3.5 Schema Types.

in-scope variables

In-scope variables. This is a mapping from expanded QNames to sequence types. It defines the set of variables that are available for reference within an expression. The expanded QName is the name of the variable, and the type is the static type of the variable.

item

An item is either an atomic item, a node, or a function item.

item type

An item type is a type that can be expressed using the ItemType syntax, which forms part of the SequenceType syntax. Item types match individual items.

item type designator

An item type designator is a syntactic construct conforming to the grammar rule ItemType. An item type designator is said to designate an item type.

JNode

A JNode is a kind of item used to represent a value within the context of a tree of maps and arrays. A root JNode represents a map or array; a non-root JNode represents a member of an array or an entry in a map.

JTree

A tree that is rooted at a parentless JNode is referred to as a JTree.

kind test

An alternative form of a node test called a type test can select XNodes based on their type, or in the case of JNodes, the type of their contained ·content·

lexical QName

A lexical QName is a name that conforms to the syntax of the QName production

literal

A literal is a direct syntactic representation of an atomic item.

literal terminal

A literal terminal is a token appearing as a string in quotation marks on the right-hand side of an ordinary production rule.

logical expression

A logical expression is either an and expression or an or expression. If a logical expression does not raise an error, its value is always one of the boolean values true or false.

lookup expression

A lookup expression is an instance of the production LookupExpr: that is, an expression in the form E1?KS, where E1 is an expression returning a sequence of maps or arrays, and KS is a key specifier, which indicates which entries in a map, or members in an array, should be selected.

map

A map is a function that associates a set of keys with values, resulting in a collection of key / value pairs.

mapping arrow operator

The mapping arrow operator=!> applies a function to each item in a sequence.

may

MAY means that an item is truly optional.

member

The values of an array are called its members.

minus-sign

minus-sign(R) is the string used to mark negative numbers; the default value is U+002D (HYPHEN-MINUS, -) .

must

MUST means that the item is an absolute requirement of the specification.

must not

MUST NOT means that the item is an absolute prohibition of the specification.

named function reference

A named function reference is an instance of the production NamedFunctionRef: it is an expression (written name#arity) which evaluates to a function item, the details of the function item being based on the properties of a function definition in the static context.

named item type

A named item type is an ItemType identified by an expanded QName.

namespace binding

A namespace binding is a pair comprising a namespace prefix (which is either an xs:NCName or empty), and a namespace URI.

namespace-sensitive

The namespace-sensitive types are xs:QName, xs:NOTATION, types derived by restriction from xs:QName or xs:NOTATION, list types that have a namespace-sensitive item type, and union types with a namespace-sensitive type in their transitive membership.

name test

A node test that consists only of an EQName or a Wildcard is called a name test.

NaN

NaN(R) is the string used to represent the double value NaN (not a number); the default value is the string "NaN"

node

Except where the context indicates otherwise, the term node is used as a synonym for XNode.

node test

A node test is a condition on the properties of a GNode. A node test determines which GNodes returned by an axis are selected by a step.

no-namespace rule

When an unprefixed lexical QName is expanded using the no-namespace rule, it is interpreted as having an absent namespace URI.

non-delimiting terminal symbol

The non-delimiting terminal symbols are: ancestorancestor-or-selfandarrayasatattributecastcastablechildcommentdescendantdescendant-or-selfdivdocument-nodeelementelseempty-sequenceenumeqeveryexceptfnfollowingfollowing-or-selffollowing-siblingfollowing-sibling-or-selffollowsforfunctiongegetgnodegtidivifininstanceintersectisis-notitemjnodekeyleletltmapmembermodnamespacenamespace-nodenenodeoforotherwiseparentprecedesprecedingpreceding-or-selfpreceding-siblingpreceding-sibling-or-selfprocessing-instructionrecordreturnsatisfiesschema-attributeschema-elementselfsometextthentotreattypeunionvalueBinaryIntegerLiteralDecimalLiteralDoubleLiteralHexIntegerLiteralIntegerLiteralNCNameQNameURIQualifiedName

non-trivial

A construct is said to be a non-trivial instance of a grammatical production if it is not also an instance of one of its sub-productions.

numeric

The type xs:numeric is defined as a union type with member types xs:double, xs:float, and xs:decimal. An item that is an instance of any of these types is referred to as a numeric value, and a type that is a subtype of xs:numeric is referred to as a numeric type.

ordinary production rule

An ordinary production rule is a production rule in A.1 EBNF that is not annotated ws:explicit.

or expression

An or expression is a non-trivial instance of the production OrExpr.

partial function application

A static or dynamic function call is a partial function application if one or more arguments is an ArgumentPlaceholder.

partially applied function

A partially applied function is a function created by partial function application.

path expression

A path expression is either an absolute path expression or a relative path expression

pattern-separator

pattern-separator(M) is a character used to separate positive and negative sub-pictures in a picture string; the default value is U+003B (SEMICOLON, ;) .

percent

percent(M, R) is used to indicate that the number is written as a per-hundred fraction; the default value for both the marker and the rendition is U+0025 (PERCENT SIGN, %) .

per-mille

per-mille(M, R) is used to indicate that the number is written as a per-thousand fraction; the default value for both the marker and the rendition is U+2030 (PER MILLE SIGN, ) .

pipeline operator

The pipeline operator-> evaluates an expression and binds the result to the context value before evaluating another expression.

predicate truth value

The predicate truth value of a value $V is the result of the expression if ($V instance of xs:numeric+) then ($V = position()) else fn:boolean($V).

primary expression

A primary expression is an instance of the production PrimaryExpr. Primary expressions are the basic primitives of the language. They include literals, variable references, context value references, and function calls. A primary expression may also be created by enclosing any expression in parentheses, which is sometimes helpful in controlling the precedence of operators.

principal node kind

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.

pure union type

A pure union type is a simple type that satisfies the following constraints: (a) {variety}XS11-1 is union, (b) the {facets}XS11-1 property is empty, (c) no type in the transitive membership of the union type has {variety}XS11-1list, and (d) no type in the transitive membership of the union type is a type with {variety}XS11-1union having a non-empty {facets}XS11-1 property

range expression

A range expression is a non-trivial instance of the production RangeExpr. A range expression is used to construct a sequence of integers.

relative path expression

A relative path expression is a non-trivial instance of the production RelativePathExpr: it consists of two or more operand expressions separated by / or // operators.

resolve

To resolve a relative URI$rel against a base URI $base is to expand it to an absolute URI, as if by calling the function fn:resolve-uri($rel, $base).

reverse document order

The node ordering that is the reverse of document order is called reverse document order.

same key

Two atomic items K1 and K2 have the same key value if fn:atomic-equal(K1, K2) returns true, as specified in [Functions and Operators 4.0] section Section 14.2.1 fn:atomic-equalFO

schema type

A schema type is a complex type or simple type as defined in the [XML Schema 1.0] or [XML Schema 1.1] specifications, including built-in types as well as user-defined types.

sequence

A sequence is an ordered collection of zero or more items.

sequence arrow operator

The sequence arrow operator=> applies a function to a supplied sequence.

sequence concatenation

The sequence concatenation of a number of sequences S1, S2, ... Sn is defined to be the sequence formed from the items of S1, followed by the items from S2, and so on, retaining order.

sequence expression

A sequence expression is a non-trivial instance of the production rule Expr, that is, an expression containing two or more instances of the production ExprSingle separated by the comma operator.

sequence type

A sequence type is a type that can be expressed using the SequenceType syntax. Sequence types are used whenever it is necessary to refer to a type in an XPath 4.0 expression. Since all values are sequences, every value matches one or more sequence types.

sequence type designator

A sequence type designator is a syntactic construct conforming to the grammar rule SequenceType. A sequence type designator is said to designate a sequence type.

SequenceType matching

SequenceType matching compares a value with an expected sequence type.

serialization

Serialization is the process of converting an XDM instance to a sequence of octets (step DM4 in Figure 1.), as described in [XSLT and XQuery Serialization 4.0].

singleton

A sequence containing exactly one item is called a singleton.

singleton enumeration type

An enumeration type with a single enumerated value E (such as enum("red")) matches an item S if and only if (a) S is an instance of xs:string, and (b) S is equal to E when compared using Unicode codepoint collation. This is referred to as a singleton enumeration type.

singleton focus

A singleton focus is a fixed focus in which the context value is a singleton item.

stable

Document order is stable, which means that the relative order of two nodes will not change during the processing of a given expression, even if this order is implementation-dependent.

statically known collations

Statically known collations. This is an implementation-defined mapping from URI to collation. It defines the names of the collations that are available for use in processing expressions.

statically known decimal formats

Statically known decimal formats. This is a mapping from QNames to decimal formats, with one default format that has no visible name, referred to as the unnamed decimal format. Each format is available for use when formatting numbers using the fn:format-number function.

statically known function definitions

Statically known function definitions. This is a set of function definitions.

statically known namespaces

Statically known namespaces. This is a mapping from prefix to namespace URI that defines all the namespaces that are known during static processing of a given expression.

static analysis phase

The static analysis phase depends on the expression itself and on the static context. The static analysis phase does not depend on input data (other than schemas).

Static Base URI

Static Base URI. This is an absolute URI, used to resolve relative URIs during static analysis.

static context

The static context of an expression is the information that is available during static analysis of the expression, prior to its evaluation.

static error

An error that can be detected during the static analysis phase, and is not a type error, is a static error.

static function call

A static function call is an instance of the production FunctionCall: it consists of an EQName followed by a parenthesized list of zero or more arguments.

static type

The static type of an expression is the best inference that the processor is able to make statically about the type of the result of the expression.

step

The operands of a path expression are conventionally referred to as steps.

string value

The string value of a node is a string and can be extracted by applying the Section 2.1.3 fn:stringFOstring function to the node.

substantively disjoint

Two sequence types are deemed to be substantively disjoint if (a) neither is a subtype of the other (see 3.3.1 Subtypes of Sequence Types) and (b) the only values that are instances of both types are one or more of the following:

substitution group

Substitution groups are defined in Section 2.2.2.2 Element Substitution Group XS1-1 and Section 2.2.2.2 Element Substitution Group XS11-1. Informally, the substitution group headed by a given element (called the head element) consists of the set of elements that can be substituted for the head element without affecting the outcome of schema validation.

subtype

Given two sequence types or item types, the rules in this section determine if one is a subtype of the other. If a type A is a subtype of type B, it follows that every value matched by A is also matched by B.

subtype substitution

The use of a value that has a dynamic type that is a subtype of the expected type is known as subtype substitution.

symbol

Each rule in the grammar defines one symbol, using the following format:

symbol ::= expression
symbol separators

Whitespace and Comments function as symbol separators. For the most part, they are not mentioned in the grammar, and may occur between any two terminal symbols mentioned in the grammar, except where that is forbidden by the /* ws: explicit */ annotation in the EBNF, or by the /* xgc: xml-version */ annotation.

system function

System functions include the functions defined in [XQuery and XPath Functions and Operators 4.0], functions defined by the specifications of a host language, constructor functions for atomic types, and any additional functions provided by the implementation. System functions are sometimes called built-in functions.

terminal

A terminal is a symbol or string or pattern that can appear in the right-hand side of a rule, but never appears on the left-hand side in the main grammar, although it may appear on the left-hand side of a rule in the grammar for terminals.

type annotation

Each element node and attribute node in an XDM instance has a type annotation (described in [XDM 4.0] section Section 4.1 Schema InformationDM). The type annotation of a node is a reference to a schema type.

typed value

The typed value of a node is a sequence of atomic items and can be extracted by applying the Section 2.1.4 fn:dataFOdata function to the node.

type error

A type error may be raised during the static analysis phase or the dynamic evaluation phase. During the static analysis phase, a type error occurs when the static type of an expression does not match the expected type of the context in which the expression occurs. During the dynamic evaluation phase, a type error occurs when the dynamic type of a value does not match the expected type of the context in which the value occurs.

URI

Within this specification, the term URI refers to a Universal Resource Identifier as defined in [RFC3986] and extended in [RFC3987] with the new name IRI.

value

In the data model, a value is always a sequence.

variable reference

A variable reference is an EQName preceded by a $-sign.

variable terminal

A variable terminal is an instance of a production rule that is not itself an ordinary production rule but that is named (directly) on the right-hand side of an ordinary production rule.

variable values

Variable values. This is a mapping from expanded QNames to values. It contains the same expanded QNames as the in-scope variables in the static context for the expression. The expanded QName is the name of the variable and the value is the dynamic value of the variable, which includes its dynamic type.

warning

In addition to static errors, dynamic errors, and type errors, an XPath 4.0 implementation may raise warnings, either during the static analysis phase or the dynamic evaluation phase. The circumstances in which warnings are raised, and the ways in which warnings are handled, are implementation-defined.

whitespace

A whitespace character is any of the characters defined by [http://www.w3.org/TR/REC-xml/#NT-S].

wildcard-matches

In these rules, if MU and NU are NameTestUnions, then MUwildcard-matchesNU is true if every name that matches MU also matches NU.

XDM instance

The term XDM instance is used, synonymously with the term value, to denote an unconstrained sequence of items.

XNode

An XNode is an instance of one of the node kinds defined in [XDM 4.0] section Section 7.1 XML NodesDM.

XPath 1.0 compatibility mode

XPath 1.0 compatibility mode.This value is true if rules for backward compatibility with XPath Version 1.0 are in effect; otherwise it is false.

xs:anyAtomicType

xs:anyAtomicType is an atomic type that includes all atomic items (and no values that are not atomic). Its base type is xs:anySimpleType from which all simple types, including atomic, list, and union types, are derived. All primitive atomic types, such as xs:decimal and xs:string, have xs:anyAtomicType as their base type.

xs:dayTimeDuration

xs:dayTimeDuration is derived by restriction from xs:duration. The lexical representation of xs:dayTimeDuration is restricted to contain only day, hour, minute, and second components.

xs:error

xs:error is a simple type with no value space. It is defined in Section 3.16.7.3 xs:error XS11-1 and can be used in the 3.1 Sequence Types to raise errors.

xs:untyped

xs:untyped is used as the type annotation of an element node that has not been validated, or has been validated in skip mode.

xs:untypedAtomic

xs:untypedAtomic is an atomic type that is used to denote untyped atomic data, such as text that has not been assigned a more specific type.

xs:yearMonthDuration

xs:yearMonthDuration is derived by restriction from xs:duration. The lexical representation of xs:yearMonthDuration is restricted to contain only year and month components.

XTree

A tree that is rooted at a parentless XNode is referred to as an XTree.

zero-digit

zero-digit(M) is the character used in the picture string to represent the digit zero; the default value is U+0030 (DIGIT ZERO, 0) . This character must be a digit (category Nd in the Unicode property database), and it must have the numeric value zero. This property implicitly defines the ten Unicode characters that are used to represent the values 0 to 9 in the function output: Unicode is organized so that each set of decimal digits forms a contiguous block of characters in numerical sequence. Within the picture string any of these ten character can be used (interchangeably) as a place-holder for a mandatory digit. Within the final result string, these ten characters are used to represent the digits zero to nine.

H Backwards Compatibility (Non-Normative)

H.4 Incompatibilities relative to XPath 1.0

This appendix provides a summary of the areas of incompatibility between XPath 4.0 and [XML Path Language (XPath) Version 1.0][XPath 1.0]. In each of these cases, an XPath 4.0 processor is compatible with an XPath 2.0, 3.0, or 3.1 processor.

Three separate cases are considered:

  1. Incompatibilities that exist when source documents have no schema, and when running with XPath 1.0 compatibility mode set to true. This specification has been designed to reduce the number of incompatibilities in this situation to an absolute minimum, but some differences remain and are listed individually.

  2. Incompatibilities that arise when XPath 1.0 compatibility mode is set to false. In this case, the number of expressions where compatibility is lost is rather greater.

  3. Incompatibilities that arise when the source document is processed using a schema (whether or not XPath 1.0 compatibility mode is set to true). Processing the document with a schema changes the way that the values of nodes are interpreted, and this can cause an XPath expression to return different results.

H.4.1 Incompatibilities when Compatibility Mode is true

The list below contains all known areas, within the scope of this specification, where an XPath 4.0 processor running with compatibility mode set to true will produce different results from an XPath 1.0 processor evaluating the same expression, assuming that the expression was valid in XPath 1.0, and that the nodes in the source document have no type annotations other than xs:untyped and xs:untypedAtomic.

Incompatibilities in the behavior of individual functions are not listed here, but are included in an appendix of [XQuery and XPath Functions and Operators 4.0].

Since both XPath 1.0 and XPath 4.0 leave some aspects of the specification implementation-defined, there may be incompatibilities in the behavior of a particular implementation that are outside the scope of this specification. Equally, some aspects of the behavior of XPath are defined by the host language.

  1. Consecutive comparison operators such as A < B < C were supported in XPath 1.0, but are not permitted by the XPath 4.0 grammar. In most cases such comparisons in XPath 1.0 did not have the intuitive meaning, so it is unlikely that they have been widely used in practice. If such a construct is found, an XPath 4.0 processor will report a syntax error, and the construct can be rewritten as (A < B) < C

  2. When converting strings to numbers (either explicitly when using the number function, or implicitly say on a function call), certain strings that converted to the special value NaN under XPath 1.0 will convert to values other than NaN under XPath 4.0. These include any number written with a leading + sign, any number in exponential floating point notation (for example 1.0e+9), and the strings INF and -INF.

    Furthermore, the strings Infinity and -Infinity, which were accepted by XPath 1.0 as representations of the floating-point values positive and negative infinity, are no longer recognized. They are converted to NaN when running under XPath 4.0 with compatibility mode set to true, and cause a dynamic error when compatibility mode is set to false.

  3. XPath 4.0 does not allow a token starting with a letter to follow immediately after a numeric literal, without intervening whitespace. For example, 10div 3 was permitted in XPath 1.0, but in XPath 4.0 must be written as 10 div 3.

  4. The namespace axis is deprecated as of XPath 2.0. Implementations may support the namespace axis for backward compatibility with XPath 1.0, but they are not required to do so. (XSLT 2.0 requires that if XPath backwards compatibility mode is supported, then the namespace axis must also be supported; but other host languages may define the conformance rules differently.)

  5. In XPath 1.0, the expression -x|y parsed as -(x|y), and returned the negation of the numeric value of the first node in the union of x and y. In XPath 4.0, this expression parses as (-x)|y. When XPath 1.0 Compatibility Mode is true, this will always cause a type error.

  6. The rules for converting numbers to strings have changed. These may affect the way numbers are displayed in the output of a stylesheet. For numbers whose absolute value is in the range 1E-6 to 1E+6, the result should be the same, but outside this range, scientific format is used for non-integral xs:float and xs:double values.

  7. If one operand in a general comparison is a single atomic item of type xs:boolean, the other operand is converted to xs:boolean when XPath 1.0 compatibility mode is set to true. In XPath 1.0, if neither operand of a comparison operation using the <, <=, > or >= operator was a node set, both operands were converted to numbers. The result of the expression true() > number('0.5') is therefore true in XPath 1.0, but is false in XPath 4.0 even when compatibility mode is set to true.

  8. In XPath 4.0, a type error is raised if the PITarget specified in a SequenceType of form processing-instruction(PITarget) is not a valid NCName. In XPath 1.0, this condition was not treated as an error.