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


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.1 Comments

Comment::="(:" (CommentContents | Comment)* ":)"
/* ws: explicit */
/* gn: comments */
CommentContents::=(Char+ - (Char* ('(:' | ':)') Char*))
/* ws: explicit */

Comments may be used to provide information relevant to programmers who read an expression. Comments are lexical constructs only, and do not affect expression processing.

Comments are strings, delimited by the symbols (: and :). Comments may be nested.

A comment may be used anywhere ignorable whitespace is allowed (see A.3.5.13.4.1 Default Whitespace Handling).

The following is an example of a comment:

(: Houston, we have a problem :)

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.53.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.2 General Comparisons

Changes in 4.0  

  1. Operators such as < and > can use the full-width forms and to avoid the need for XML escaping.

The general comparison operators are =, !=, <, <=, >, and >=. General comparisons are existentially quantified comparisons that may be applied to operand sequences of any length. The result of a general comparison that does not raise an error is always true or false.

If XPath 1.0 compatibility mode is true, a general comparison is evaluated by applying the following rules, in order:

  1. If either operand is a single atomic item that is an instance of xs:boolean, then the other operand is converted to xs:boolean by taking its effective boolean value.

  2. Atomization is applied to each operand. After atomization, each operand is a sequence of atomic items.

  3. If the comparison operator is <, <=, >, or >=, then each item in both of the operand sequences 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.)

  4. The result of the comparison is true if and only if there is a pair of atomic items, one in the first operand sequence and the other in the second operand sequence, that have the required magnitude relationship. Otherwise the result of the comparison is false or an error. The magnitude relationship between two atomic items is determined by applying the following rules. If a cast operation called for by these rules is not successful, a dynamic error is raised. [err:FORG0001]FO40

    1. If at least one of the two atomic items is an instance of a numeric type, then both atomic items are converted to the type xs:double by applying the fn:number function.

    2. If at least one of the two atomic items is an instance of xs:string, or if both atomic items are instances of xs:untypedAtomic, then both atomic items are cast to the type xs:string.

    3. If one of the atomic items is an instance of xs:untypedAtomic and the other is not an instance of xs:string, xs:untypedAtomic, or any numeric type, then the xs:untypedAtomic item is cast to the dynamic type of the other value.

    4. After performing the conversions described above, the atomic items are compared using one of the value comparison operators eq, ne, lt, le, gt, or ge, depending on whether the general comparison operator was =, !=, <, <=, >, or >=. The values have the required magnitude relationship if and only if the result of this value comparison is true.

If XPath 1.0 compatibility mode is false, a general comparison is evaluated by applying the following rules, in order:

  1. Atomization is applied to each operand. After atomization, each operand is a sequence of atomic items.

  2. The result of the comparison is true if and only if there is a pair of atomic items, one in the first operand sequence and the other in the second operand sequence, that have the required magnitude relationship. Otherwise the result of the comparison is false or an error. The magnitude relationship between two atomic items is determined by applying the following rules. If a cast operation called for by these rules is not successful, a dynamic error is raised. [err:FORG0001]FO40

    1. If both atomic items are instances of xs:untypedAtomic, then the values are cast to the type xs:string.

    2. If exactly one of the atomic items is an instance of xs:untypedAtomic, it is cast to a type depending on the other value’s dynamic type T according to the following rules, in which V denotes the value to be cast:

      1. If T is a numeric type or is derived from a numeric type, then V is cast to xs:double.

      2. If T is xs:dayTimeDuration or is derived from xs:dayTimeDuration, then V is cast to xs:dayTimeDuration.

      3. If T is xs:yearMonthDuration or is derived from xs:yearMonthDuration, then V is cast to xs:yearMonthDuration.

      4. In all other cases, V is cast to the primitive base type of T.

      Note:

      The special treatment of the duration types is required to avoid errors that may arise when comparing the primitive type xs:duration with any duration type.

    3. After performing the conversions described above, the atomic items are compared using one of the value comparison operators eq, ne, lt, le, gt, or ge, depending on whether the general comparison operator was =, !=, <, <=, >, or >=. The values have the required magnitude relationship if and only if the result of this value comparison is true.

When evaluating a general comparison in which either operand is a sequence of items, an implementation may return true as soon as it finds an item in the first operand and an item in the second operand that have the required magnitude relationship. Similarly, a general comparison may raise a dynamic error as soon as it encounters an error in evaluating either operand, or in comparing a pair of items from the two operands. As a result of these rules, the result of a general comparison is not deterministic in the presence of errors.

Here are some examples of general comparisons:

  • The following comparison is true if the typed value of any author subelement of $book1 is "Kennedy" as an instance of xs:string or xs:untypedAtomic:

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

    [ "Obama", "Nixon", "Kennedy" ] = "Kennedy"
  • The following example contains three general comparisons. The value of the first two comparisons is true, and the value of the third comparison is false. This example illustrates the fact that general comparisons are not transitive.

    (1, 2) = (2, 3)
    (2, 3) = (3, 4)
    (1, 2) = (3, 4)
  • The following example contains two general comparisons, both of which are true. This example illustrates the fact that the = and != operators are not inverses of each other.

    (1, 2) = (2, 3)
    (1, 2) != (2, 3)
  • Suppose that $a, $b, and $c are bound to element nodes with type annotation xs:untypedAtomic, with string values"1", "2", and "2.0" respectively. Then ($a, $b) = ($c, 3.0) returns false, because $b and $c are compared as strings. However, ($a, $b) = ($c, 2.0) returns true, because $b and 2.0 are compared as numbers.

A XPath 4.0 Grammar

