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

XPath and XQuery Functions and Operators 4.0

W3C Editor's Draft 23 February 2026

This version:
https://qt4cg.org/specifications/xpath-functions-40/
Latest version of XPath and XQuery Functions and Operators 4.0:
https://qt4cg.org/specifications/xpath-functions-40/
Most recent Recommendation of XPath and XQuery Functions and Operators:
https://www.w3.org/TR/2017/REC-xpath-functions-31-20170321/
Editor:
Michael Kay, Saxonica <http://www.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: Specification in XML format and XML function catalog.


Abstract

This document defines constructor functions, operators, and functions on the datatypes defined in [XML Schema Part 2: Datatypes Second Edition] and the datatypes defined in [XQuery and XPath Data Model (XDM) 3.1]. It also defines functions and operators on nodes and node sequences as defined in the [XQuery and XPath Data Model (XDM) 3.1]. These functions and operators are defined for use in [XML Path Language (XPath) 4.0] and [XQuery 4.0: An XML Query Language] and [XSL Transformations (XSLT) Version 4.0] and other related XML standards. The signatures and summaries of functions defined in this document are available at: http://www.w3.org/2005/xpath-functions/.

A summary of changes since version 3.1 is provided at H Changes since 3.1.

Status of this Document

This version of the specification is work in progress. It is produced by the QT4 Working Group, officially the W3C XSLT 4.0 Extensions Community Group. Individual functions specified in the document may be at different stages of review, reflected in their History notes. Comments are invited, in the form of GitHub issues at https://github.com/qt4cg/qtspecs.

Dedication

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


2 Processing sequences

A sequence is an ordered collection of zero or more items. An item is a node, an atomic item, or a function, such as a map or an array. The terms sequence and item are defined formally in [XQuery 4.0: An XML Query Language] and [XML Path Language (XPath) 4.0].

2.5 Basic higher-order functions

The following functions take function items as an argument.

FunctionMeaning
fn:applyMakes a dynamic call on a function with an argument list supplied in the form of an array.
fn:do-untilProcesses a supplied value repeatedly, continuing when some condition is false, and returning the value that satisfies the condition.
fn:everyReturns true if every item in the input sequence matches a supplied predicate.
fn:filterReturns those items from the sequence $input for which the supplied function $predicate returns true.
fn:fold-leftProcesses the supplied sequence from left to right, applying the supplied function repeatedly to each item in turn, together with an accumulated result value.
fn:fold-rightProcesses the supplied sequence from right to left, applying the supplied function repeatedly to each item in turn, together with an accumulated result value.
fn:for-eachApplies the function item $action to every item from the sequence $input in turn, returning the concatenation of the resulting sequences in order.
fn:for-each-pairApplies the function item $action to successive pairs of items taken one from $input1 and one from $input2, returning the concatenation of the resulting sequences in order.
fn:highestReturns those items from a supplied sequence that have the highest value of a sort key, where the sort key can be computed using a caller-supplied function.
fn:index-whereReturns the positions in an input sequence of items that match a supplied predicate.
fn:lowestReturns those items from a supplied sequence that have the lowest value of a sort key, where the sort key can be computed using a caller-supplied function.
fn:partial-applyPerforms partial application of a function item by binding values to selected arguments.
fn:partitionPartitions a sequence of items into a sequence of non-empty arrays containing the same items, starting a new partition when a supplied condition is true.
fn:scan-leftProduces the sequence of successive partial results from the evaluation of fn:fold-left with the same arguments.
fn:scan-rightProduces the sequence of successive partial results from the evaluation of fn:fold-right with the same arguments.
fn:someReturns true if at least one item in the input sequence matches a supplied predicate.
fn:sortSorts a supplied sequence, based on the value of a sort key supplied as a function.
fn:sort-bySorts a supplied sequence, based on the value of a number of sort keys supplied as functions.
fn:sort-withSorts a supplied sequence, according to the order induced by the supplied comparator functions.
fn:subsequence-whereReturns a contiguous sequence of items from $input, with the start and end points located by applying predicates.
fn:take-whileReturns items from the input sequence prior to the first one that fails to match a supplied predicate.
fn:transitive-closureReturns all the GNodes reachable from a given start GNode by applying a supplied function repeatedly.
fn:while-doProcesses a supplied value repeatedly, continuing while some condition remains true, and returning the first value that does not satisfy the condition.