A.1 EBNF

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 grammar of XPath 4.0 uses the same simple Extended Backus-Naur Form (EBNF) notation as [XML 1.0] with the following differences.

  • The notation XYZ ** "," indicates a sequence of zero or more occurrences of XYZ, with a single comma between adjacent occurrences.

  • The notation XYZ ++ "," indicates a sequence of one or more occurrences of XYZ, with a single comma between adjacent occurrences.

  • All named symbols have a name that begins with an uppercase letter.

  • It adds a notation for referring to productions in external specifications.

  • Comments or extra-grammatical constraints on grammar productions are between '/*' and '*/' symbols.

The terminal symbols for this grammar include the quoted strings used in the production rules below, and the terminal symbols defined in section A.3.1 Terminal Symbols. The grammar is a little unusual in that parsing and tokenization are somewhat intertwined: for more details see A.3 Lexical structure.

The EBNF notation is described in more detail in A.1.1 Notation.

AbbreviatedStep::=".." | ("@" NodeTest) | SimpleNodeTest
AbsolutePathExpr::=("/" RelativePathExpr?) | ("//" RelativePathExpr)
AdditiveExpr::=MultiplicativeExpr (("+" | "-") MultiplicativeExpr)*
AndExpr::=ComparisonExpr ("and" ComparisonExpr)*
AnyArrayType::="array" "(" "*" ")"
AnyFunctionType::=("function" | "fn") "(" "*" ")"
AnyItemTest::="item" "(" ")"
AnyMapType::="map" "(" "*" ")"
AnyNodeKindTest::="node" "(" ")"
AnyRecordType::="record" "(" "*" ")"
Argument::=ExprSingle | ArgumentPlaceholder
ArgumentList::="(" ((PositionalArguments ("," KeywordArguments)?) | KeywordArguments)? ")"
ArgumentPlaceholder::="?"
ArrayConstructor::=SquareArrayConstructor | CurlyArrayConstructor
ArrayType::=AnyArrayType | TypedArrayType
ArrowExpr::=UnaryExpr (SequenceArrowTarget | MappingArrowTarget)*
ArrowTarget::=FunctionCall | RestrictedDynamicCall
AttributeName::=EQName
AttributeTest::="attribute" "(" (NameTestUnion ("," TypeName)?)? ")"
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") "::"
AxisStep::=(AbbreviatedStep | FullStep) Predicate*
BracedAction::=EnclosedExpr
CastableExpr::=CastExpr ("castable" "as" CastTarget "?"?)?
CastExpr::=PipelineExpr ("cast" "as" CastTarget "?"?)?
CastTarget::=TypeName | ChoiceItemType | EnumerationType
ChoiceItemType::="(" (ItemType ++ "|") ")"
CommentTest::="comment" "(" ")"
ComparisonExpr::=OtherwiseExpr ((ValueComp | GeneralComp | NodeComp) OtherwiseExpr)?
ContextValueRef::="."
CurlyArrayConstructor::="array" EnclosedExpr
DocumentTest::="document-node" "(" (ElementTest | SchemaElementTest | NameTestUnion)? ")"
DynamicFunctionCall::=PostfixExprPositionalArgumentList
ElementName::=EQName
ElementTest::="element" "(" (NameTestUnion ("," TypeName "?"?)?)? ")"
EnclosedExpr::="{" Expr? "}"
EnumerationType::="enum" "(" (StringLiteral ++ ",") ")"
EQName::=QName | URIQualifiedName
Expr::=(ExprSingle ++ ",")
ExprSingle::=ForExpr
| LetExpr
| QuantifiedExpr
| IfExpr
| OrExpr
ExtensibleFlag::="," "*"
FieldDeclaration::=FieldName "?"? ("as" SequenceType)?
FieldName::=NCName | StringLiteral
FilterExpr::=PostfixExprPredicate
FilterExprAM::=PostfixExpr "?[" Expr "]"
ForBinding::=ForItemBinding | ForMemberBinding | ForEntryBinding
ForClause::="for" (ForBinding ++ ",")
ForEntryBinding::=((ForEntryKeyBindingForEntryValueBinding?) | ForEntryValueBinding) PositionalVar? "in" ExprSingle
ForEntryKeyBinding::="key" VarNameAndType
ForEntryValueBinding::="value" VarNameAndType
ForExpr::=ForClauseForLetReturn
ForItemBinding::=VarNameAndTypePositionalVar? "in" ExprSingle
ForLetReturn::=ForExpr | LetExpr | ("return" ExprSingle)
ForMemberBinding::="member" VarNameAndTypePositionalVar? "in" ExprSingle
FullStep::=AxisNodeTest
FunctionBody::=EnclosedExpr
FunctionCall::=EQNameArgumentList
/* xgc: reserved-function-names */
/* gn: parens */
FunctionItemExpr::=NamedFunctionRef | InlineFunctionExpr
FunctionSignature::="(" ParamList ")" TypeDeclaration?
FunctionType::=AnyFunctionType
| TypedFunctionType
GeneralComp::="=" | "!=" | "<" | "<=" | ">" | ">="
GNodeType::="gnode" "(" ")"
IfExpr::="if" "(" Expr ")" (UnbracedActions | BracedAction)
InlineFunctionExpr::=MethodAnnotation* ("function" | "fn") FunctionSignature? FunctionBody
InstanceofExpr::=TreatExpr ("instance" "of" SequenceType)?
IntersectExceptExpr::=InstanceofExpr (("intersect" | "except") InstanceofExpr)*
ItemType::=RegularItemType | FunctionType | TypeName | ChoiceItemType
JNodeType::="jnode" "(" SequenceType? ")"
KeySpecifier::=NCName | IntegerLiteral | StringLiteral | VarRef | ParenthesizedExpr | LookupWildcard
KeywordArgument::=EQName ":=" Argument
KeywordArguments::=(KeywordArgument ++ ",")
LetArrayBinding::="$" "[" (VarNameAndType ++ ",") "]" TypeDeclaration? ":=" ExprSingle
LetBinding::=LetValueBinding | LetSequenceBinding | LetArrayBinding | LetMapBinding
LetClause::="let" (LetBinding ++ ",")
LetExpr::=LetClauseForLetReturn
LetMapBinding::="$" "{" (VarNameAndType ++ ",") "}" TypeDeclaration? ":=" ExprSingle
LetSequenceBinding::="$" "(" (VarNameAndType ++ ",") ")" TypeDeclaration? ":=" ExprSingle
LetValueBinding::=VarNameAndType ":=" ExprSingle
Literal::=NumericLiteral | StringLiteral | QNameLiteral
Lookup::="?" KeySpecifier
LookupExpr::=PostfixExprLookup
LookupWildcard::="*"
MapConstructor::="map"? "{" (MapConstructorEntry ** ",") "}"
MapConstructorEntry::=ExprSingle (":" ExprSingle)?
MappingArrowTarget::="=!>" ArrowTarget
MapType::=AnyMapType | TypedMapType
MethodAnnotation::="%method"
MultiplicativeExpr::=UnionExpr (("*" | "×" | "div" | "÷" | "idiv" | "mod") UnionExpr)*
NamedFunctionRef::=EQName "#" IntegerLiteral
/* xgc: reserved-function-names */
NamespaceNodeTest::="namespace-node" "(" ")"
NameTest::=EQName | Wildcard
NameTestUnion::=(NameTest ++ "|")
NodeComp::="is" | "is-not" | NodePrecedes | NodeFollows
NodeFollows::=">>" | "follows"
NodeKindTest::=DocumentTest
| ElementTest
| AttributeTest
| SchemaElementTest
| SchemaAttributeTest
| PITest
| CommentTest
| TextTest
| NamespaceNodeTest
| AnyNodeKindTest
NodePrecedes::="<<" | "precedes"
NodeTest::=UnionNodeTest | SimpleNodeTest
NumericLiteral::=IntegerLiteral | HexIntegerLiteral | BinaryIntegerLiteral | DecimalLiteral | DoubleLiteral
OccurrenceIndicator::="?" | "*" | "+"
/* xgc: occurrence-indicators */
OrExpr::=AndExpr ("or" AndExpr)*
OtherwiseExpr::=StringConcatExpr ("otherwise" StringConcatExpr)*
ParamList::=(VarNameAndType ** ",")
ParenthesizedExpr::="(" Expr? ")"
PathExpr::=AbsolutePathExpr
| RelativePathExpr
/* xgc: leading-lone-slash */
PipelineExpr::=ArrowExpr ("->" ArrowExpr)*
PITest::="processing-instruction" "(" (NCName | StringLiteral)? ")"
PositionalArgumentList::="(" PositionalArguments? ")"
PositionalArguments::=(Argument ++ ",")
PositionalVar::="at" VarName
PostfixExpr::=PrimaryExpr | FilterExpr | DynamicFunctionCall | LookupExpr | FilterExprAM
Predicate::="[" Expr "]"
PrimaryExpr::=Literal
| VarRef
| ParenthesizedExpr
| ContextValueRef
| FunctionCall
| FunctionItemExpr
| MapConstructor
| ArrayConstructor
| StringTemplate
| UnaryLookup
QNameLiteral::="#" EQName
QuantifiedExpr::=("some" | "every") (QuantifierBinding ++ ",") "satisfies" ExprSingle
QuantifierBinding::=VarNameAndType "in" ExprSingle
RangeExpr::=AdditiveExpr ("to" AdditiveExpr)?
RecordType::=AnyRecordType | TypedRecordType
RegularItemType::=AnyItemTest | NodeKindTest | GNodeType | JNodeType | MapType | ArrayType | RecordType | EnumerationType
RelativePathExpr::=StepExpr (("/" | "//") StepExpr)*
RestrictedDynamicCall::=(VarRef | ParenthesizedExpr | FunctionItemExpr | MapConstructor | ArrayConstructor) PositionalArgumentList
SchemaAttributeTest::="schema-attribute" "(" AttributeName ")"
SchemaElementTest::="schema-element" "(" ElementName ")"
Selector::=EQName | Wildcard | ("get" "(" Expr ")")
SequenceArrowTarget::="=>" ArrowTarget
SequenceType::=("empty-sequence" "(" ")")
| (ItemTypeOccurrenceIndicator?)
SimpleMapExpr::=PathExpr ("!" PathExpr)*
SimpleNodeTest::=TypeTest | Selector
SquareArrayConstructor::="[" (ExprSingle ** ",") "]"
StepExpr::=PostfixExpr | AxisStep
StringConcatExpr::=RangeExpr ("||" RangeExpr)*
StringTemplate::="`" (StringTemplateFixedPart | StringTemplateVariablePart)* "`"
/* ws: explicit */
StringTemplateFixedPart::=((Char - ('{' | '}' | '`')) | "{{" | "}}" | "``")*
/* ws: explicit */
StringTemplateVariablePart::=EnclosedExpr
/* ws: explicit */
TextTest::="text" "(" ")"
TreatExpr::=CastableExpr ("treat" "as" SequenceType)?
TypedArrayType::="array" "(" SequenceType ")"
TypeDeclaration::="as" SequenceType
TypedFunctionParam::=("$" EQName "as")? SequenceType
TypedFunctionType::=("function" | "fn") "(" (TypedFunctionParam ** ",") ")" "as" SequenceType
TypedMapType::="map" "(" ItemType "," SequenceType ")"
TypedRecordType::="record" "(" (FieldDeclaration ** ",") ExtensibleFlag? ")"
TypeName::=EQName
TypeTest::=RegularItemType | ("type" "(" SequenceType ")")
UnaryExpr::=("-" | "+")* ValueExpr
UnaryLookup::=Lookup
UnbracedActions::="then" ExprSingle "else" ExprSingle
UnionExpr::=IntersectExceptExpr (("union" | "|") IntersectExceptExpr)*
UnionNodeTest::="(" (SimpleNodeTest ++ "|") ")"
ValueComp::="eq" | "ne" | "lt" | "le" | "gt" | "ge"
ValueExpr::=SimpleMapExpr
VarName::="$" EQName
VarNameAndType::="$" EQNameTypeDeclaration?
VarRef::="$" EQName
Wildcard::="*"
| (NCName ":*")
| ("*:" NCName)
| (BracedURILiteral "*")
/* ws: explicit */
XPath::=Expr

A.1.2 Extra-grammatical Constraints

This section contains constraints on the EBNF productions, which are required to parse syntactically valid sentences. The notes below are referenced from the right side of the production, with the notation: /* xgc: <id> */.

Constraint: leading-lone-slash

A single slash may appear either as a complete path expression or as the first part of a path expression in which it is followed by a RelativePathExpr. In some cases, the next terminal after the slash is insufficient to allow a parser to distinguish these two possibilities: a * symbol or a keyword like union could be either an operator or a NameTest. For example, the expression /union/* could be parsed either as (/) union (/*) or as /child::union/child::* (the second interpretation is the one chosen).

The situation where / is followed by < is a little more complicated. In XPath, this is unambiguous: the < can only indicate one of the operators <, <=, or <<. In XQuery, however, it can also be the start of a direct constructor: specifically, a direct constructor for an element node, processing instruction node, or comment node. These constructs are identified by the tokenizer, independently of their syntactic context, as described in A.3 Lexical structure.

The rule adopted is as follows: if the terminal immediately following a slash can form the start of a RelativePathExpr, then the slash must be the beginning of a PathExpr, not the entirety of it.

The terminals that can form the start of a RelativePathExpr are: NCName, QName, URIQualifiedName, StringLiteral, NumericLiteral, Wildcard, and StringTemplate; plus @...*$???%([; and in XQuery StringConstructor and DirectConstructor.

A single slash may be used as the left-hand argument of an operator by parenthesizing it: (/) * 5. The expression 5 * /, on the other hand, is syntactically valid without parentheses.

Constraint: xml-version

The version of XML and XML Names (e.g. [XML 1.0] and [XML Names], or [XML 1.1] and [XML Names 1.1]) is implementation-defined. It is recommended that the latest applicable version be used (even if it is published later than this specification). The EBNF in this specification links only to the 1.0 versions. Note also that these external productions follow the whitespace rules of their respective specifications, and not the rules of this specification, in particular A.3.5.13.4.1 Default Whitespace Handling. Thus prefix : localname is not a syntactically valid lexical QName for purposes of this specification, just as it is not permitted in a XML document. Also, comments are not permissible on either side of the colon. Also extra-grammatical constraints such as well-formedness constraints must be taken into account.

Constraint: reserved-function-names

Unprefixed function names spelled the same way as language keywords could make the language impossible to parse. For instance, element(foo) could be taken either as a FunctionCall or as an ElementTest. Therefore, an unprefixed function name must not be any of the names in A.4 Reserved Function Names.

A function named if can be called by binding its namespace to a prefix and using the prefixed form: library:if(foo) instead of if(foo).

Constraint: occurrence-indicators

As written, the grammar in A XPath 4.0 Grammar is ambiguous for some forms using the "+", "?" and "*"OccurrenceIndicators. The ambiguity is resolved as follows: these operators are tightly bound to the SequenceType expression, and have higher precedence than other uses of these symbols. Any occurrence of "+", "?" or "*", that follows a sequence type is assumed to be an occurrence indicator, which binds to the last ItemType in the SequenceType.

Thus, 4 treat as item() + - 5 must be interpreted as (4 treat as item()+) - 5, taking the '+' as an occurrence indicator and the '-' as a subtraction operator. To force the interpretation of "+" as an addition operator (and the corresponding interpretation of the "-" as a unary minus), parentheses may be used: the form (4 treat as item()) + -5 surrounds the SequenceType expression with parentheses and leads to the desired interpretation.

function () as xs:string * is interpreted as function () as (xs:string *), not as (function () as xs:string) *. Parentheses can be used as shown to force the latter interpretation.

This rule has as a consequence that certain forms which would otherwise be syntactically valid and unambiguous are not recognized: in 4 treat as item() + 5, the "+" is taken as an OccurrenceIndicator, and not as an operator, which means this is not a syntactically valid expression.

A.1.3 Grammar Notes

This section contains general notes on the EBNF productions, which may be helpful in understanding how to interpret and implement the EBNF. These notes are not normative. The notes below are referenced from the right side of the production, with the notation: /* gn: <id> */.