With all these functions, if the caller-supplied function fails with a dynamic error, this error is propagated as an error from the higher-order function itself.

2.5.19 fn:sort-with

Changes in 4.0  

  1. New in 4.0  [Issues 655 2012 PRs 795 2228 20 February 2024]

Summary

Sorts a supplied sequence, according to the order induced by the supplied comparator functions.

Signature
fn:sort-with(
$inputas item()*,
$comparatorsas (fn(item(), item()) as xs:integer)+
) as item()*
Properties

This function is deterministic, context-independent, and focus-independent.

Rules

Informally, the items of the supplied $input are sorted into an order based on the result of evaluating the supplied $comparators. The result is a sorted sequence.

Each comparator function takes two items and returns an xs:integer that defines the relationship between these items, following the conventions of the fn:compare function. Specifically, when a comparator $c is used to compare two items $a and $b, it must return a negative integer if $a is to be sorted before $b, zero if they are considered equal, and a positive integer if $a is to be sorted after $b.

There may be more than one comparator, representing sort keys in major to minor order. To determine the relative position of two items $a and $b:

  1. The first comparator is called: $comparators[1]($a, $b). If the result is non-zero, this determines the relative position of $a and $b in the result sequence, and any further comparators can be ignored.

  2. If the Nth comparator returns zero, then:

    1. If this is the last comparator, then the two items are considered equal, and their relative position in the result sequence will be the same as their relative position in the input sequence (that is, the sort is stable).

    2. Otherwise, the next comparator is evaluated, and so on, until the last comparator is reached or the result of a comparator is non-zero.

To ensure that the sorting algorithm produces predictable results (indeed, to ensure that it terminates), it is necessary for the comparators to have certain properties. Specifically, for every comparator C:

  1. C must be deterministic (if called twice with the same arguments, it must deliver the same result).

  2. C must be error-free (it can successfully process any pair of items from the input sequence).

  3. Every item must be equal to itself: C($a, $a) must be zero.

  4. The ordering must be consistent: if C($a, $b) < 0, then C($b, $a) > 0, and vice versa, and similarly, if C($a, $b) = 0, then C($b, $a) = 0.

  5. The ordering must be transitive: if C($a, $b) < 0 and C($b, $c) < 0, then C($a, $c) < 0.

Error Conditions