Note:

grammar-note: parens

Lookahead is required to distinguish a FunctionCall from an EQName or keyword followed by a Comment. For example: address (: this may be empty :) may be mistaken for a call to a function named "address" unless this lookahead is employed. Another example is for (: whom the bell :) $tolls in 3 return $tolls, where the keyword "for" must not be mistaken for a function name.

grammar-note: comments

Comments are allowed everywhere that ignorable whitespace is allowed, and the Comment symbol does not explicitly appear on the right-hand side of the grammar (except in its own production). See A.3.5.13.4.1 Default Whitespace Handling.

A comment can contain nested comments, as long as all "(:" and ":)" patterns are balanced, no matter where they occur within the outer comment.

Note:

Lexical analysis may typically handle nested comments by incrementing a counter for each "(:" pattern, and decrementing the counter for each ":)" pattern. The comment does not terminate until the counter is back to zero.

Some illustrative examples:

  • (: commenting out a (: comment :) may be confusing, but often helpful :) is a syntactically valid Comment, since balanced nesting of comments is allowed.

  • "this is just a string :)" is a syntactically valid expression. However, (: "this is just a string :)" :) will cause a syntax error. Likewise, "this is another string (:" is a syntactically valid expression, but (: "this is another string (:" :) will cause a syntax error. It is a limitation of nested comments that literal content can cause unbalanced nesting of comments.

  • for (: set up loop :) $i in $x return $i is syntactically valid, ignoring the comment.

  • 5 instance (: strange place for a comment :) of xs:integer is also syntactically valid.

A.3 Lexical structure

Changes in 4.0  

  1. The rules for tokenization have been largely rewritten. In some cases the revised specification may affect edge cases that were handled in different ways by different 3.1 processors, which could lead to incompatible behavior.   [Issue 327 PR 519 30 May 2023]

This section describes how an XPath 4.0 text is tokenized prior to parsing.

All keywords are case sensitive. Keywords are not reserved—that is, any lexical QName may duplicate a keyword except as noted in A.4 Reserved Function Names.

Tokenizing an input string is a process that follows the following rules:

  • [Definition: An ordinary production rule is a production rule in A.1 EBNF that is not annotated ws:explicit.]

  • [Definition: A literal terminal is a token appearing as a string in quotation marks on the right-hand side of an ordinary production rule.]

    Note:

    Strings that appear in other production rules do not qualify. For example, BracedURILiteral does not quality because it appears only in URIQualifiedName, and "0x" does not qualify because it appears only in HexIntegerLiteral.

    The literal terminals in XPath 4.0 are: !!=#$()*+,...///::::=<<<<===!>=>>>=>>??[@[]{|||}×÷%method-->ancestorancestor-or-selfandarrayasatattributecastcastablechildcommentdescendantdescendant-or-selfdivdocument-nodeelementelseempty-sequenceenumeqeveryexceptfnfollowingfollowing-or-selffollowing-siblingfollowing-sibling-or-selffollowsforfunctiongegetgnodegtidivifininstanceintersectisis-notitemjnodekeyleletltmapmembermodnamespacenamespace-nodenenodeoforotherwiseparentprecedesprecedingpreceding-or-selfpreceding-siblingpreceding-sibling-or-selfprocessing-instructionrecordreturnsatisfiesschema-attributeschema-elementselfsometextthentotreattypeunionvalue

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

    The variable terminals in XPath 4.0 are: BinaryIntegerLiteralDecimalLiteralDoubleLiteralHexIntegerLiteralIntegerLiteralNCNameQNameStringLiteralStringTemplateURIQualifiedNameWildcard

  • [Definition: A complex terminal is a variable terminal whose production rule references, directly or indirectly, an ordinary production rule.]

    The complex terminals in XPath 4.0 are: StringTemplate

    Note:

    The significance of complex terminals is that at one level, a complex terminal is treated as a single token, but internally it may contain arbitrary expressions that must be parsed using the full EBNF grammar.

  • Tokenization is the process of splitting the supplied input string into a sequence of terminals, where each terminal is either a literal terminal or a variable terminal (which may itself be a complex terminal). Tokenization is done by repeating the following steps:

    1. Starting at the current position, skip any whitespace and comments.

    2. If the current position is not the end of the input, then return the longest literal terminal or variable terminal that can be matched starting at the current position, regardless whether this terminal is valid at this point in the grammar. If no such terminal can be identified starting at the current position, or if the terminal that is identified is not a valid continuation of the grammar rules, then a syntax error is reported.

      Note:

      Here are some examples showing the effect of the longest token rule:

      • The expression map{a:b} is a syntax error. Although there is a tokenization of this string that satisfies the grammar (by treating a and b as separate expressions), this tokenization does not satisfy the longest token rule, which requires that a:b is interpreted as a single QName.

      • The expression 10 div3 is a syntax error. The longest token rule requires that this be interpreted as two tokens ("10" and "div3") even though it would be a valid expression if treated as three tokens ("10", "div", and "3").

      • The expression $x-$y is a syntax error. This is interpreted as four tokens, ("$", "x-", "$", and "y").

      Note:

      The lexical production rules for variable terminals have been designed so that there is minimal need for backtracking. For example, if the next terminal starts with "0x", then it can only be either a HexIntegerLiteral or an error; if it starts with "`" (and not with "```") then it can only be a StringTemplate or an error.

      This convention, together with the rules for whitespace separation of tokens (see A.3.2 Terminal Delimitation) means that the longest-token rule does not normally result in any need for backtracking. For example, suppose that a variable terminal has been identified as a StringTemplate by examining its first few characters. If the construct turns out not to be a valid StringTemplate, an error can be reported without first considering whether there is some shorter token that might be returned instead.

  • Tokenization unambiguously identifies the boundaries of the terminals in the input, and this can be achieved without backtracking or lookahead. However, tokenization does not unambiguously classify each terminal. For example, it might identify the string "div" as a terminal, but it does not resolve whether this is the operator symbol div, or an NCName or QName used as a node test or as a variable or function name. Classification of terminals generally requires information about the grammatical context, and in some cases requires lookahead.

    Note:

    Operationally, classification of terminals may be done either in the tokenizer or the parser, or in some combination of the two. For example, according to the EBNF, the expression "parent::x" is made up of three tokens, "parent", "::", and "x". The name "parent" can be classified as an axis name as soon as the following token "::" is recognized, and this might be done either in the tokenizer or in the parser. (Note that whitespace and comments are allowed both before and after "::".)

  • In the case of a complex terminal, identifying the end of the complex terminal typically involves invoking the parser to process any embedded expressions. Tokenization, as described here, is therefore a recursive process. But other implementations are possible.