If a comparator function raises an error when processing any pair of items from the input sequence (for example, if the comparator function is fn:compare#2 and the two items are of non-comparable types), then the evaluation of fn:sort-with fails with that error.

In general it is unpredictable which pairs of items from the input sequence will actually be compared using each comparator function. However, a comparator function must not be called to compare two items if they have been determined as unequal by an earlier comparator function.

Examples
Expression:

sort-with((1, 4, 6, 5, 3), compare#2)

Result:

1, 3, 4, 5, 6

Expression:

sort-with((1, 4, 6, 5, 3), op('-'))

Result:

1, 3, 4, 5, 6

Expression:

sort-with((1, 4, 4e0, 6, 5, 3), fn($a, $b) { compare($b, $a) })

Result:

6, 5, 4, 4e0, 3, 1

Expression:
sort-with(
  (1, -2, 5, 10, -12, 8),
  fn($a, $b) { abs($a) - abs($b) }
)
Result:
1, -2, 5, 8, 10, -12
Expression:
let $persons := <persons>
  <person name='Josipa' age='8'/>
  <person name='Jade' age='6'/>
  <person name='Jie' age='8'/>
</persons>
return sort-with($persons/person, (
  fn($a, $b) { compare($a/@age, $b/@age) },
  fn($a, $b) { compare($a/@name, $b/@name) }
))
Result:
<person name="Jade" age="6"/>
<person name="Jie" age="8"/>
<person name="Josipa" age="8"/>

15 Processing arrays

Arrays were introduced as a new datatype in XDM 3.1. This section describes functions that operate on arrays.

An array is an additional kind of item. An array of size N is a mapping from the integers (1 to N) to a set of values, called the members of the array, each of which is an arbitrary sequence. Because an array is an item, and therefore a sequence, arrays can be nested.

An array acts as a function from integer positions to associated values, so the function call $array($index) can be used to retrieve the array member at a given position. The function corresponding to the array has the signature function($index as xs:integer) as item()*. The fact that an array is a function item allows it to be passed as an argument to higher-order functions that expect a function item as one of their arguments.

15.2 Functions that operate on arrays

The functions defined in this section use a conventional namespace prefix array, which is assumed to be bound to the namespace URI http://www.w3.org/2005/xpath-functions/array.

As with all other values, arrays are treated as immutable. For example, the array:reverse function returns an array that differs from the supplied array in the order of its members, but the supplied array is not changed by the operation. Two calls on array:reverse with the same argument will return arrays that are indistinguishable from each other; there is no way of asking whether these are “the same array”. Like sequences, arrays have no identity.

All functionality on arrays is defined in terms of two primitives:

  • The function array:members decomposes an array to a sequence of value records.

  • The function array:of-members composes an array from a sequence of value records.

A value record here is an item that encapsulates an arbitrary value; the representation chosen for a value record is record(value as item()*), that is, a map containing a single entry whose key is the string "value" and whose value is the encapsulated sequence.

Note that when the required type of an argument to a function such as array:build is an array type, then the coercion rules ensure that a JNode can be supplied in the function call: if the ·content· property of the JNode is an array, then the array is automatically extracted as if by the jnode-content function.

FunctionMeaning
array:appendReturns an array containing all the members of a supplied array, plus one additional member at the end.
array:buildReturns an array obtained by evaluating the supplied function once for each item in the input sequence.
array:emptyReturns true if the supplied array contains no members.
array:filterReturns an array containing those members of the $array for which $predicate returns true. A return value of () is treated as false.
array:flattenReplaces any array appearing in a supplied sequence with the members of the array, recursively.
array:fold-leftEvaluates the supplied function cumulatively on successive members of the supplied array.
array:fold-rightEvaluates the supplied function cumulatively on successive values of the supplied array.
array:footReturns the last member of an array.
array:for-eachReturns an array whose size is the same as array:size($array), in which each member is computed by applying $action to the corresponding member of $array.
array:for-each-pairReturns an array obtained by evaluating the supplied function once for each pair of members at the same position in the two supplied arrays.
array:getReturns the value at the specified position in the supplied array (counting from 1).
array:headReturns the first member of an array, that is $array(1).
array:index-ofReturns a sequence of positive integers giving the positions within the array $array of members that are equal to $target.
array:index-whereReturns the positions in an input array of members that match a supplied predicate.
array:insert-beforeReturns an array containing all the members of the supplied array, with one additional member at a specified position.
array:itemsReturns the sequence concatenation of the members of an array.
array:joinConcatenates the contents of several arrays into a single array, with an optional separator between adjacent members.
array:membersDelivers the contents of an array as a sequence of value records.
array:of-membersConstructs an array from the contents of a sequence of value records.
array:putReturns an array containing all the members of a supplied array, except for one member which is replaced with a new value.
array:removeReturns an array containing all the members of the supplied array, except for the members at specified positions.
array:reverseReturns an array containing all the members of a supplied array, but in reverse order.
array:sizeReturns the number of members in the supplied array.
array:sliceReturns an array containing selected members of a supplied input array based on their position.
array:sortSorts a supplied array, based on the value of a sort key supplied as a function.
array:sort-bySorts a supplied array, based on the value of a number of sort keys supplied as functions.
array:sort-withSorts a supplied array, according to the order induced by the supplied comparator functions.
array:splitDelivers the contents of an array as a sequence of single-member arrays.
array:subarrayReturns an array containing all members from a supplied array starting at a supplied position, up to a specified length.
array:tailReturns an array containing all members except the first from a supplied array.
array:trunkReturns an array containing all members except the last from a supplied array.

15.2.27 array:sort-with

Changes in 4.0  

  1. New in 4.0  [Issue 2012 PR 2228 3 October 2025]

Summary

Sorts a supplied array, according to the order induced by the supplied comparator functions.

Signature
array:sort-with(
$inputas array(*),
$comparatorsas (fn(item()*, item()*) as xs:integer)+
) as array(*)
Properties

This function is deterministic, context-independent, and focus-independent.

Rules

Informally, the members of the supplied $input array are sorted into an order based on the result of evaluating the supplied $comparators. The result is a sorted array.

Each comparator function takes two values and returns an xs:integer that defines the relationship between these values, following the conventions of the fn:compare function. Specifically, when a comparator $c is used to compare two values $a and $b, it must return a negative integer if $a is to be sorted before $b, zero if they are considered equal, and a positive integer if $a is to be sorted after $b.

There may be more than one comparator, representing sort keys in major to minor order. To determine the relative position of two members $a and $b:

  1. The first comparator is called: $comparators[1]($a, $b). If the result is non-zero, this determines the relative position of $a and $b in the result array, and any further comparators can be ignored.

  2. If the Nth comparator returns zero, then:

    1. If this is the last comparator, then the two members are considered equal, and their relative position in the result sequence will be the same as their relative position in the input sequence (that is, the sort is stable).

    2. Otherwise, the next comparator is evaluated, and so on, until the last comparator is reached or the result of a comparator is non-zero.

To ensure that the sorting algorithm produces predictable results (indeed, to ensure that it terminates), it is necessary for the comparators to have certain properties. Specifically, for every comparator C:

  1. C must be deterministic (if called twice with the same arguments, it must deliver the same result).

  2. C must be error-free (it can successfully process any pair of values from the input array).

  3. Every value must be equal to itself: C($a, $a) must be zero.

  4. The ordering must be consistent: if C($a, $b) < 0, then C($b, $a) > 0, and vice versa, and similarly, if C($a, $b) = 0, then C($b, $a) = 0.

  5. The ordering must be transitive: if C($a, $b) < 0 and C($b, $c) < 0, then C($a, $c) < 0.

Error Conditions

If a comparator function raises an error when processing any pair of members from the input array (for example, if the comparator function is fn:compare#2 and one of the members is not coercible to xs:anyAtomicType), then the evaluation of fn:sort-with fails with that error.

In general it is unpredictable which pairs of members from the input array will actually be compared using each comparator function. However, a comparator function must not be called to compare two members if they have been determined as unequal by an earlier comparator function.

Examples
Expression:

array:sort-with([1, 4, 6, 5, 3], compare#2)

Result:

[1, 3, 4, 5, 6]

Expression:

array:sort-with([1, 4, 6, 5, 3], op('-'))

Result:

[1, 3, 4, 5, 6]

Expression:

array:sort-with([1, 4, 4e0, 6, 5, 3], fn($a, $b) { compare($b, $a) })

Result:

[6, 5, 4, 4e0, 3, 1]

Expression:
array:sort-with(
  [{"a":1, "b":20}, {"a":5, "b":12}, {"a":1, "b":3}],
   ( fn($x, $y){ compare($x?a, $y?a) },
     fn($x, $y){ compare($x?b, $y?b) })  
)
Result:
[{"a":1, "b":3}, {"a":1, "b":20}, {"a":5, "b":12}]