Note:

Previous versions of this specification included the statement: When tokenizing, the longest possible match that is consistent with the EBNF is used.

Different processors are known to have interpreted this in different ways. One interpretation, for example, was that the expression 10 div-3 should be split into four tokens (10, div, -, 3) on the grounds that any other tokenization would give a result that was inconsistent with the EBNF grammar. Other processors report a syntax error on this example.

This rule has therefore been rewritten in version 4.0. Tokenization is now entirely insensitive to the grammatical context; div-3 is recognized as a single token even though this results in a syntax error. For some implementations this may mean that expressions that were accepted in earlier releases are no longer accepted in 4.0.

A.3.3 Less-Than and Greater-Than Characters

The operator symbols <, <=, >, >=, <<, >>, =>, ->, =!>, and =?> have alternative representations using the characters U+FF1C (FULL-WIDTH LESS-THAN SIGN, ) and U+FF1E (FULL-WIDTH GREATER-THAN SIGN, ) in place of U+003C (LESS-THAN SIGN, <) and U+003E (GREATER-THAN SIGN, >) . The alternative tokens are respectively , <=, , >=, <<, >>, =>, and =!>. In order to avoid visual confusion these alternatives are not shown explicitly in the grammar.

This option is provided to improve the readability of XPath expressions embedded in XML-based host languages such as XSLT; it enables these operators to be depicted using characters that do not require escaping as XML entities or character references.

A.3.43.3 End-of-Line Handling

The host language must specify whether the XPath 4.0 processor normalizes all line breaks on input, before parsing, and if it does so, whether it uses the rules of [XML 1.0] or [XML 1.1].

Note:

XML-based host languages such as XSLT and XSD do not normalize line breaks at the XPath level, because it will already have been done by the host XML parser. Use of character or entity references suppresses normalization of line breaks, so the string literal &#x0D; written within an XSLT-hosted XPath expression represents a string containing a single U+000D (CARRIAGE RETURN) character.

A.3.4.13.3.1 XML 1.0 End-of-Line Handling

For [XML 1.0] processing, all of the following must be translated to a single U+000A (NEWLINE) :

  1. the two-character sequence U+000D (CARRIAGE RETURN) , U+000A (NEWLINE) ;

  2. any U+000D (CARRIAGE RETURN) character that is not immediately followed by U+000A (NEWLINE) .

A.3.4.23.3.2 XML 1.1 End-of-Line Handling

For [XML 1.1] processing, all of the following must be translated to a single U+000A (NEWLINE) character:

  1. the two-character sequence U+000D (CARRIAGE RETURN) , U+000A (NEWLINE) ;

  2. the two-character sequence U+000D (CARRIAGE RETURN) , U+0085 (NEXT LINE, NEL) ;

  3. the single character U+0085 (NEXT LINE, NEL) ;

  4. the single character U+2028 (LINE SEPARATOR) ;

  5. any U+000D (CARRIAGE RETURN) character that is not immediately followed by U+000A (NEWLINE) or U+0085 (NEXT LINE, NEL) .

A.3.53.4 Whitespace Rules

A.3.5.13.4.1 Default Whitespace Handling

[Definition: A whitespace character is any of the characters defined by [http://www.w3.org/TR/REC-xml/#NT-S].]

[Definition: 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.5.23.4.2 Explicit Whitespace Handling).] Ignorable whitespace characters are not significant to the semantics of an expression. Whitespace is allowed before the first terminal and after the last terminal of an XPath expression. Whitespace is allowed between any two terminals. Comments may also act as "whitespace" to prevent two adjacent terminals from being recognized as one. Some illustrative examples are as follows:

  • foo- foo results in a syntax error. "foo-" would be recognized as a QName.

  • foo -foo is syntactically equivalent to foo - foo, two QNames separated by a subtraction operator.

  • foo(: This is a comment :)- foo is syntactically equivalent to foo - foo. This is because the comment prevents the two adjacent terminals from being recognized as one.

  • foo-foo is syntactically equivalent to single QName. This is because "-" is a valid character in a QName. When used as an operator after the characters of a name, the "-" must be separated from the name, e.g. by using whitespace or parentheses.

  • 10div 3 results in a syntax error.

  • 10 div3 also results in a syntax error.

  • 10div3 also results in a syntax error.

A.3.5.23.4.2 Explicit Whitespace Handling

Explicit whitespace notation is specified with the EBNF productions, when it is different from the default rules, using the notation shown below. This notation is not inherited. In other words, if an EBNF rule is marked as /* ws: explicit */, the notation does not automatically apply to all the 'child' EBNF productions of that rule.

ws: explicit

/* ws: explicit */ means that the EBNF notation explicitly notates, with S or otherwise, where whitespace characters are allowed. In productions with the /* ws: explicit */ annotation, A.3.5.13.4.1 Default Whitespace Handling does not apply. Comments are not allowed in these productions except where the Comment non-terminal appears.

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

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

method

A method is a function item that has the annotation %method.

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 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 (such as enum("red")) is an anonymous atomic type derived from xs:string by restriction using an enumeration facet that permits only the value "red". 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:stringFO 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 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:dataFO 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 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.

I Change Log (Non-Normative)

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

    See 1 Introduction

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

    See 1 Introduction

  3. Setting the default namespace for elements and types to the special value ##any causes an unprefixed element name to act as a wildcard, matching by local name regardless of namespace.

    See 3.2.7.2 Element Types

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

    See 3.2.8.1 Function Types

  5. Record types are added as a new kind of ItemType, constraining the value space of maps.

    See 3.2.8.3 Record Types

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

    See 3.4.4 Function Coercion

  7. PR 1817 1853 

    An inline function may be annotated as a %method, giving it access to its containing map.

    See 4.5.6 Inline Function Expressions

    See 4.5.6.1 Methods

    See 4.13.3 Lookup Expressions

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

    See 4.8 Arithmetic Expressions

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

    See 4.10.1 Value Comparisons

  10. Operators such as < and > can use the full-width forms and to avoid the need for XML escaping.

    See 4.10.2 General Comparisons

  11. Operator is-not is introduced, as a complement to the operator is.

    See 4.10.3 GNode Comparisons

  12. Operators precedes and follows are introduced as synonyms for operators << and >>.

    See 4.10.3 GNode Comparisons

  13. The lookup operator ? can now be followed by a string literal, for cases where map keys are strings other than NCNames. It can also be followed by a variable reference.

    See 4.13.3 Lookup Expressions

  14. PR 1763 1830 

    The syntax on the right-hand side of an arrow operator has been relaxed; a dynamic function call no longer needs to start with a variable reference or a parenthesized expression, it can also be (for example) an inline function expression or a map or array constructor.

    See 4.20 Arrow Expressions

  15. The arrow operator => is now complemented by a “mapping arrow” operator =!> which applies the supplied function to each item in the input sequence independently.

    See 4.20.2 Mapping Arrow Expressions

  16. PR 1023 1128 

    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.

    See 3.4.4 Function Coercion

  17. A dynamic function call can now be applied to a sequence of functions, and in particular to an empty sequence. This makes it easier to chain a sequence of calls.

    See 4.5.3.1 Evaluating Dynamic Function Calls

  18. The syntax document-node(N), where N is a NameTestUnion, is introduced as an abbreviation for document-node(element(N)). For example, document-node(*) matches any well-formed XML document (as distinct from a document fragment).

    See 3.2.7 Node Types

  19. QName literals are new in 4.0.

    See 4.2.1.3 QName Literals

  20. Path expressions are extended to handle JNodes (found in trees of maps and arrays) as well as XNodes (found in trees representing parsed XML).

    See 4.6 Path Expressions

  21. PR 28 

    Multiple for and let clauses can be combined in an expression without an intervening return keyword.

    See 4.12.1 For Expressions

    See 4.12.2 Let Expressions

  22. PR 159 

    Keyword arguments are allowed on static function calls, as well as positional arguments.

    See 4.5.1.1 Static Function Call Syntax

  23. PR 202 

    The presentation of the rules for the subtype relationship between sequence types and item types has been substantially rewritten to improve clarity; no change to the semantics is intended.

    See 3.3 Subtype Relationships

  24. PR 230 

    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.

    See 2.4.5 Guarded Expressions

  25. PR 254 

    The term "function conversion rules" used in 3.1 has been replaced by the term "coercion rules".

    See 3.4 Coercion Rules

    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.

    See 3.4 Coercion Rules

  26. PR 284 

    Alternative syntax for conditional expressions is available: if (condition) { X }.

    See 4.14 Conditional Expressions

  27. PR 286 

    Element and attribute tests can include alternative names: element(chapter|section), attribute(role|class).

    See 3.2.7 Node Types

    The NodeTest in an AxisStep now allows alternatives: ancestor::(section|appendix)

    See 3.2.7 Node Types

    Element and attribute tests of the form element(N) and attribute(N) now allow N to be any NameTest, including a wildcard.

    See 3.2.7.2 Element Types

    See 3.2.7.3 Attribute Types

  28. PR 324 

    String templates provide a new way of constructing strings: for example `{$greeting}, {$planet}!` is equivalent to $greeting || ', ' || $planet || '!'

    See 4.9.2 String Templates

  29. PR 326 

    Support for higher-order functions is now a mandatory feature (in 3.1 it was optional).

    See 5 Conformance

  30. PR 344 

    A for member clause is added to FLWOR expressions to allow iteration over an array.

    See 4.12.1 For Expressions

  31. PR 368 

    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.

    See 2.2.2 Dynamic Context

  32. PR 433 

    Numeric literals can now be written in hexadecimal or binary notation; and underscores can be included for readability.

    See 4.2.1.1 Numeric Literals

  33. PR 519 

    The rules for tokenization have been largely rewritten. In some cases the revised specification may affect edge cases that were handled in different ways by different 3.1 processors, which could lead to incompatible behavior.

    See A.3 Lexical structure

  34. PR 521 

    New abbreviated syntax is introduced (focus function) for simple inline functions taking a single argument. An example is fn { ../@code }

    See 4.5.6 Inline Function Expressions

  35. PR 603 

    The rules for reporting type errors during static analysis have been changed so that a processor has more freedom to report errors in respect of constructs that are evidently wrong, such as @price/@value, even though dynamic evaluation is defined to return an empty sequence rather than an error.

    See 2.4.6 Implausible Expressions

    See 4.6.4.6 Implausible Axis Steps

  36. PR 606 

    Element and attribute tests of the form element(A|B) and attribute(A|B) are now allowed.

    See 3.2.7.2 Element Types

    See 3.2.7.3 Attribute Types

  37. PR 691 

    Enumeration types are added as a new kind of ItemType, constraining the value space of strings.

    See 3.2.6 Enumeration Types

  38. PR 728 

    The syntax record(*) is allowed; it matches any map.

    See 3.2.8.3 Record Types

  39. PR 815 

    The coercion rules now allow conversion in either direction between xs:hexBinary and xs:base64Binary.

    See 3.4 Coercion Rules

  40. PR 911 

    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.

    See 3.4 Coercion Rules

  41. PR 996 

    The value of a predicate in a filter expression can now be a sequence of integers.

    See 4.4 Filter Expressions

  42. PR 1031 

    An otherwise operator is introduced: A otherwise B returns the value of A, unless it is an empty sequence, in which case it returns the value of B.

    See 4.15 Otherwise Expressions

  43. PR 1071 

    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.

    See 4.13.1.1 Map Constructors

  44. PR 1131 

    A positional variable can be defined in a for expression.

    See 4.12.1 For Expressions

    The type of a variable used in a for expression can be declared.

    See 4.12.1 For Expressions

    The type of a variable used in a let expression can be declared.

    See 4.12.2 Let Expressions

  45. PR 1132 

    Choice item types (an item type allowing a set of alternative item types) are introduced.

    See 3.2.5 Choice Item Types

  46. PR 1163 

    Filter expressions for maps and arrays are introduced.

    See 4.13.4 Filter Expressions for Maps and Arrays

  47. PR 1181 

    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.

    See 2.2.1 Static Context

    If the default namespace for elements and types has the special value ##any, then an unprefixed name in a NameTest acts as a wildcard, matching names in any namespace or none.

    See 4.6.4.2 Node Tests

  48. PR 1197 

    The keyword fn is allowed as a synonym for function in function types, to align with changes to inline function declarations.

    See 3.2.8.1 Function Types

    In inline function expressions, the keyword function may be abbreviated as fn.

    See 4.5.6 Inline Function Expressions

  49. PR 1212 

    XPath 3.0 included empty-sequence and item as reserved function names, and XPath 3.1 added map and array. This was unnecessary since these names never appear followed by a left parenthesis at the start of an expression. They have therefore been removed from the list. New keywords introducing item types, such as record and enum, have not been included in the list.

    See A.4 Reserved Function Names

  50. PR 1217 

    Predicates in filter expressions for maps and arrays can now be numeric.

    See 4.13.4 Filter Expressions for Maps and Arrays

  51. PR 1249 

    A for key/value clause is added to FLWOR expressions to allow iteration over maps.

    See 4.12.1 For Expressions

  52. PR 1250 

    Several decimal format properties, including minus sign, exponent separator, percent, and per-mille, can now be rendered as arbitrary strings rather than being confined to a single character.

    See 2.2.1.2 Decimal Formats

  53. PR 1265 

    The rules regarding the document-uri property of nodes returned by the fn:collection function have been relaxed.

    See 2.2.2 Dynamic Context

  54. PR 1344 

    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.

    See 2.2.1 Static Context

    The static typing option has been dropped.

    See 2.3 Processing Model

    The static typing feature has been dropped.

    See 5 Conformance

  55. PR 1361 

    The term atomic value has been replaced by atomic item.

    See 2.1.3 Values

  56. PR 1384 

    If a type declaration is present, the supplied values in the input sequence are now coerced to the required type. Type declarations are now permitted in XPath as well as XQuery.

    See 4.16 Quantified Expressions

  57. PR 1496 

    The context value static type, which was there purely to assist in static typing, has been dropped.

    See 2.2.1 Static Context

  58. PR 1498 

    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.

    See 2.1 Terminology

    The EBNF notation has been extended to allow the constructs (A ++ ",") (one or more occurrences of A, comma-separated, and (A ** ",") (zero or more occurrences of A, comma-separated.

    See 2.1.1 Grammar Notation

    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.

    See A.1 EBNF

    See A.1.1 Notation

  59. PR 1501 

    The coercion rules now apply recursively to the members of an array and the entries in a map.

    See 3.4 Coercion Rules

  60. PR 1532 

    Four new axes have been defined: preceding-or-self, preceding-sibling-or-self, following-or-self, and following-sibling-or-self.

    See 4.6.4.1 Axes

  61. PR 1577 

    The syntax record() is allowed; the only thing it matches is an empty map.

    See 3.2.8.3 Record Types

  62. PR 1686 

    With the pipeline operator ->, the result of an expression can be bound to the context value before evaluating another expression.

    See 4.18 Pipeline operator

  63. PR 1696 

    Parameter names may be included in a function signature; they are purely documentary.

    See 3.2.8.1 Function Types

  64. PR 1703 

    Ordered maps are introduced.

    See 4.13.1 Maps

    The order of key-value pairs in the map constructor is now retained in the constructed map.

    See 4.13.1.1 Map Constructors

  65. PR 1874 

    The coercion rules now reorder the entries in a map when the required type is a record type.

    See 3.4 Coercion Rules

  66. PR 1898 

    The rules for subtyping of document node types have been refined.

    See 3.3.2.4.2 Subtyping Nodes: Document Nodes

  67. PR 1991 

    Named record types used in the signatures of built-in functions are now available as standard in the static context.

    See 2.2.1 Static Context

  68. PR 2026 

    The module feature is no longer an optional feature; processing of library modules is now required.

    See 5 Conformance

  69. PR 2031 

    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.

    See 2.1.3 Values

    JNodes are introduced

    See 3.2.9 Generalized Node Types

  70. PR 2055 

    Sequences, arrays, and maps can be destructured in a let expression to extract their components into multiple variables.

    See 4.12.2 Let Expressions

  71. PR 2094 

    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.

    See 4.13.1.1 Map Constructors

  72. PR 2115 

    This section describes and formalizes a convention that was already in use, but not explicitly stated, in earlier versions of the specification.

    See 2.1.2 Expression Names