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 18 February12 March 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/>

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) 4.0]. It also defines functions and operators on nodes and node sequences as defined in the [XQuery and XPath Data Model (XDM) 4.0]. 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 section describes the status of this document at the time of its publication. Other documents may supersede this document.

This document is a working draft developed and maintained by a W3C Community Group, the XQuery and XSLT Extensions Community Group unofficially known as QT4CG (where "QT" denotes Query and Transformation). This draft is work in progress and should not be considered either stable or complete. Standard W3C copyright and patent conditions apply.

The community group welcomes comments on the specification. Comments are best submitted as issues on the group's GitHub repository.

As the Community Group moves towards publishing dated, stable drafts, some features that the group thinks may likely be removed or substantially changed are marked “at risk” in their changes section. In this draft:

The community group maintains two extensive test suites, one oriented to XQuery and XPath, the other to XSLT. These can be found at qt4tests and xslt40-test respectively. New tests, or suggestions for correcting existing tests, are welcome. The test suites include extensive metadata describing the conditions for applicability of each test case as well as the expected results. They do not include any test drivers for executing the tests: each implementation is expected to provide its own test driver.

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.4 Aggregate functions

Aggregate functions take a sequence as argument and return a single value computed from values in the sequence. Except for fn:count, the sequence must consist of values of a single type or one if its subtypes, or they must be numeric. xs:untypedAtomic values are permitted in the input sequence and handled by special conversion rules. The type of the items in the sequence must also support certain operations.

FunctionMeaning
fn:countReturns the number of items in a sequence.
fn:all-equalReturns true if all items in a supplied sequence (after atomization) are contextually equal.
fn:all-differentReturns true if no two items in a supplied sequence are contextually equal.
fn:avgReturns the average of the values in the input sequence $values, that is, the sum of the values divided by the number of values.
fn:maxReturns a value that is greater than or equal to every other value appearing in the input sequence.
fn:minReturns a value that is less than or equal to every other value appearing in the input sequence.
fn:sumReturns a value obtained by adding together the values in $values.

2.4.2 fn:all-equal

Changes in 4.0 (next | previous)

  1. New in 4.0. Originally proposed under the name fn:uniform  [  20 September 2022]

Summary

Returns true if all items in a supplied sequence (after atomization) are contextually equal.

Signature
fn:all-equal(
$valuesas xs:anyAtomicType*,
$collationas xs:string?:= fn:default-collation()
) as xs:boolean
Properties

This function is deterministic, context-dependent, and focus-independent. It depends on collations.

Rules

Omitting the second argument, $collation, is equivalent to supplying fn:default-collation(). For more information on collations see 5.3.7 Choosing a collation.

The result of the function fn:all-equal($values, $collation) is true if and only if the result of fn:count(fn:distinct-values($values, $collation)) le 1 is true (that is, if the sequence is empty, or if all the items in the sequence are equal under the rules of the fn:distinct-values function).

Examples
Expression:

all-equal((1, 2, 3))

Result:

false()

Expression:

all-equal((1, 1.0, 1.0e0))

Result:

true()

Expression:

all-equal("one")

Result:

true()

Expression:

all-equal(())

Result:

true()

Expression:

all-equal((xs:float('NaN'), xs:double('NaN')))

Result:

true()

Expression:
all-equal(
  ("ABC", "abc"),
  "http://www.w3.org/2005/xpath-functions/collation/html-ascii-case-insensitive"
)
Result:
true()
Expression:

The expression fn:all-equal(//p/@class) returns true if all p elements have the same value for @class.

all-equal(//p/@class)

Result:
Returns true if all
                p elements have the same value for @class.
Expression:

The expression fn:all-equal(* ! fn:node-name()) returns true if all element children of the context node have the same name.

all-equal(* ! node-name())

Result:
Returns true if all
               element children of the context node have the same name.

2.4.3 fn:all-different

Changes in 4.0 (next | previous)

  1. New in 4.0. Originally proposed under the name fn:unique  [  20 September 2022]

Summary

Returns true if no two items in a supplied sequence are contextually equal.

Signature
fn:all-different(
$valuesas xs:anyAtomicType*,
$collationas xs:string?:= fn:default-collation()
) as xs:boolean
Properties

This function is deterministic, context-dependent, and focus-independent. It depends on collations.

Rules

Omitting the second argument, $collation, is equivalent to supplying fn:default-collation(). For more information on collations see 5.3.7 Choosing a collation.

The result of the function fn:all-different($values, $collation) is true if and only if the result of fn:count(fn:distinct-values($values, $collation)) eq fn:count($values) is true (that is, if the sequence is empty, or if all the items in the sequence are contextually unequal under the rules used by the fn:distinct-values function).

Examples
Expression:

all-different((1, 2, 3))

Result:

true()

Expression:

all-different((1, 1.0, 1.0e0))

Result:

false()

Expression:

all-different("one")

Result:

true()

Expression:

all-different(())

Result:

true()

Expression:
all-different(
  ("ABC", "abc"),
  "http://www.w3.org/2005/xpath-functions/collation/html-ascii-case-insensitive"
)
Result:
false()
Expression:

The expression fn:all-different(//employee/@ssn) is true if no two employees have the same value for their @ssn attribute.

Result:
Returns true if no two employees have the same value for their
            @ssn attribute.
Expression:

The expression fn:all-different(* ! fn:node-name()) returns true if all element children of the context node have distinct names.

Result:
Returns true if all
                  element children of the context node have distinct names.

2.4.4 fn:avg

Changes in 4.0 (next | previous)

  1. In 3.1, given a mixed input sequence such as (1, 3, 4.2e0), the specification was unclear whether it was permitted to add the first two integer items using integer arithmetic, rather than converting all items to doubles before performing any arithmetic. The 4.0 specification is clear that this is permitted; but since the items can be reordered before being added, this is not required.  [Issue 1682 PR 1734 27 January 2025]

Summary

Returns the average of the values in the input sequence $values, that is, the sum of the values divided by the number of values.

Signature
fn:avg(
$valuesas xs:anyAtomicType*
) as xs:anyAtomicType?
Properties

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

Rules

If $values is the empty sequence, the empty sequence is returned.

Any item in $values that is an instance of xs:untypedAtomic is cast to xs:double.

After this conversion, one of the following conditions must be true:

  1. Every item in $values is an instance of xs:yearMonthDuration.

  2. Every item in $values is an instance of xs:dayTimeDuration.

  3. Every item in $values is an instance of xs:numeric.

The function returns the average of the values as sum($values) div count($values); but the implementation may use an otherwise equivalent algorithm that avoids arithmetic overflow. Note that the fn:sum function allows the input sequence to be reordered, which may affect the result in edge cases when the sequence contains a mixture of different numeric types.

Error Conditions

A type error is raised [err:FORG0006] if the input sequence contains items of incompatible types, as described above.

Examples
Variables
let $d1 := xs:yearMonthDuration("P20Y")
let $d2 := xs:yearMonthDuration("P10M")
let $seq3 := (3, 4, 5)
ExpressionResult
avg($seq3)

4.0

(The result is of type xs:decimal.)

avg(($d1, $d2))

xs:yearMonthDuration("P10Y5M")

avg(())

()

avg((xs:float('INF'), xs:float('-INF')))

xs:float('NaN')

avg(($seq3, xs:float('NaN')))

xs:float('NaN')

fn:avg(($d1, $seq3))

fn:avg(($d1, $seq3)) raises a type error [err:FORG0006].

Raises error FORG0006.

2.4.5 fn:max

Changes in 4.0 (next | previous)

  1. The way that fn:min and fn:max compare numeric values of different types has changed. The most noticeable effect is that when these functions are applied to a sequence of xs:integer or xs:decimal values, the result is an xs:integer or xs:decimal, rather than the result of converting this to an xs:float or xs:double.  [Issue 866 PR 881 6 December 2023]

Summary

Returns a value that is greater than or equal to every other value appearing in the input sequence.

Signature
fn:max(
$valuesas xs:anyAtomicType*,
$collationas xs:string?:= fn:default-collation()
) as xs:anyAtomicType?
Properties

The one-argument form of this function is deterministic, context-dependent, and focus-independent. It depends on collations, and implicit timezone.

The two-argument form of this function is deterministic, context-dependent, and focus-independent. It depends on collations, and static base URI, and implicit timezone.

Rules

Any item in $values that is an instance of xs:untypedAtomic is first cast to xs:double. The resulting sequence is referred to as the converted sequence.

All pairs of values in the converted sequence must be mutually comparable. Two values A and B are mutually comparable if fn:compare(A, B) raises no error.

If the converted sequence is empty, the function returns the empty sequence.

If the converted sequence contains the value NaN, the value NaN is returned (as an xs:float or xs:double as appropriate).

Two items A and B from the converted sequence are compared by calling fn:compare(A, B, $collation), where $collation is determined by the rules in 5.3.7 Choosing a collation:

The result of the function is a value from the converted sequence that is greater than or equal to every other value under the above rules. If there is more than one such value, then it is implementation-dependent which of them is returned.

Error Conditions

A type error is raised [err:FORG0006] if the input sequence contains items of incompatible types, as described above.

Notes

If there are two or items that are “equal highest”, the specific item whose value is returned is implementation-dependent. This can arise for example if two different strings compare equal under the selected collation, or if two different xs:dateTime values compare equal despite being in different timezones.

If the converted sequence contains exactly one value then that value is returned.

The default type when the fn:max function is applied to xs:untypedAtomic values is xs:double. This differs from the default type for operators such as lt, and for sorting in XQuery and XSLT, which is xs:string.

In version 4.0, if $values is a sequence of xs:decimal values (including the case where it is a sequence of xs:integer values), then the result will be one of these xs:decimal or xs:integer values. In earlier versions it would be the result of converting this xs:decimal to xs:float or xs:double.

Examples
ExpressionResult
max((3, 2, 1))

3

max([ 3, 2, 1 ])

3

(Arrays are atomized).

max((
  xs:integer(5),
  xs:float(5),
  xs:double(0)
))

5

(The result may be either the xs:integer or the xs:float, since they are equal.)

max((
  xs:float(0.0E0),
  xs:float(-0.0E0)
))

xs:float(0.0e0)

(The result may be either positive or negative zero, since they are equal.)

max((
  current-date(),
  xs:date("2100-01-01")
))

xs:date("2100-01-01")

(Assuming that the current date is during the 21st century.)

max(("a", "b", "c"))

"c"

(Assuming a typical default collation.)

max((3, 4, "Zero"))

max((3, 4, "Zero")) raises a type error [err:FORG0006].

Raises error FORG0006.

2.4.6 fn:min

Changes in 4.0 (next | previous)

  1. The way that fn:min and fn:max compare numeric values of different types has changed. The most noticeable effect is that when these functions are applied to a sequence of xs:integer or xs:decimal values, the result is an xs:integer or xs:decimal, rather than the result of converting this to an xs:float or xs:double.  [Issue 866 PR 881 6 December 2023]

Summary

Returns a value that is less than or equal to every other value appearing in the input sequence.

Signature
fn:min(
$valuesas xs:anyAtomicType*,
$collationas xs:string?:= fn:default-collation()
) as xs:anyAtomicType?
Properties

The one-argument form of this function is deterministic, context-dependent, and focus-independent. It depends on collations, and implicit timezone.

The two-argument form of this function is deterministic, context-dependent, and focus-independent. It depends on collations, and static base URI, and implicit timezone.

Rules

Any item in $values that is an instance of xs:untypedAtomic is first cast to xs:double. The resulting sequence is referred to as the converted sequence.

All pairs of values in the converted sequence must be mutually comparable. Two values A and B are mutually comparable if fn:compare(A, B) raises no error.

If the converted sequence is empty, the function returns the empty sequence.

If the converted sequence contains the value NaN, the value NaN is returned (as an xs:float or xs:double as appropriate).

Two items A and B from the converted sequence are compared by calling fn:compare(A, B, $collation), where $collation is determined by the rules in 5.3.7 Choosing a collation:

The result of the function is a value from the converted sequence that is less than or equal to every other value under the above rules. If there is more than one such value, then it is implementation-dependent which of them is returned.

Error Conditions

A type error is raised [err:FORG0006] if the input sequence contains items of incompatible types, as described above.

Notes

If there are two or items that are “equal lowest”, the specific item whose value is returned is implementation-dependent. This can arise for example if two different strings compare equal under the selected collation, or if two different xs:dateTime values compare equal despite being in different timezones.

If the converted sequence contains exactly one value then that value is returned.

The default type when the fn:min function is applied to xs:untypedAtomic values is xs:double. This differs from the default type for operators such as lt, and for sorting in XQuery and XSLT, which is xs:string.

In version 4.0, if $values is a sequence of xs:decimal values (including the case where it is a sequence of xs:integer values), then the result will be one of these xs:decimal or xs:integer values. In earlier versions it would be the result of converting this xs:decimal to xs:float or xs:double.

Examples
ExpressionResult
min((3, 4, 5))

3

min([ 3, 4, 5 ])

3

(Arrays are atomized).

min((
  xs:integer(5),
  xs:float(5),
  xs:double(10)
))

5

(The result may be either the xs:integer or the xs:float, since they are equal.)

min((
  xs:float(0.0E0),
  xs:float(-0.0E0)
))

xs:float(0.0e0)

(The result may be either positive or negative zero, since they are equal.)

min((
  current-date(),
  xs:date("1900-01-01")
))

xs:date("1900-01-01")

(Assuming that the current date is set to a reasonable value.)

min(("a", "b", "c"))

"a"

(Assuming a typical default collation.)

min((3, 4, "Zero"))

min((3, 4, "Zero")) raises a type error [err:FORG0006].

Raises error FORG0006.

2.4.7 fn:sum

Changes in 4.0 (next | previous)

  1. In 3.1, given a mixed input sequence such as (1, 3, 4.2e0), the specification was unclear whether it was permitted to add the first two integer items using integer arithmetic, rather than converting all items to doubles before performing any arithmetic. The 4.0 specification is clear that this is permitted; but since the items can be reordered before being added, this is not required.  [Issue 1682 PR 1734 27 January 2025]

Summary

Returns a value obtained by adding together the values in $values.

Signature
fn:sum(
$valuesas xs:anyAtomicType*,
$zeroas xs:anyAtomicType?:= 0
) as xs:anyAtomicType?
Properties

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

Rules

Any value of type xs:untypedAtomic in $values is cast to xs:double. The items in the resulting sequence may be reordered in an arbitrary order. The resulting sequence is referred to below as the converted sequence.

If the converted sequence is empty, then the function returns the value of the argument $zero, which defaults to the xs:integer value 0.

In other cases the items in the converted sequence are added pairwise according the rules of the + operator.

Specifically, the result of the function is the value of the expression:

if (empty($c)) then $zero
else if (count($c) eq 1) then $c
else head($c) + sum(tail($c))

where $c is the converted sequence.

This has the effect that a type error will occur unless one of the following conditions is satisfied:

  1. Every item in $values is an instance of xs:yearMonthDuration.

  2. Every item in $values is an instance of xs:dayTimeDuration.

  3. Every item in $values is an instance of xs:numeric.

Error Conditions

A type error is raised [err:FORG0006] if the input sequence contains items of incompatible types, as described above.

Notes

The second argument allows an appropriate value to be defined to represent the sum of an empty sequence. For example, when summing a sequence of durations it would be appropriate to return a zero-length duration of the appropriate type. This argument is necessary because a system that does dynamic typing cannot distinguish “an empty sequence of integers", for example, from “an empty sequence of durations”.

The explicit or implicit value of the $zero argument is used only when the input sequence is empty, not when a non-empty sequence sums to zero. For example, sum((-1, +1), xs:double('NaN')) returns the xs:integer value 0, not NaN.

The sum of a sequence of integers will be an integer, while the sum of a numeric sequence that includes at least one xs:double will be an xs:double.

If the converted sequence contains exactly one value then that value is returned.

If the converted sequence contains the value NaN, NaN is returned.

In edge cases the fact that the input sequence may be reordered makes the result slightly unpredictable. For example, if the input contains two xs:decimal values and an xs:float, then the decimal values might be added using decimal arithmetic, or they might both be converted to xs:float (potentially losing precision) before any arithmetic is performed.

Examples
Variables
let $d1 := xs:yearMonthDuration("P20Y")
let $d2 := xs:yearMonthDuration("P10M")
let $seq1 := ($d1, $d2)
let $seq3 := (3, 4, 5)
Expression:

sum(($d1, $d2))

Result:

xs:yearMonthDuration("P20Y10M")

Expression:
sum(
  $seq1[. lt xs:yearMonthDuration('P3M')],
  xs:yearMonthDuration('P0M')
)
Result:
xs:yearMonthDuration("P0M")
Expression:

sum($seq3)

Result:

12

Expression:

sum(())

Result:

0

Expression:

sum((),())

Result:

()

Expression:

sum((1 to 100)[. lt 0], 0)

Result:

0

Expression:

sum(($d1, $d2), "ein Augenblick")

Result:

xs:yearMonthDuration("P20Y10M")

(There is no requirement that the $zero value should be the same type as the items in $value, or even that it should belong to a type that supports addition.)

Expression:

sum([ 1, 2, 3 ])

Result:

6

(Atomizing an array returns the sequence obtained by atomizing its members.)

Expression:

sum([ [ 1, 2 ], [ 3, 4 ] ])

Result:

10

(Atomizing an array returns the sequence obtained by atomizing its members.)

Expression:

fn:sum(($d1, 9E1)) raises a type error [err:FORG0006].

Result:

Raises error FORG0006.

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 a value that is greater than or equal to every other value appearing in the input sequence.
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.9 fn:highest

Changes in 4.0 (next | previous)

  1. New in 4.0  [  20 September 2022]

Summary

Returns a value that is greater than or equal to every other value appearing in the input sequence.

Signature
fn:highest(
$inputas item()*,
$collationas xs:string?:= fn:default-collation(),
$keyas (fn(item()) as xs:anyAtomicType*)?:= fn:data#1
) as item()*
Properties

This function is deterministic, context-dependent, and focus-independent. It depends on collations.

Rules

The second argument, $collation, defaults to ().

Supplying an empty sequence as $collation is equivalent to supplying fn:default-collation(). For more information on collations see 5.3.7 Choosing a collation.

The third argument, $key, defaults to the function data#1.

Let $modified-key be the function:

fn($item) {
  $key($item) => data() ! (
    if (. instance of xs:untypedAtomic) then xs:double(.) else .
  )
}

That is, the supplied function for computing key values is wrapped in a function that converts any xs:untypedAtomic values in its result to xs:double. This makes the function consistent with the behavior of fn:min and fn:max, but inconsistent with fn:sort, which treats untyped values as strings.

The result of the function is obtained as follows:

  • If the input is an empty sequence, the result is an empty sequence.

  • The input sequence is sorted, by applying the function fn:sort($input, $collation, $modified-key).

  • Let $C be the selected collation, or the default collation where applicable.

  • Let $B be the last item in the sorted sequence.

  • The function returns those items $A from the input sequence that are contextually equal to $B, retaining their order.

Error Conditions

If the set of computed keys contains xs:untypedAtomic values that are not castable to xs:double then the operation will fail with a dynamic error ([err:FORG0001]FO).

If the set of computed keys contains values that are not comparable using the lt operator then the sort operation will fail with a type error ([err:XPTY0004]XP).

Examples
Variables
let $e := <a x="10" y="5" z="2"/>
Expression:

highest($e/@*) ! name()

Result:

"x"

(By default, untyped values are compared as numbers.)

Expression:

highest($e/@*, (), string#1) ! name()

Result:

"y"

(Here, the attribute values are compared as strings.)

Expression:

highest(("red", "green", "blue"), (), string-length#1)

Result:

"green"

Expression:
highest(
  ("red", "green", "blue"),
  key := {
    "red"  : xs:hexBinary('FF0000'),
    "green": xs:hexBinary('008000'),
    "blue" : xs:hexBinary('0000FF')
  }
)
Result:
"red"
Expression:
highest(
  ("red", "orange", "yellow", "green", "blue", "indigo", "violet"),
  key := string-length#1
)
Result:
"orange", "yellow", "indigo", "violet"
Expression:

highest(1 to 25, (), fn { . idiv 10 })

Result:

20, 21, 22, 23, 24, 25

Expression:

highest(//employee, (), fn { xs:decimal(salary) })

Result:

To findThe employees having the highest salary: .

highest($employees, (), fn { xs:decimal(salary) })

2.5.11 fn:lowest

Changes in 4.0 (next | previous)

  1. New in 4.0  [  20 September 2022]

Summary

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

Signature
fn:lowest(
$inputas item()*,
$collationas xs:string?:= fn:default-collation(),
$keyas (fn(item()) as xs:anyAtomicType*)?:= fn:data#1
) as item()*
Properties

This function is deterministic, context-dependent, and focus-independent. It depends on collations.

Rules

The second argument, $collation, defaults to ().

Supplying the empty sequence as $collation is equivalent to supplying fn:default-collation(). For more information on collations see 5.3.7 Choosing a collation.

The third argument defaults to the function data#1.

Let $modified-key be the function:

fn($item) {
  $key($item) => data() ! (
    if (. instance of xs:untypedAtomic) then xs:double(.) else .
  )
}

That is, the supplied function for computing key values is wrapped in a function that converts any xs:untypedAtomic values in its result to xs:double. This makes the function consistent with the behavior of fn:min and fn:max, but inconsistent with fn:sort, which treats untyped values as strings.

The result of the function is obtained as follows:

  • If the input is the empty sequence, the result is the empty sequence.

  • The input sequence is sorted, by applying the function fn:sort($input, $collation, $modified-key).

  • Let $C be the selected collation, or the default collation where applicable.

  • Let $B be the first item in the sorted sequence.

  • The function returns those items $A from the input sequence that are contextually equal to $B, retaining their order.

Error Conditions

If the set of computed keys contains xs:untypedAtomic values that are not castable to xs:double then the operation will fail with a dynamic error ([err:FORG0001]FO).

If the set of computed keys contains values that are not comparable using the lt operator then the sort operation will fail with a type error ([err:XPTY0004]XP).

Examples
Variables
let $e := <a x="10" y="5" z="2"/>
Expression:

lowest($e/@*) ! name()

Result:

"z"

(By default, untyped values are compared as numbers.)

Expression:

lowest($e/@*, (), string#1) ! name()

Result:

"x"

(Here, the attribute values are compared as strings.)

Expression:

lowest(("red", "green", "blue"), (), string-length#1)

Result:

"red"

Expression:
lowest(
  ("red", "green", "blue"),
  key := {
    "red"  : xs:hexBinary('FF0000'),
    "green": xs:hexBinary('008000'),
    "blue" : xs:hexBinary('0000FF')
  }
)
Result:
"blue"
Expression:
lowest(
  ("April", "June", "July", "August"),
  key := string-length#1
)
Result:
"June", "July"
Expression:

lowest(1 to 25, (), fn { . idiv 10 })

Result:

1, 2, 3, 4, 5, 6, 7, 8, 9

Expression:

lowest(//employee, (), fn { xs:decimal(salary) })

Result:

To findThe employees having the lowest salary: .

lowest($employees, (), fn { xs:decimal(salary) })

2.5.17 fn:sort

Summary

Sorts a supplied sequence, based on the value of a sort key supplied as a function.

Signature
fn:sort(
$inputas item()*,
$collationas xs:string?:= fn:default-collation(),
$keyas fn(item()) as xs:anyAtomicType*:= fn:data#1
) as item()*
Properties

This function is deterministic, context-dependent, and focus-independent. It depends on collations.

Rules

This function is retained for compatibility from version 3.1 of this specification. Version 4.0 introduces two more powerful functions, fn:sort-by and fn:sort-with.

The function call fn:sort($input, $collation, $key) is defined to have the same effect as the call fn:sort-by($input, { 'key': $key, 'collation': $collation, 'order': 'ascending'}). See fn:sort-by.

The result of the function is a sequence that contains all the items from $input, typically in a different order, the order being defined by the supplied sort key definitions.

Formal Equivalent

The effect of the function is equivalent to the result of the following XPath expression.

fn:sort-by($input, { 'key':$key, 'collation':$collation, 'order':'ascending' })
Error Conditions

If the set of computed sort keys contains values that are not comparable using the lt operator then the sort operation will fail with a type error ([err:XPTY0004]XP).

Examples
Expression:

sort((1, 4, 6, 5, 3))

Result:

1, 3, 4, 5, 6

Expression:

sort((1, -2, 5, 10, -10, 10, 8), (), abs#1)

Result:

1, -2, 5, 8, 10, -10, 10

Expression:

To sort a set of strings $in using Swedish collation:

let $SWEDISH := collation({ 'lang': 'se' })
return sort(//name!string(), $SWEDISH)
Result:
let $SWEDISH := collation({ 'lang': 'se' })
return sort($in, $SWEDISH)
The names in //name sorted using Swedish collation.
Expression:

To sort a sequence of employees by last name as the major sort key and first name as the minor sort key, using the default collation:

sort(//employee, (), fn { name ! (last, first) })
Result:
sort($employees, (), fn { name ! (last, first) })
A sorted sequence of employees by last name as the major sort key and first name as the minor sort key,
               using the default collation.

2.5.18 fn:sort-by

Changes in 4.0 (next | previous)

  1. New in 4.0.  [Issue 1085 PR 2001 19 May 2025]

Summary

Sorts a supplied sequence, based on the value of a number of sort keys supplied as functions.

Signature
fn:sort-by(
$inputas item()*,
$keysas record(key? as (fn(item()) as xs:anyAtomicType*)?, collation? as xs:string?, order? as enum('ascending', 'descending')?)*
) as item()*
Properties

This function is deterministic, context-dependent, and focus-independent. It depends on collations.

Rules

The result of the function is a sequence that contains all the items from $input, typically in a different order, the order being defined by the supplied sort key definitions.

A sort key definition is a record with three parts:

  1. key: A sort key function, which is applied to each item in the input sequence to determine a sort key value. If no function is supplied, the default is fn:data#1, which atomizes the item.

  2. collation: A collation, which is used when comparing sort key values that are of type xs:string or xs:untypedAtomic. If no collation is supplied, the default collation from the static context is used.

    When comparing values of types other than xs:string or xs:untypedAtomic, the collation is ignored (but an error may be reported if it is invalid). For more information see 5.3.7 Choosing a collation.

  3. order: An order direction, either "ascending" or "descending". The default is "ascending".

The number of sort key definitions is determined by the number of records supplied in the $keys argument. If the argument is absent or empty, the default is a single sort key definition using the function data#1, using the default collation from the static context, and with order ascending.

The result of the fn:sort-by function is obtained as follows:

  1. The result sequence contains the same items as the input sequence $input, but generally in a different order.

  2. The sort key definitions are established as described above. The sort key definitions are in major-to-minor order. That is, the position of two items $A and $B in the result sequence is determined first by the relative magnitude of their primary sort key values, which are computed by evaluating the sort key function in the first sort key definition. If those two sort key values are equal, then the position is determined by the relative magnitude of their secondary sort key values, computed by evaluating the sort key function in the second sort key definition, and so on.

  3. When a pair of corresponding sort key values of $A and $B are found to be not equal, then $A precedes $B in the result sequence if both the following conditions are true, or if both conditions are false:

    1. The sort key value for $A is less than the sort key value for $B, as defined below.

    2. The order direction in the corresponding sort key definition is "ascending".

  4. If all the sort key values for $A and $B are pairwise equal, then $A precedes $B in the result sequence if and only if $A precedes $B in the input sequence.

    Note:

    That is, the sort is stable.

  5. Each sort key value for a given item is obtained by applying the sort key function of the corresponding sort key definition to that item. The result of this function is in the general case a sequence of atomic items. Two sort key values $a and $b are compared as follows:

    1. Let $C be the collation in the corresponding sort key definition.

    2. Let $REL be the result of evaluating op:lexicographic-compare($key($A), $key($B), $C) where op:lexicographic-compare($a, $b, $C) is defined as follows:

      if (empty($a) and empty($b)) then 0 
      else if (empty($a)) then -1
      else if (empty($b)) then +1
      else let $rel = op:simple-compare(head($a), head($b), $C)
           return if ($rel eq 0)
                  then op:lexicographic-compare(tail($a), tail($b), $C)
                  else $rel
    3. Here op:simple-compare($k1, $k2) is defined as follows:

      if ($k1 instance of (xs:string | xs:anyURI | xs:untypedAtomic)
          and $k2 instance of (xs:string | xs:anyURI | xs:untypedAtomic))
      then compare($k1, $k2, $C)
      else if ($k1 instance of xs:numeric and $k2 instance of xs:numeric)
      then compare($k1, $k2)
      else if ($k1 eq $k2) then 0
      else if ($k2 lt $k2) then -1
      else +1

      Note:

      This raises an error if two keys are not comparable, for example if one is a string and the other is a number, or if both belong to a non-ordered type such as xs:QName.

    4. If $REL is zero, then the two sort key values are deemed equal; if $REL is -1 then $a is deemed less than $b, and if $REL is +1 then $a is deemed greater than $b

Error Conditions

If the set of computed sort keys contains values that are not comparable using the lt operator then the sort operation will fail with a type error ([err:XPTY0004]XP).

Notes

The function is a generalization of the fn:sort function available in 3.1, which is retained for compatibility. The enhancements allow multiple sort keys to be defined, each potentially with a different collation, and allow sorting in descending order.

If the sort key for an item evaluates to the empty sequence, the effect of the rules is that this item precedes any value for which the key is non-empty. This is equivalent to the effect of the XQuery option empty least. The effect of the option empty greatest can be achieved by adding an extra sort key definition with { 'key': fn { empty(K(.) } }: when comparing boolean sort keys, false precedes true.

Examples
Expression:

sort-by((1, 4, 6, 5, 3), ())

Result:

1, 3, 4, 5, 6

Expression:

sort-by((1, 4, 4e0, 6, 5, 3), { 'order': 'descending' })

Result:

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

Expression:

sort-by((1, -2, 5, 10, -10, 10, 8), { 'key': abs#1 })

Result:

1, -2, 5, 8, 10, -10, 10

Expression:

To sort a set of strings $in using Swedish collation:

let $SWEDISH := collation({ 'lang': 'se' })
return sort-by($in, { 'collation': $SWEDISH })
let $SWEDISH := collation({ 'lang': 'se' })
return sort-by($in, { 'collation': $SWEDISH })
Result:

To sort a sequence of employees by last name as the major sort key and first name as the minor sort key, using the default collation:

The names in //name sorted using Swedish collation.
Expression:
sort-by($employees, { 'key': fn { name ! (last, first) } })
sort-by(//employee, { 'key': fn { name ! (last, first) } })
Result:

To sort a sequence of employees first by increasing last name (using Swedish collation order) and then by decreasing salary:

Sorts a sequence of employees by last name as the major sort key 
                  and first name as the minor sort key,
               using the default collation
Expression:
sort-by(
  $employees, 
  ({ 'key': fn { name/last }, 'collation': collation({ 'lang': 'se' }) },
   { 'key': fn { xs:decimal(salary) }, 'order': 'descending' }))
Result:
Sorts a sequence of employees first by increasing last name (using Swedish collation order)
               and then by decreasing salary

3 Processing booleans

This section defines functions and operators on the xs:boolean datatype.

3.2 Functions on Boolean values

The following functions are defined on boolean values:

FunctionMeaning
fn:booleanComputes the effective boolean value of the sequence $input.
fn:notReturns true if the effective boolean value of $input is false, or false if it is true.

3.2.1 fn:boolean

Summary

Computes the effective boolean value of the sequence $input.

Signature
fn:boolean(
$inputas item()*
) as xs:boolean
Rules

The function computes the effective boolean value of a sequence, defined according to the following rules. See also [XML Path Language (XPath) 4.0] section 2.6.4 Effective Boolean Value.

  • If $input is the empty sequence, fn:boolean returns false.

  • If $input is a sequence whose first item is a GNodeDM (a generalized node), fn:boolean returns true.

  • If $input is a singleton value of type xs:boolean or of a type derived from xs:boolean, fn:boolean returns $input.

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

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

Error Conditions

In all cases other than those listed above, fn:boolean raises a type error [err:FORG0006].

Notes

The result of this function is not necessarily the same as $input cast as xs:boolean. For example, fn:boolean("false") returns the value true whereas "false" cast as xs:boolean (which can also be written xs:boolean("false")) returns false.

Examples
Variables
let $abc := ("a", "b", "")
ExpressionResult
boolean($abc[1])

true()

boolean($abc[0])

false()

boolean($abc[3])

false()

fn:boolean($abc)

fn:boolean($abc) raises a type error [err:FORG0006].

Raises error FORG0006.

fn:boolean([])

fn:boolean([]) raises a type error [err:FORG0006].

Raises error FORG0006.

3.2.2 fn:not

Summary

Returns true if the effective boolean value of $input is false, or false if it is true.

Signature
fn:not(
$inputas item()*
) as xs:boolean
Properties

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

Rules

The value of $input is first reduced to an effective boolean value by applying the fn:boolean() function. The function returns true if the effective boolean value is false, or false if the effective boolean value is true.

Examples
ExpressionResult
not(true())

false()

not(())

true()

not("false")

false()

fn:not(1 to 10)

fn:not(1 to 10) raises a type error [err:FORG0006].

Raises error FORG0006.

4 Processing numerics

This section specifies arithmetic operators on the numeric datatypes defined in [XML Schema Part 2: Datatypes Second Edition].

4.6 Formatting integers

FunctionMeaning
fn:format-integerFormats an integer according to a given picture string, using the conventions of a given natural language if specified.

4.6.1 fn:format-integer

Changes in 4.0 (next | previous)

  1. The function has been extended to allow output in a radix other than 10, for example in hexadecimal.  [Issue 241 PR 434 7 April 2023]

Summary

Formats an integer according to a given picture string, using the conventions of a given natural language if specified.

Signature
fn:format-integer(
$valueas xs:integer?,
$pictureas xs:string,
$languageas xs:string?:= ()
) as xs:string
Properties

The two-argument form of this function is deterministic, context-dependent, and focus-independent. It depends on default language.

The three-argument form of this function is deterministic, context-independent, and focus-independent.

Rules

If $value is the empty sequence, the function returns a zero-length string.

In all other cases, the $picture argument describes the format in which $value is output.

The rules that follow describe how non-negative numbers are output. If the value of $value is negative, the rules below are applied to the absolute value of $value, and a minus sign is prepended to the result.

The value of $picture consists of the following, in order:

  1. An optional radix, which is an integer in the range 2 to 36, written using ASCII digits (0-9) without any leading zero;

  2. A circumflex (^), which is present if the radix is present, and absent otherwise.

    A circumflex is recognized as marking the presence of a radix only if (a) it is immediately preceded by an integer in the range 2 to 36, and (b) it is followed (somewhere within the primary format token) by an "X" or "x". In other cases, the circumflex is treated as a grouping separator. For example, the picture 9^000 outputs the number 2345 as "2^345", whereas 9^XXX outputs "3185". This rule is to ensure backwards compatibility.

  3. A primary format token. This is always present and must not be zero-length.

  4. An optional format modifier.

    If the string contains one or more semicolons then the last semicolon is taken as terminating the primary format token, and everything that follows is taken as the format modifier; if the string contains no semicolon then the format modifier is taken to be absent (which is equivalent to supplying a zero-length string).

If a radix is present, then the primary format token must follow the rules for a digit-pattern.

The primary format token is classified as one of the following:

  1. A digit-pattern made up of optional-digit-signs, mandatory-digit-signs, and grouping-separator-signs.

    • The optional-digit-sign is the character #.

    • If the radix is absent, then a mandatory-digit-sign is a character in Unicode category Nd. All mandatory-digit-signs within the format token must be from the same digit family, where a digit family is a sequence of ten consecutive characters in Unicode category Nd, having digit values 0 through 9. Within the format token, these digits are interchangeable: a three-digit number may thus be indicated equivalently by 000, 001, or 999.

      If the primary format token contains at least one Unicode digit, then the primary format token is taken as a decimal digit pattern, and in this case it must match the regular expression ^((\p{Nd}|#|[^\p{N}\p{L}])+?)$. If it contains a digit but does not match this pattern, a dynamic error is raised [err:FODF1310].

    • If the radix (call it R) is present (including the case where an explicit radix of 10 is used), then the character used as the mandatory-digit-sign is either "x" or "X". If any mandatory-digit-sign is upper-case "X", then all mandatory-digit-signs must be upper-case "X". The digit family used in the output comprises the first R characters of the alphabet 0123456789abcdefghijklmnopqrstuvwxyz, but using upper-case letters in place of lower-case if an upper-case "X" is used as the mandatory-digit-sign.

      In this case the primary format token must match the regular expression ^(([Xx#]|[^\p{N}\p{L}])+?)$

    • a grouping-separator-sign is a non-alphanumeric character, that is a character whose Unicode category is other than Nd, Nl, No, Lu, Ll, Lt, Lm or Lo.

    Note:

    If a semicolon is to be used as a grouping separator, then the primary format token as a whole must be followed by another semicolon, to ensure that the grouping separator is not mistaken as a separator between the primary format token and the format modifier.

    There must be at least one mandatory-digit-sign. There may be zero or more optional-digit-signs, and (if present) these must precede all mandatory-digit-signs. There may be zero or more grouping-separator-signs. A grouping-separator-signmust not appear at the start or end of the digit-pattern, nor adjacent to another grouping-separator-sign.

    The corresponding output is a number in the specified radix, using this digit family, with at least as many digits as there are mandatory-digit-signs in the format token. Thus:

    • A format token 1 generates the sequence 0 1 2 ... 10 11 12 ...

    • A format token 01 (or equivalently, 00 or 99) generates the sequence 00 01 02 ... 09 10 11 12 ... 99 100 101

    • A format token of U+0661 (ARABIC-INDIC DIGIT ONE, ١) generates the sequence ١ then ٢ then ٣ ...

    • A format token of 16^xx generates the sequence 00 01 02 03 ... 08 09 0a 0b 0c 0d 0e 0f 10 11 ...

    • A format token of 16^X generates the sequence 0 1 2 3 ... 8 9 A B C D E F 10 11 ...

    The grouping-separator-signs are handled as follows:

    1. The position of grouping separators within the format token, counting backwards from the last digit, indicates the position of grouping separators to appear within the formatted number, and the character used as the grouping-separator-sign within the format token indicates the character to be used as the corresponding grouping separator in the formatted number.

    2. More specifically, the position of a grouping separator is the number of optional-digit-signs and mandatory-digit-signs appearing between the grouping separator and the right-hand end of the primary format token.

    3. Grouping separators are defined to be regular if the following conditions apply:

      1. There is at least one grouping separator.

      2. Every grouping separator is the same character (call it C).

      3. There is a positive integer G (the grouping size) such that:

        1. The position of every grouping separator is an integer multiple of G, and

        2. Every positive integer multiple of G that is less than the number of optional-digit-signs and mandatory-digit-signs in the primary format token is the position of a grouping separator.

    4. The grouping separator template is a (possibly infinite) set of (position, character) pairs.

    5. If grouping separators are regular, then the grouping separator template contains one pair of the form (n×G, C) for every positive integer n where G is the grouping size and C is the grouping character.

    6. Otherwise (when grouping separators are not regular), the grouping separator template contains one pair of the form (P, C) for every grouping separator found in the primary formatting token, where C is the grouping separator character and P is its position.

    7. Note:

      If there are no grouping separators, then the grouping separator template is the empty set.

    The number is formatted as follows:

    1. Let S1 be the result of formatting the supplied number in the appropriate radix: for radix 10 this will be the value obtained by casting it to xs:string.

    2. Let S2 be the result of padding S1 on the left with as many leading zeroes as are needed to ensure that it contains at least as many digits as the number of mandatory-digit-signs in the primary format token.

    3. Let S3 be the result of replacing all decimal digits (0-9) in S2 with the corresponding digits from the selected digit family. (This has no effect when the selected digit family uses ASCII digits (0-9), which will always be the case if a radix is specified.)

    4. Let S4 be the result of inserting grouping separators into S3: for every (position P, character C) pair in the grouping separator template where P is less than the number of digits in S3, insert character C into S3 at position P, counting from the right-hand end.

    5. Let S5 be the result of converting S4 into ordinal form, if an ordinal modifier is present, as described below.

    6. The result of the function is then S5.

  2. The format token A, which generates the sequence A B C ... Z AA AB AC....

  3. The format token a, which generates the sequence a b c ... z aa ab ac....

  4. The format token i, which generates the sequence i ii iii iv v vi vii viii ix x ....

  5. The format token I, which generates the sequence I II III IV V VI VII VIII IX X ....

  6. The format token w, which generates numbers written as lower-case words, for example in English, one two three four ...

  7. The format token W, which generates numbers written as upper-case words, for example in English, ONE TWO THREE FOUR ...

  8. The format token Ww, which generates numbers written as title-case words, for example in English, One Two Three Four ...

  9. Any other format token, which indicates a numbering sequence in which that token represents the number 1 (one) (but see the note below). It is implementation-defined which numbering sequences, additional to those listed above, are supported. If an implementation does not support a numbering sequence represented by the given token, it must use a format token of 1.

    Note:

    In some traditional numbering sequences additional signs are added to denote that the letters should be interpreted as numbers, for example, in ancient Greek U+0374 (DEXIA KERAIA, ʹ) and sometimes U+0375 (ARISTERI KERAIA, ͵) . These should not be included in the format token.

For all format tokens other than a digit-pattern, there may be implementation-defined lower and upper bounds on the range of numbers that can be formatted using this format token; indeed, for some numbering sequences there may be intrinsic limits. For example, the format token U+2460 (CIRCLED DIGIT ONE, ) has a range imposed by the Unicode character repertoire — zero to 20 in Unicode versions prior to 3.2, or zero to 50 in subsequent versions. For the numbering sequences described above any upper bound imposed by the implementation must not be less than 1000 (one thousand) and any lower bound must not be greater than 1. Numbers that fall outside this range must be formatted using the format token 1.

The above expansions of numbering sequences for format tokens such as a and i are indicative but not prescriptive. There are various conventions in use for how alphabetic sequences continue when the alphabet is exhausted, and differing conventions for how roman numerals are written (for example, IV versus IIII as the representation of the number 4). Sometimes alphabetic sequences are used that omit letters such as i and o. This specification does not prescribe the detail of any sequence other than those sequences consisting entirely of decimal digits.

Many numbering sequences are language-sensitive. This applies especially to the sequence selected by the tokens w, W, and Ww. It also applies to other sequences, for example different languages using the Cyrillic alphabet use different sequences of characters, each starting with the letter U+0410 (CYRILLIC CAPITAL LETTER A, А) . In such cases, the $language argument specifies which language conventions are to be used. If the argument is specified, the value should be either the empty sequence or a value that would be valid for the xml:lang attribute (see [Extensible Markup Language (XML) 1.0 (Fifth Edition)]). Note that this permits the identification of sublanguages based on country codes (from ISO 3166-1) as well as identification of dialects and regions within a country.

The set of languages for which numbering is supported is implementation-defined. If the $language argument is absent, or is set to the empty sequence, or is invalid, or is not a language supported by the implementation, then the number is formatted using the default language from the dynamic context.

The format modifier must be a string that matches the regular expression ^([co](\(.+\))?)?[at]?$. That is, if it is present it must consist of one or more of the following, in order:

  • either c or o, optionally followed by a sequence of characters enclosed between parentheses, to indicate cardinal or ordinal numbering respectively, the default being cardinal numbering

  • either a or t, to indicate alphabetic or traditional numbering respectively, the default being implementation-defined.

If the o modifier is present, this indicates a request to output ordinal numbers rather than cardinal numbers. For example, in English, when used with the format token 1, this outputs the sequence 1st 2nd 3rd 4th ..., and when used with the format token w outputs the sequence first second third fourth ....

The string of characters between the parentheses, if present, is used to select between other possible variations of cardinal or ordinal numbering sequences. The interpretation of this string is implementation-defined. No error occurs if the implementation does not define any interpretation for the defined string.

It is implementation-defined what combinations of values of the format token, the language, and the cardinal/ordinal modifier are supported. If ordinal numbering is not supported for the combination of the format token, the language, and the string appearing in parentheses, the request is ignored and cardinal numbers are generated instead.

The use of the a or t modifier disambiguates between numbering sequences that use letters. In many languages there are two commonly used numbering sequences that use letters. One numbering sequence assigns numeric values to letters in alphabetic sequence, and the other assigns numeric values to each letter in some other manner traditional in that language. In English, these would correspond to the numbering sequences specified by the format tokens a and i. In some languages, the first member of each sequence is the same, and so the format token alone would be ambiguous. In the absence of the a or t modifier, the default is implementation-defined.

Error Conditions

A dynamic error is raised [err:FODF1310] if the format token is invalid, that is, if it violates any mandatory rules (indicated by an emphasized must or required keyword in the above rules). For example, the error is raised if the primary format token contains a digit but does not match the required regular expression.

Notes
  1. Note the careful distinction between conditions that are errors and conditions where fallback occurs. The principle is that an error in the syntax of the format picture will be reported by all processors, while a construct that is recognized by some implementations but not others will never result in an error, but will instead cause a fallback representation of the integer to be used.

  2. The following notes apply when a digit-pattern is used:

    1. If grouping-separator-signs appear at regular intervals within the format token, then the sequence is extrapolated to the left, so grouping separators will be used in the formatted number at every multiple of N. For example, if the format token is 0'000 then the number one million will be formatted as 1'000'000, while the number fifteen will be formatted as 0'015.

    2. The only purpose of optional-digit-signs is to mark the position of grouping-separator-signs. For example, if the format token is #'##0 then the number one million will be formatted as 1'000'000, while the number fifteen will be formatted as 15. A grouping separator is included in the formatted number only if there is a digit to its left, which will only be the case if either (a) the number is large enough to require that digit, or (b) the number of mandatory-digit-signs in the format token requires insignificant leading zeros to be present.

    3. Grouping separators are not designed for effects such as formatting a US telephone number as (365)123-9876. In general they are not suitable for such purposes because (a) only single characters are allowed, and (b) they cannot appear at the beginning or end of the number.

    4. Numbers will never be truncated. Given the digit-pattern01, the number three hundred will be output as 300, despite the absence of any optional-digit-sign.

  3. The following notes apply when ordinal numbering is selected using the o modifier.

    In some languages, the form of numbers (especially ordinal numbers) varies depending on the grammatical context: they may have different genders and may decline with the noun that they qualify. In such cases the string appearing in parentheses after the letter c or o may be used to indicate the variation of the cardinal or ordinal number required.

    The way in which the variation is indicated will depend on the conventions of the language.

    For inflected languages that vary the ending of the word, the approach recommended in the previous version of this specification was to indicate the required ending, preceded by a hyphen: for example in German, appropriate values might be o(-e), o(-er), o(-es), o(-en).

    Another approach, which might usefully be adopted by an implementation based on the open-source ICU localization library [ICU], or any other library making use of the Unicode Common Locale Data Repository [Unicode CLDR], is to allow the value in parentheses to be the name of a registered numbering rule set for the language in question, conventionally prefixed with a percent sign: for example, o(%spellout-ordinal-masculine), or c(%spellout-cardinal-year).

  4. The following notes apply when the primary format token is neither a digit-pattern nor one of the seven other defined format tokens (A, a, i, I, w, W, Ww), but is an arbitrary token representing the number 1:

    Unexpected results may occur for traditional numbering. For example, in an implementation that supports traditional numbering system in Greek, the example format-integer(19, "α;t") might return δπιιιι or ιθ, depending upon whether the ancient acrophonic or late antique alphabetic system is supported.

    Unexpected results may also occur for alphabetic numbering. For example, in an implementation that supports alphabetic numbering system in Greek, someone writing format-integer(19, "α;a") might expect the nineteenth Greek letter, U+03C4 (GREEK SMALL LETTER TAU, τ) , but the implementation might return the eighteenth one, U+03C3 (GREEK SMALL LETTER SIGMA, σ) , because the latter is the nineteenth item in the sequence of lowercase Greek letters in Unicode (the sequence is interrupted because of the final form of the sigma, U+03C2 (GREEK SMALL LETTER FINAL SIGMA, ς) ). Because Greek never had a final capital sigma, Unicode has marked U+03A2, the eighteenth codepoint in the sequence of Greek capital letters, as reserved, to ensure that every Greek uppercase letter is always 32 codepoints less than its lowercase counterpart. Therefore, someone writing format-integer(18, "Α;a") might expect the eighteenth Greek capital letter, U+03A3 (GREEK CAPITAL LETTER SIGMA, Σ) , but an implementation might return U+03A2, the eighteenth position in the sequence of Greek capital letters, but unassigned to any character.

Examples
ExpressionResult
Expression:

format-integer(123, '0000')

Result:
format-integer(123, '0000')

"0123"

format-integer(123, 'w') might return "one hundred and twenty-three"

format-integer(123, 'w')
Depending on the default language, the expression might return
               the string "one hundred and twenty-three"

Ordinal numbering in Italian: The specification "1;o(-º)" with $language equal to it, if supported, should produce the sequence:

1º 2º 3º 4º ...

The specification "Ww;o" with $language equal to it, if supported, should produce the sequence:

Primo Secondo Terzo Quarto Quinto ...
Expression:

format-integer(21, '1;o', 'en')

Result:
format-integer(21, '1;o', 'en')

"21st"

format-integer(14, 'Ww;o(-e)', 'de')

format-integer(14, 'Ww;o(-e)', 'de')If supported, might return the string "Vierzehnte".

Expression:

format-integer(7, 'a')

1 to 10 ! format-integer(., "1;o(-º)", language:="it")
This requests ordinal numbering in Italian: if supported, 
                  this should produce the sequence: 1º 2º 3º 4º ...
1 to 10 ! format-integer(., "Ww;o", language:="it")
This requests ordinal numbering in Italian, spelled out
                  as words: if supported, 
                  this should produce the sequence: Primo Secondo Terzo Quarto Quinto ...
Result:
format-integer(7, 'a')

"g"

Expression:

format-integer(27, 'a')

Result:
format-integer(27, 'a')

"aa"

Expression:

format-integer(57, 'I')

Result:
format-integer(57, 'I')

"LVII"

Expression:

format-integer(1234, '#;##0;')

Result:
format-integer(1234, '#;##0;')

"1;234"

Expression:

format-integer(1234, '16^xxxx')

Result:
format-integer(1234, '16^xxxx')

"04d2"

Expression:

format-integer(1234, '16^X')

Result:
format-integer(1234, '16^X')

"4D2"

Expression:

format-integer(12345678, '16^xxxx_xxxx')

Result:
format-integer(12345678, '16^xxxx_xxxx')

"00bc_614e"

Expression:

format-integer(12345678, '16^#_xxxx')

Result:
format-integer(12345678, '16^#_xxxx')

"bc_614e"

Expression:

format-integer(255, '2^xxxx xxxx')

Result:
format-integer(255, '2^xxxx xxxx')

"1111 1111"

Expression:

format-integer(1023, '32^XXXX')

Result:
format-integer(1023, '32^XXXX')

"00VV"

Expression:

format-integer(1023, '10^XXXX')

Result:
format-integer(1023, '10^XXXX')

"1023"

Expression:

format-integer(1023, '10^00')

Result:
format-integer(1023, '10^00')

"10^23"

Expression:

format-integer(-5, '001')

Result:
format-integer(-5, '001')

"-005"

Expression:

format-integer(-5, 'a')

Result:
format-integer(-5, 'a')

"-e"

Expression:

format-integer(-12, '16^XX')

Result:
format-integer(-12, '16^XX')

"-0C"

4.8 Trigonometric and exponential functions

The functions in this section perform trigonometric and other mathematical calculations on xs:double values. They are provided primarily for use in applications performing geometrical computation, for example when generating SVG graphics.

Functions are provided to support the six most commonly used trigonometric calculations: sine, cosine, and tangent, and their inverses arc sine, arc cosine, and arc tangent. Other functions such as secant, cosecant, and cotangent are not provided because they are easily computed in terms of these six.

The functions in this section (with the exception of math:pi) are specified by reference to [IEEE 754-2019], where they appear as Recommended operations in section 9. IEEE defines these functions for a variety of floating point formats; this specification defines them only for xs:double values. The IEEE specification applies with the following caveats:

  1. IEEE states that the preferred quantum is language-defined. In this specification, it is implementation-defined.

  2. IEEE states that certain functions should raise the inexact exception if the result is inexact. In this specification, this exception if it occurs does not result in an error. Any diagnostic information is outside the scope of this specification.

  3. IEEE defines various rounding algorithms for inexact results, and states that the choice of rounding direction, and the mechanisms for influencing this choice, are language-defined. In this specification, the rounding direction and any mechanisms for influencing it are implementation-defined.

  4. Certain operations (such as taking the square root of a negative number) are defined in IEEE to signal the invalid operation exception and return a quiet NaN. In this specification, such operations return NaN and do not raise an error. The same policy applies to operations (such as taking the logarithm of zero) that raise a divide-by-zero exception. Any diagnostic information is outside the scope of this specification.

  5. Operations whose mathematical result is greater than the largest finite xs:double value are defined in IEEE to signal the overflow exception; operations whose mathematical result is closer to zero than the smallest non-zero xs:double value are similarly defined in IEEE to signal the underflow exception. The treatment of these exceptions in this specification is defined in 4.2 Arithmetic operators on numeric values.

FunctionMeaning
math:piReturns an approximation to the mathematical constant π.
math:eReturns an approximation to the mathematical constant e.
math:acosReturns the arc cosine of the argument.
math:asinReturns the arc sine of the argument.
math:atanReturns the arc tangent of the argument.
math:atan2Returns the angle in radians subtended at the origin by the point on a plane with coordinates (x, y) and the positive x-axis.
math:cosReturns the cosine of the argument. The argument is an angle in radians.
math:coshReturns the hyperbolic cosine of the argument.
math:expReturns the value of ex where x is the argument value.
math:exp10Returns the value of 10x, where x is the supplied argument value.
math:logReturns the natural logarithm of the argument.
math:log10Returns the base-ten logarithm of the argument.
math:powReturns the result of raising the first argument to the power of the second.
math:sinReturns the sine of the argument. The argument is an angle in radians.
math:sinhReturns the hyperbolic sine of the argument.
math:sqrtReturns the non-negative square root of the argument.
math:tanReturns the tangent of the argument. The argument is an angle in radians.
math:tanhReturns the hyperbolic tangent of the argument.

4.8.1 math:pi

Summary

Returns an approximation to the mathematical constant π.

Signature
math:pi() as xs:double
Properties

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

Rules

This function returns the xs:double value whose lexical representation is 3.141592653589793e0

Examples
ExpressionResult
2 * math:pi()

6.283185307179586e0

The expression 60 * (math:pi() div 180) converts an angle of 60 degrees to radians.

60 * (math:pi() div 180)
Converts an angle of 60 degrees
               to radians.

4.9 Random Numbers

FunctionMeaning
fn:random-number-generatorReturns a random number generator, which can be used to generate sequences of random numbers.

The function makes use of the record structure defined in the next section.

4.9.2 fn:random-number-generator

Changes in 4.0 (next | previous)

  1. The 3.1 specification suggested that every value in the result range should have the same chance of being chosen. This has been corrected to say that the distribution should be arithmetically uniform (because there are as many xs:double values between 0.01 and 0.1 as there are between 0.1 and 1.0).

Summary

Returns a random number generator, which can be used to generate sequences of random numbers.

Signature
fn:random-number-generator(
$seedas xs:anyAtomicType?:= ()
) as random-number-generator-record
Properties

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

Rules

The function returns a random number generator. A random number generator is represented as a value of type random-number-generator-record, defined in 4.9.1 Record fn:random-number-generator-record.

Calling the fn:random-number-generator function with no arguments is equivalent to calling the single-argument form of the function with an implementation-dependent seed.

Calling the fn:random-number-generator function with the empty sequence as $seed is equivalent to calling the single-argument form of the function with an implementation-dependent seed.

If a $seed is supplied, it may be an atomic item of any type.

Both forms of the function are deterministic: calling the function twice with the same arguments, within a single execution scope, produces the same results.

The value of the number entry should be such that the distribution of numbers is uniform: for example, the probability of the number being in the range 0.1e0 to 0.2e0 is the same as the probability of its being in the range 0.8e0 to 0.9e0.

The function returned in the permute entry should be such that all permutations of the supplied sequence are equally likely to be chosen.

The map returned by the fn:random-number-generator function may contain additional entries beyond those specified here, but it must match the record type defined above. The meaning of any additional entries is implementation-defined. To avoid conflict with any future version of this specification, the keys of any such entries should start with an underscore character.

Notes

It is not meaningful to ask whether the functions returned in the next and permute functions resulting from two separate calls with the same seed are “the same function”, but the functions must be equivalent in the sense that calling them produces the same sequence of random numbers.

The repeatability of the results of function calls in different execution scopes is outside the scope of this specification. It is recommended that when the same seed is provided explicitly, the same random number sequence should be delivered even in different execution scopes; while if no seed is provided, the processor should choose a seed that is likely to be different from one execution scope to another. (The same effect can be achieved explicitly by using fn:current-dateTime() as a seed.)

The specification does not place strong conformance requirements on the actual randomness of the result; this is left to the implementation. It is desirable, for example, when generating a sequence of random numbers that the sequence should not get into a repeating loop; but the specification does not attempt to dictate this.

Examples

The following example returns a random permutation of the integers in the range 1 to 100:

Expression:

random-number-generator()?permute(1 to 100)

Result:

The following example returns a 10% sample of the items in an input sequence $seq, chosen at random:

A random permutation of the integers in the range
               1 to 100
Expression:

random-number-generator()?permute($seq)[1 to (count($seq) idiv 10)]

Result:

A 10% sample of the items in an input sequence $seq, chosen at random

The following XQuery code produces a random sequence of 200 xs:double values in the range zero to one:

declare %public function local:random-sequence($length as xs:integer) as xs:double* {
  local:random-sequence($length, random-number-generator())
};
declare %private function local:random-sequence(
  $length as xs:integer, 
  $record as record(number as xs:double, next as fn(*))
) as xs:double* {
  if ($length != 0) {
    $record?number,
    local:random-sequence($length - 1, $record?next())
  }
};
local:random-sequence(200)

An equivalent result can be achieved with fn:fold-left:

tail(fold-left(
  (1 to 200),
  random-number-generator(),
  fn($result) { head($result) ! (?next(), ?number), tail($result) }
))

5 Processing strings

This section specifies functions and operators on the [XML Schema Part 2: Datatypes Second Edition]xs:string datatype and the datatypes derived from it.

5.3 Comparison of strings

FunctionMeaning
fn:codepoint-equalReturns true if two strings are equal, considered codepoint-by-codepoint.
fn:collationConstructs a collation URI with requested properties.
fn:collation-availableAsks whether a collation URI is recognized by the implementation, and whether it has required properties.
fn:collation-keyGiven a string value and a collation, generates an internal value called a collation key, with the property that the matching and ordering of collation keys reflects the matching and ordering of strings under the specified collation.
fn:contains-tokenDetermines whether or not any of the supplied strings, when tokenized at whitespace boundaries, contains the supplied token, under the rules of the supplied collation.

5.3.9 fn:collation

Changes in 4.0 (next | previous)

  1. New in 4.0  [Issue 1091 PR 1093 9 April 2024]

Summary

Constructs a collation URI with requested properties.

Signature
fn:collation(
$optionsas map(*)
) as xs:string
Properties

This function is deterministic, context-dependent, and focus-independent. It depends on collations.

Rules

The function is supplied with a map defining the properties required of the collation, and returns a collation URI with these properties.

Specifically, it returns a string in the form of a URI with the scheme and path http://www.w3.org/2013/collation/UCA followed by an optional query part. The query part is absent if options is empty. Otherwise it consists of a question mark followed by a sequence of one or more semicolon-separated parameters. Each parameter is a keyword-value pair, the keyword and value being separated by an equals sign. There is one keyword-value pair for each entry in the options map: the keyword is the same as the string value of the key in the map, and the value is the string value of the corresponding value, except where the value is of type xs:boolean, in which case true and false are translated to yes and no.

The function does not check whether the implementation actually recognizes the resulting collation URI: that can be achieved using the fn:collation-available function.

The properties available are as defined for the Unicode Collation Algorithm (see 5.3.4 The Unicode Collation Algorithm). Additional implementation-defined properties may be specified as described in the rules for UCA collation URIs.

The option parameter conventions apply, except as regards the handling of options not defined in this specification. Specifically:

  • If the option key is of type xs:string, xs:anyURI, or xs:untypedAtomic then it is converted to a string, and produces a URI query parameter which is handled as described in 5.3.4 The Unicode Collation Algorithm.

  • If the option key is of any other type then the function fails with a type error [err:XPTY0004]XP.

The following options are defined:

record(
fallback?as xs:boolean,
lang?as xs:language,
version?as xs:string,
strength?as enum("primary", "secondary", "tertiary", "quaternary", "identical", "1", "2", "3", "4", "5"),
maxVariable?as enum("space", "punct", "symbol", "currency"),
alternate?as enum("non-ignorable", "shifted", "blanked", "currency"),
backwards?as xs:boolean,
normalization?as xs:boolean,
caseLevel?as xs:boolean,
caseFirst?as enum("upper","lower"),
numeric?as xs:boolean,
reorder?as xs:string
)
KeyMeaning

fallback?

See 5.3.4 The Unicode Collation Algorithm.
  • Type: xs:boolean

  • Default: true

lang?

See 5.3.4 The Unicode Collation Algorithm.
  • Type: xs:language

  • Default: default-language()

version?

See 5.3.4 The Unicode Collation Algorithm.
  • Type: xs:string

  • Default: ()

strength?

See 5.3.4 The Unicode Collation Algorithm.
  • Type: enum("primary", "secondary", "tertiary", "quaternary", "identical", "1", "2", "3", "4", "5")

  • Default: ()

maxVariable?

See 5.3.4 The Unicode Collation Algorithm.
  • Type: enum("space", "punct", "symbol", "currency")

  • Default: "punct"

alternate?

See 5.3.4 The Unicode Collation Algorithm.
  • Type: enum("non-ignorable", "shifted", "blanked", "currency")

  • Default: "non-ignorable"

backwards?

See 5.3.4 The Unicode Collation Algorithm.
  • Type: xs:boolean

  • Default: false

normalization?

See 5.3.4 The Unicode Collation Algorithm.
  • Type: xs:boolean

  • Default: false

caseLevel?

See 5.3.4 The Unicode Collation Algorithm.
  • Type: xs:boolean

  • Default: false

caseFirst?

See 5.3.4 The Unicode Collation Algorithm.
  • Type: enum("upper","lower")

  • Default: "lower"

numeric?

See 5.3.4 The Unicode Collation Algorithm.
  • Type: xs:boolean

  • Default: false

reorder?

See 5.3.4 The Unicode Collation Algorithm.
  • Type: xs:string

  • Default: ""

Error Conditions

A type error is raised [err:XPTY0004]XP if options includes an entry whose key is not of type xs:string, xs:anyURI, or xs:untypedAtomic, or whose corresponding value is not castable to xs:string.

Examples
Expression:

collation({})

Result:

"http://www.w3.org/2013/collation/UCA"

Expression:

collation({ 'lang': 'de' })

Result:

"http://www.w3.org/2013/collation/UCA?lang=de"

Expression:

collation({ 'lang': 'de', 'strength': 'primary' })

Result:

"http://www.w3.org/2013/collation/UCA?lang=de;strength=primary"

(The order of query parameters may vary.)

Expression:

The expression collation({ 'lang': default-language() }) returns a collation suitable for the default language in the dynamic context.

Result:
A collation suitable for the default language in the
               dynamic context.

5.3.10 fn:collation-available

Changes in 4.0 (next | previous)

  1. New in 4.0  [Issue 1160 PR 1262 9 July 2024]

Summary

Asks whether a collation URI is recognized by the implementation, and whether it has required properties.

Signature
fn:collation-available(
$collationas xs:string,
$usageas enum('compare', 'key', 'substring')*:= ()
) as xs:boolean
Properties

This function is deterministic, context-dependent, and focus-independent. It depends on collations.

Rules

The first argument is a candidate collation URI.

The second argument establishes the intended usage of the collation URI. The value is a sequence containing zero or more of the following:

  • compare indicates that the intended purpose of the collation URI is to compare strings for equality or ordering, for example in functions such as fn:index-of, fn:deep-equal, fn:compare, and fn:sort.

  • key indicates that the intended purpose of the collation URI is to obtain collation keys for strings using the fn:collation-key function.

  • substring indicates that the intended purpose of the collation URI is to establish whether one string is a substring of another, for example in functions such as fn:contains or fn:starts-with.

The function returns true if and only if the implementation recognizes the candidate collation URI as one that can be used for each of the purposes listed in the $usage argument. If the $usage argument is absent or set to the empty sequence, the function returns true only if the collation is available for all purposes.

Notes

If the candidate collation is a UCA collation specifying fallback=yes, then this function will always return true: implementations are required to recognize such a collation and use fallback behavior if there is no direct equivalent available.

Examples
Expression:

collation-available("http://www.w3.org/2013/collation/UCA?lang=de")

Result:

true()

Expression:

collation({ 'lang': 'de' }) => collation-available()

Result:

true()

Expression:

The expression collation({ 'lang': default-language() }) returns a collation suitable for the default language in the dynamic context.

Result:
A collation suitable for the default language in the
               dynamic context.

9 Processing dates and times

This section defines operations on the [XML Schema Part 2: Datatypes Second Edition] date and time types.

See [Working With Timezones] for a disquisition on working with date and time values with and without timezones.

9.7 Adjusting timezones on dates and times

FunctionMeaning
fn:adjust-dateTime-to-timezoneAdjusts an xs:dateTime value to a specific timezone, or to no timezone at all.
fn:adjust-date-to-timezoneAdjusts an xs:date value to a specific timezone, or to no timezone at all; the result is the date in the target timezone that contains the starting instant of the supplied date.
fn:adjust-time-to-timezoneAdjusts an xs:time value to a specific timezone, or to no timezone at all.
fn:civil-timezoneReturns the timezone offset from UTC that is in conventional use at a given place and time.

These functions adjust the timezone component of an xs:dateTime, xs:date or xs:time value. The $timezone argument to these functions is defined as an xs:dayTimeDuration but must be a valid timezone value.

9.7.4 fn:civil-timezone

Changes in 4.0 (next | previous)

  1. New in 4.0  [Issue 1539 PR 1545 5 November 2024]

Summary

Returns the timezone offset from UTC that is in conventional use at a given place and time.

Signature
fn:civil-timezone(
$valueas xs:dateTime,
$placeas xs:string?:= ()
) as xs:dayTimeDuration
Properties

The one-argument form of this function is deterministic, context-dependent, and focus-independent. It depends on default place.

The two-argument form of this function is deterministic, context-independent, and focus-independent.

Rules

This function uses a database of civil timezones (including daylight savings time) to return the timezone offset for a given date/time and place. For example, the timezone offset for New York on 31 December 2024 would be -PT5H.

If the $place argument is omitted or empty then the default placeXP from the dynamic context is used.

If the supplied $value has no timezone then the implicit timezone from the dynamic context is used. This is unrelated to the timezone applicable to the requested $place.

The intended use of the $place argument is to identify the place where an event represented by the $value argument took place or will take place. The value must be an IANA timezone name as defined in the IANA timezone database [IANA Timezone Database]. Examples are "America/New_York" and "Europe/Rome".

The result of the function is the civil timezone offset applicable to the given date/time and place, as determined by the IANA timezone database or an alternative authoritative source.

Error Conditions

A dynamic error is raised [err:FODT0004] if no timezone information is available for the given date/time and place. This includes the case where the given place is not present in the timezone database, and also the case where the information available for that place does not cover a sufficient range of dates.

Examples
Expression:
civil-timezone(
  xs:dateTime('2024-12-31T23:59:59'), 'America/New_York')
Result:
xs:dayTimeDuration('-PT5H')
Expression:
civil-timezone(
  xs:dateTime('2024-06-30T23:59:59'), 'America/New_York')
Result:
xs:dayTimeDuration('-PT4H')
Expression:

The expression:

adjust-dateTime-to-timezone(
  current-dateTime(),
  civil-timezone(current-dateTime(), 'America/New_York')
)
Result:
adjust-dateTime-to-timezone(
  current-dateTime(),
  civil-timezone(current-dateTime(), 'America/New_York')
)
The current civil date and time in New York.

returns the current civil date and time in New York.

Expression:

If the default place is a location in the same timezone as (say) Paris, then the expression

civil-timezone(xs:dateTime('2024-07-01T09:00:00'))

Result:
civil-timezone(xs:dateTime('2024-07-01T09:00:00'))
If the default place is a location in the same timezone 
                  as (say) Paris, then PT2H

returns PT2H.

10 Processing QNames and NOTATIONS

10.1 Functions to create a QName

In XPath 4.0, statically-known QNames can be expressed using a QName literal such as #xml:space. Where the QName is not known statically, the xs:QName constructor function can be used.

In addition to the xs:QName constructor function, QName values can be constructed by combining a namespace URI, prefix, and local name, or by resolving a lexical QName against the in-scope namespaces of an element node. This section defines functions that perform these operations. Leading and trailing whitespace, if present, is stripped from string arguments before the result is constructed.

FunctionMeaning
fn:QNameReturns an xs:QName value formed using a supplied namespace URI and lexical QName.
fn:parse-QNameReturns an xs:QName value formed by parsing an EQName.
fn:resolve-QNameReturns an xs:QName value (that is, an expanded-QName) by taking an xs:string that has the lexical form of an xs:QName (a string in the form "prefix:local-name" or "local-name") and resolving it using the in-scope namespaces for a given element.

10.1.1 fn:QName

Summary

Returns an xs:QName value formed using a supplied namespace URI and lexical QName.

Signature
fn:QName(
$urias xs:string?,
$qnameas xs:string
) as xs:QName
Properties

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

Rules

The namespace URI in the returned QName is taken from $uri. If $uri is the zero-length string or the empty sequence, it represents “no namespace”.

The prefix (or absence of a prefix) in $qname is retained in the returned xs:QName value.

The local name in the result is taken from the local part of $qname.

Error Conditions

A dynamic error is raised [err:FOCA0002] if $qname does not have the correct lexical form for an instance of xs:QName.

A dynamic error is raised [err:FOCA0002] if $uri is the zero-length string or the empty sequence, and the value of $qname contains a colon (:).

A dynamic error may be raised [err:FOCA0002] if $uri is not a valid URI (XML Namespaces 1.0) or IRI (XML Namespaces 1.1).

Examples
ExpressionResult
QName("http://www.example.com/example", "person")

fn:QName("http://www.example.com/example", "person") returns an xs:QName with namespace URI "http://www.example.com/example", local name "person" and prefix "".

#Q{http://www.example.com/example}person

QName("http://www.example.com/example", "ht:person")

fn:QName("http://www.example.com/example", "ht:person") returns an xs:QName with namespace URI "http://www.example.com/example", local name "person" and prefix "ht".

#Q{http://www.example.com/example}ht:person

10.1.3 fn:resolve-QName

Summary

Returns an xs:QName value (that is, an expanded-QName) by taking an xs:string that has the lexical form of an xs:QName (a string in the form "prefix:local-name" or "local-name") and resolving it using the in-scope namespaces for a given element.

Signature
fn:resolve-QName(
$valueas xs:string?,
$elementas element()
) as xs:QName?
Properties

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

Rules

If $value is the empty sequence, returns the empty sequence.

More specifically, the function searches the namespace bindings of $element for a binding whose name matches the prefix of $value, or the zero-length string if it has no prefix, and returns an expanded-QName whose local name is taken from the supplied $value, and whose namespace URI is taken from the string value of the namespace binding.

If the $value has no prefix, and there is no namespace binding for $element corresponding to the default (unnamed) namespace, then the resulting expanded-QName has no namespace part.

The prefix (or absence of a prefix) in the supplied $value argument is retained in the returned expanded-QName, as described in [XQuery and XPath Data Model (XDM) 4.0] section 2.1 Terminology.

Error Conditions

A dynamic error is raised [err:FOCA0002] if $value does not have the correct lexical form for an instance of xs:QName.

A dynamic error is raised [err:FONS0004] if $value has a prefix and there is no namespace binding for $element that matches this prefix.

Notes

Sometimes the requirement is to construct an xs:QName without using the default namespace. This can be achieved by writing:

if (contains($value, ":"))
then resolve-QName($value, $element)
else QName("", $value)

If the requirement is to construct an xs:QName using the namespaces in the static context, then the xs:QName constructor should be used.

Examples
Variables
let $element := <e xmlns:eg="http://ns.example.com/"/>
ExpressionResult

Assume that the element bound to $element has a single namespace binding bound to the prefix eg.

fn:resolve-QName("hello", $element)

fn:resolve-QName("hello", $element) returns a QName with local name "hello" that is in no namespace.

#Q{}hello

fn:resolve-QName("eg:myFunc", $element)

fn:resolve-QName("eg:myFunc", $element) returns an xs:QName whose namespace URI is specified by the namespace binding corresponding to the prefix "eg" and whose local name is "myFunc".

#Q{http://ns.example.com/}eg:myFunc

12 Processing nodes

12.2 Other properties of nodes

This section specifies further functions that return properties of nodes. Nodes are formally defined in 6 Nodes DM31.

FunctionMeaning
fn:has-childrenReturns true if the supplied GNode has one or more child nodes (of any kind).
fn:in-scope-namespacesReturns the in-scope namespaces of an element node, as a map.
fn:in-scope-prefixesReturns the prefixes of the in-scope namespaces for an element node.
fn:langThis function tests whether the language of $node, or the context value if the second argument is omitted, as specified by xml:lang attributes is the same as, or is a sublanguage of, the language specified by $language.
fn:local-nameReturns the local part of the name of $node as an xs:string that is either the zero-length string, or has the lexical form of an xs:NCName.
fn:nameReturns the name of a node, as an xs:string that is either the zero-length string, or has the lexical form of an xs:QName.
fn:namespace-uriReturns the namespace URI part of the name of $node, as an xs:anyURI value.
fn:namespace-uri-for-prefixReturns the namespace URI of one of the in-scope namespaces for $element, identified by its namespace prefix.
fn:pathReturns a path expression that can be used to select the supplied node relative to the root of its containing document.
fn:rootReturns the root of the tree to which $node belongs. The function can be applied both to XNodesDM and to JNodesDM.
fn:siblingsReturns the supplied GNode together with its siblings, in document order.

12.2.1 fn:has-children

Changes in 4.0 (next | previous)

  1. Generalized to work with JNodes as well as XNodes.  [Issue 2100 PR 2149 12 August 2025]

Summary

Returns true if the supplied GNode has one or more child nodes (of any kind).

Signature
fn:has-children(
$nodeas gnode()?:= .
) as xs:boolean
Properties

The zero-argument form of this function is deterministic, context-dependent, and focus-dependent.

The one-argument form of this function is deterministic, context-independent, and focus-independent.

Rules

If the argument is omitted, it defaults to the context value (.).

Provided that the supplied argument $node matches the expected type gnode()?, the result of the function call fn:has-children($node) is defined to be the same as the result of the expression fn:exists($node/child::gnode()).

Error Conditions

The following errors may be raised when $node is omitted:

  • If the context value is absentDM, type error [err:XPDY0002]XP

  • If the context value is not an instance of the sequence type gnode()?, type error [err:XPTY0004]XP.

Notes

If $node is the empty sequence the result is false.

The motivation for this function is to support streamed evaluation. According to the streaming rules in [XSL Transformations (XSLT) Version 4.0], the following construct is not streamable:

<xsl:if test="exists(row)">
  <ulist>
    <xsl:for-each select="row">
      <item><xsl:value-of select="."/></item>
    </xsl:for-each>
  </ulist>
</xsl:if>

This is because it makes two downward selections to read the child row elements. The use of fn:has-children in the xsl:if conditional is intended to circumvent this restriction.

Although the function was introduced to support streaming use cases, it has general utility as a convenience function.

If the supplied argument is a map or an array, it will automatically be coerced to a JNode.

Examples
Variables
let $e := <doc>
  <p id="alpha">One</p>
  <p/>
  <p>Three</p>
  <?pi 3.14159?>
</doc>
ExpressionResult
has-children($e)

true()

has-children($e//p[1])

true()

has-children($e//p[2])

false()

has-children($e//p[3])

true()

has-children($e//processing-instruction())

false()

has-children($e//p[1]/text())

false()

has-children($e//p[1]/@id)

false()

jtree([1,2,3]) => has-children()
[1,2,3] => has-children()

true()

jtree([]) => has-children()
[] => has-children()

false()

12.2.4 fn:lang

Summary

This function tests whether the language of $node, or the context value if the second argument is omitted, as specified by xml:lang attributes is the same as, or is a sublanguage of, the language specified by $language.

Signature
fn:lang(
$languageas xs:string?,
$nodeas node():= .
) as xs:boolean
Properties

The one-argument form of this function is deterministic, context-dependent, and focus-dependent.

The two-argument form of this function is deterministic, context-independent, and focus-independent.

Rules

The behavior of the function if the second argument is omitted is exactly the same as if the context value (.) had been passed as the second argument.

The language of the argument $node, or the context value if the second argument is omitted, is determined by the value of the xml:lang attribute on the node, or, if the node has no such attribute, by the value of the xml:lang attribute on the nearest ancestor of the node that has an xml:lang attribute. If there is no such ancestor, then the function returns false.

If $language is the empty sequence it is interpreted as the zero-length string.

The relevant xml:lang attribute is determined by the value of the XPath expression:

(ancestor-or-self::*/@xml:lang)[last()]

If this expression returns the empty sequence, the function returns false.

Otherwise, the function returns true if and only if, based on a caseless default match as specified in section 3.13 of [The Unicode Standard], either:

  1. $language is equal to the string-value of the relevant xml:lang attribute, or

  2. $language is equal to some substring of the string-value of the relevant xml:lang attribute that starts at the start of the string-value and ends immediately before a hyphen, - (HYPHEN-MINUS, #x002D).

Error Conditions

The following errors may be raised when $node is omitted:

Examples
ExpressionResult
<para xml:lang="en"/> -> fn:lang("en")

The expression fn:lang("en") would return true if the context node were any of the following four elements:

true()

  • <para xml:lang="en"/>

  • <div xml:lang="en"><para>And now, and forever!</para></div>

  • <para xml:lang="EN"/>

  • <para xml:lang="en-us"/>

<div xml:lang="en"><para>And now, and
                        forever!</para></div> -> fn:lang("en")

true()

<para xml:lang="EN"/> -> fn:lang("en")

The expression fn:lang("fr") would return false if the context node were <para xml:lang="EN"/>

true()

<para xml:lang="en-us"/> -> fn:lang("en")

true()

<para xml:lang="EN"/> -> fn:lang("fr")

false()

<para xml:lang="en-us"/> -> fn:lang("en-GB")

false()

12.2.9 fn:path

Changes in 4.0 (next | previous)

  1. Options are added to customize the form of the output.  [Issues 332 1660 PRs 1620 1886 29 November 2024]

  2. The function is extended to handle JNodes.  [Issue 2100 PR 2149 5 August 2025]

Summary

Returns a path expression that can be used to select the supplied node relative to the root of its containing document.

Signature
fn:path(
$nodeas gnode()?:= .,
$optionsas map(*)?:= {}
) as xs:string?
Properties

The zero-argument form of this function is deterministic, context-dependent, and focus-dependent.

The one-argument form of this function is deterministic, context-independent, and focus-independent.

The two-argument form of this function is deterministic, context-independent, and focus-independent.

Rules

The behavior of the function if the $nodeargument is omitted is exactly the same as if the context value (.) had been passed as the argument.

If $node is the empty sequence, the function returns the empty sequence.

The $options argument, if present, defines additional parameters controlling how the output is formatted. The option parameter conventions apply. The options available are as follows:

record(
origin?as gnode()?,
lexical?as xs:boolean,
namespaces?as map((xs:NCName | enum('')), xs:anyURI)?,
indexes?as xs:boolean
)
KeyMeaning

origin?

A GNode, which must be an ancestor of $node. If present, the returned path will be a relative path that selects $node starting from the supplied origin node, rather than from the root of the containing tree.
  • Type: gnode()?

  • Default: ()

lexical?

If true, the names of element nodes in the path are represented by the result of a call on the name function applied to each element. The result in this case does not contain sufficient information to identify the namespace URI of the element.
  • Type: xs:boolean

  • Default: false

namespaces?

A map from namespace prefixes to namespace URIs, such as might be returned by the function fn:in-scope-namespaces. If a prefix is available for a given URI, it is used in preference to using Q{uri}local notation.
  • Type: map((xs:NCName | enum('')), xs:anyURI)?

  • Default: ()

indexes?

If true, the returned path includes the index positions of nodes. If false, only the node names are included.
  • Type: xs:boolean

  • Default: true

Let R be the GNode supplied in the origin option, or the root GNode of the tree containing $node otherwise.

If $node is a document node, or a JNode with no parent, the function returns the string "/".

Otherwise, the function returns a string that consists of a sequence of steps, one for each ancestor-or-self of $node that is not an ancestor-or-self of R.

If R is an XNode other than a document node and the origin option is absent or empty, then this string is preceded by a string notionally representing a call to the fn:root function, expressed as follows:

  • If the lexical option is present with the value true, then the string "fn:root()".

  • If the namespaces option is present and defines a mapping from a non empty prefix P to the namespace URI http://www.w3.org/2005/xpath-functions, then "P:root()"

  • If the namespaces option is present and defines a mapping from the empty string to the namespace URI http://www.w3.org/2005/xpath-functions, then "root()"

  • Otherwise, "Q{http://www.w3.org/2005/xpath-functions}root()".

Each step is the concatenation of:

  1. The character "/", which is omitted for the first step if the origin option is present;

  2. A string whose form depends on the kind of node selected by that step, as follows:

    1. For an element node, the concatenation of:

      1. A representation of the element name, chosen as follows:

        1. If the lexical option is present with the value true, then the result of applying the name function to the element node.

        2. Otherwise, if the namespaces option is present and the element is in a namespace U and the namespaces option includes a mapping from a prefix P to the namespace U, then the string P:L, where L is the local part of the element name. If there is more than one such prefix, then one of them is chosen arbitrarily.

        3. Otherwise, if the namespaces option is present and the element is in a namespace U and the namespaces option includes a mapping from the zero-length string to the namespace U, then the local part of the element name.

        4. Otherwise, if the namespaces option is present and the element is in no namespace and the namespaces option includes no mapping from the zero-length string to any namespace, then the local part of the element name.

        5. Otherwise, the string Q{U}L, where U is the namespace URI of the element name or the empty string if the element is in no namespace, and L is the local part of the element name.

      2. Unless the indexes option is present with the value false, a string in the form [position] where position is an integer representing the one-based position of the selected node among its like-named siblings.

    2. For an attribute node, the concatenation of:

      1. The character "@"

      2. If the lexical option is present with the value true, then the result of applying the name function to the attribute node.

      3. Otherwise, if the attribute node is in no namespace, the local part of the attribute name.

      4. Otherwise, if the namespaces option is present, and if it includes a mapping from a non-empty namespace prefix P to the namespace URI of the attribute, then a string in the form P:L, where L is the local part of the attribute name. If there is more than one such prefix, then one of them is chosen arbitrarily.

      5. Otherwise, the string Q{U}L, where U is the namespace URI of the attribute name, and L is the local part of the attribute name.

    3. For a text node: text()[position] where position is an integer representing the position of the selected node among its text node siblings.

      The suffix [position] is omitted if the indexes option is present with the value false.

    4. For a comment node: comment()[position] where position is an integer representing the position of the selected node among its comment node siblings.

      The suffix [position] is omitted if the indexes option is present with the value false.

    5. For a processing-instruction node: processing-instruction(local)[position] where local is the name of the processing instruction node and position is an integer representing the position of the selected node among its like-named processing-instruction node siblings.

      The suffix [position] is omitted if the indexes option is present with the value false.

    6. For a namespace node:

      1. If the namespace node has a name: namespace::prefix, where prefix is the local part of the name of the namespace node (which represents the namespace prefix).

      2. If the namespace node has no name (that is, if it represents the default namespace): namespace::*[Ulocal-name() = ""]

        Here Ulocal-name() represents a call on the function fn:local-name and is formatted using the same conventions as the call on fn:root described earlier.

    7. For a JNode where the ·content· property of the parent is an array, then as the string *[N] where N is the value of the ·selector· property.

    8. For any other JNode (including the case where the ·content· property of the parent is a map):

      1. If the value is an xs:string, xs:untypedAtomic, or xs:anyURI that is castable to xs:NCName, then the result of casting the value to xs:NCName.

      2. If the value is an xs:string, xs:untypedAtomic, or xs:anyURI that is not castable to xs:NCName, then then as the string get("S") where S is the string value.

      3. If the value is numeric, then as the string get(N) where N is the result of casting the numeric value to xs:string.

      4. If the value is an xs:QName, then as the string get(#Q{uri}local) where uri and local are the namespace URI and local name parts of the QName.

      5. If the value is an xs:boolean, then as the string get(true()) or get(false()).

      6. If the value is of any other type, then as the string get(xs:T("S")) where T is the local part of the most specific built-in atomic type of which the value is an instance, and S is the result of casting the value to xs:string.

      TODO: Better handling of the case where the parent is neither a map nor an array, for example where it is a sequence of several maps or several arrays. It's hard to provide a better path for these when there is no AxisStep for selecting within such values.

Error Conditions

The following errors may be raised when $node is omitted:

  • If the context value is absentDM, type error [err:XPDY0002]XP

  • If the context value is not an instance of the sequence type gnodenode()?, type error [err:XPTY0004]XP.

If the value of the origin option is a node that is not an ancestor of $node (or in the absence of $node, the context value), dynamic error [err:FOPA0001].

Notes

Using the namespaces option to shorten the generated path is often convenient, but the resulting path may be unusable if the input tree contains multiple bindings for the same prefix.

Similarly, using the lexical option is convenient if there is no need for precise namespace information: it is especially suitable when the containing node tree declares no namespaces.

If the supplied argument is a map or an array, it will automatically be coerced to a JNode. This however is not useful, because this will be a root JNode, yielding the path /.

Examples
Variables
let $e := document {            
  <p xmlns="http://example.com/one" xml:lang="de" author="Friedrich von Schiller">
Freude, schöner Götterfunken,<br/>
Tochter aus Elysium,<br/>
Wir betreten feuertrunken,<br/>
Himmlische, dein Heiligtum.
</p>}
let $emp := 
  <employee xml:id="ID21256">
     <empnr>E21256</empnr>
     <first>John</first>
     <last>Brown</last>
  </employee>
Expression:
path($e)
Result:
'/'
Expression:
path($e/*:p)
Result:
'/Q{http://example.com/one}p[1]'
Expression:
path($e/*:p, { 'namespaces': in-scope-namespaces($e/*) })
Result:
'/p[1]'
Expression:
path($e/*:p, { 'indexes': false() })
Result:
'/Q{http://example.com/one}p'
Expression:
path($e/*:p/@xml:lang)
Result:
'/Q{http://example.com/one}p[1]/@Q{http://www.w3.org/XML/1998/namespace}lang'
Expression:
path($e//@xml:lang, { 'namespaces': in-scope-namespaces($e/*) })
Result:
'/p[1]/@xml:lang'
Expression:
path($e/*:p/@author)
Result:
'/Q{http://example.com/one}p[1]/@author'
Expression:
path($e/*:p/*:br[2])
Result:
'/Q{http://example.com/one}p[1]/Q{http://example.com/one}br[2]'
Expression:
path($e/*:p/*:br[2], {
  'namespaces': { 'N': 'http://example.com/one' },
  'indexes': false() 
})
Result:
'/N:p/N:br'
Expression:
path($e//text()[starts-with(normalize-space(), 'Tochter')])
Result:
'/Q{http://example.com/one}p[1]/text()[2]'
Expression:
path($e/*:p/*:br[2], { 'lexical': true() })
Result:
'/p[1]/br[2]'
Expression:
path($e/*:p/*:br[2], { 'lexical': true(), 'origin': $e/*:p })
Result:
'br[2]'
Expression:
path($emp)
Result:
'Q{http://www.w3.org/2005/xpath-functions}root()'
Expression:
path($emp/@xml:id)
Result:
'Q{http://www.w3.org/2005/xpath-functions}root()/@Q{http://www.w3.org/XML/1998/namespace}id'
Expression:
path($emp/empnr)
Result:
'Q{http://www.w3.org/2005/xpath-functions}root()/Q{}empnr[1]'
Expression:
path($emp/empnr, { 'lexical': true() })
Result:
'fn:root()/empnr[1]'
Expression:
path($emp/empnr, {
  'namespaces': {
    'fn': 'http://www.w3.org/2005/xpath-functions',
    '': ''
  }
})
Result:
'fn:root()/empnr[1]'
Expression:
let $in := [{"b":[3,4]}]
return path($in/*[1]/b/*[2])
Result:
"/*[1]/b/*[2]"
Expression:
let $in := [[{'a':1}], [{'a':2}]]
return path($in//a[. = 2])
Result:
"/*[2]/*[1]/a"

12.2.11 fn:siblings

Changes in 4.0 (next | previous)

  1. New in 4.0  [Issues 1542 1552 PRs 1547 1551 5 November 2024]

Summary

Returns the supplied GNode together with its siblings, in document order.

Signature
fn:siblings(
$nodeas gnode()?:= .
) as gnode()*
Properties

The zero-argument form of this function is deterministic, context-dependent, and focus-dependent.

The one-argument form of this function is deterministic, context-independent, and focus-independent.

Rules

If the $node argument is omitted, it defaults to the context value (.).

If the value of $node is the empty sequence, the function returns the empty sequence.

If $node is a child of some parent GNode P, the function returns all the children of P (including $node), in document order, as determined by the value of $node/child::gnode().

Otherwise (specifically, if $node is parentless, or if it is an attribute or namespace node), the function returns $node.

Formal Equivalent

The effect of the function is equivalent to the result of the following XPath expression.

if ($node intersect $node/parent::gnode()/child::gnode())
then $node/parent::gnode()/child::gnode()
else $node
if ($node intersect $node/parent::node()/child::node())
then $node/parent::node()/child::node()
else $node
Error Conditions

The following errors may be raised when $node is omitted:

  • If the context value is absentDM, type error [err:XPDY0002]XP

  • If the context value is not an instance of the sequence type gnodenode()?, type error [err:XPTY0004]XP.

Notes

The result of siblings($n) (except in error cases) is the same as the result of $n/(preceding-sibling::node() | following-sibling-or-self::node()). It is also the same as $n/(preceding-sibling-or-self::node() | following-sibling::node())

As with names such as parent and child, the word sibling used here as a technical term is not a precise match to its use in describing human family relationships, but is chosen for convenience.

Examples
Variables
let $e := <doc x="X"><a>A</a>text<?pi 3.14159?></doc>
ExpressionResult
siblings($e//a) ! string()

"A", "text", "3.14159"

siblings($e//processing-instruction('pi')) ! string()

"A", "text", "3.14159"

siblings($e//@x) ! string()

"X"

[[1,2], [11,12], [13,14]]//jnode()[.='12'] => siblings() => sum()

23

12.3 Functions on sequences of nodes

This section specifies functions on sequences of nodes.

FunctionMeaning
fn:distinct-ordered-nodesRemoves duplicate GNodes and sorts the input into document order.
fn:innermostReturns every GNode within the input sequence that is not an ancestor of another member of the input sequence; the GNodes are returned in document order with duplicates eliminated.
fn:outermostReturns every GNode within the input sequence that has no ancestor that is itself a member of the input sequence; the nodes are returned in document order with duplicates eliminated.

12.3.1 fn:distinct-ordered-nodes

Changes in 4.0 (next | previous)

  1. New in 4.0  [Issue 1189 PR 1191 14 May 2024]

Summary

Removes duplicate GNodes and sorts the input into document order.

Signature
fn:distinct-ordered-nodes(
$nodesas gnode()*
) as gnode()*
Properties

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

Rules

Any duplicate GNodes (that is, XNodes or JNodes) in the input (based on node identity) are discarded. The remaining GNodes are returned in document orderXP.

Notes

Document order is implementation-dependent (but stable) for GNodes in different trees. If some GNode in tree A precedes some GNode in tree B, then every GNode in A precedes every GNode in B.

Examples
Expression:
let $x := parse-xml('<doc><a/><b/><c/><d/><c/><e/></doc>')
return distinct-ordered-nodes(($x//c, $x//b, $x//a, $x//b)) ! name()
Result:
"a", "b", "c", "c"

(The two $x//b expressions select the same node; one of these is eliminated as a duplicate. The $x//c expression selects two nodes that have distinct identity, so both are retained.)

Expression:
let $x := [1, "a", true()]
return count(distinct-ordered-nodes(
                ($x/*[1], $x/type(xs:integer)) 
            ))
let $x := [1, "a", true()]
return count(distinct-ordered-nodes(
                ($x/*[1], $x/jnode(*, xs:integer)) 
            ))
Result:
1

(The first array member is selected by two different routes; duplicate JNodes are eliminated.)

12.3.2 fn:innermost

Changes in 4.0 (next | previous)

  1. Generalized to work with JNodes as well as XNodes.  [Issue 2100 PR 2149 12 August 2025]

Summary

Returns every GNode within the input sequence that is not an ancestor of another member of the input sequence; the GNodes are returned in document order with duplicates eliminated.

Signature
fn:innermost(
$nodesas gnode()*
) as gnode()*
Properties

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

Rules

The effect of the function call fn:innermost($nodes) is defined to be equivalent to the result of the expression:

$nodes except $nodes/ancestor::gnode()

That is, the function takes as input a sequence of GNodes, and returns every GNode within the sequence that is not an ancestor of another GNode within the sequence; the GNodes are returned in document order with duplicates eliminated.

Notes

If the supplied argument includes a map or an array, it will automatically be coerced to a JNode.

Examples
Expression:
parse-xml("<doc>
    <div id='a'><div id='b'><div id='c'/></div></div>
  </doc>")//div
   => innermost() => for-each(fn{string(@id)})
Result:
"c"
Expression:
[[[1,2], [3,4]], [[5,6], [7,8]]]//array(*)
   => innermost() =!> jnode-content()
[[[1,2], [3,4]], [[5,6], [7,8]]]//jnode(*, array(*))
   => innermost() =!> jnode-content()
Result:
[1,2], [3,4], [5,6], [7,8]

12.3.3 fn:outermost

Changes in 4.0 (next | previous)

  1. Generalized to work with JNodes as well as XNodes.  [Issue 2100 PR 2149 12 August 2025]

Summary

Returns every GNode within the input sequence that has no ancestor that is itself a member of the input sequence; the nodes are returned in document order with duplicates eliminated.

Signature
fn:outermost(
$nodesas gnode()*
) as gnode()*
Properties

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

Rules

The effect of the function call fn:outermost($nodes) is defined to be equivalent to the result of the expression:

$nodes[not(ancestor::gnode() intersect $nodes)]/.

That is, the function takes as input a sequence of GNodes, and returns every GNode within the sequence that does not have another GNode within the sequence as an ancestor; the GNodes are returned in document order with duplicates eliminated.

Notes

The formulation $nodes except $nodes/descendant::node() might appear to be simpler, but does not correctly account for attribute nodes, as these are not descendants of their parent element.

The motivation for the function was based on XSLT streaming use cases. There are cases where the [XSL Transformations (XSLT) Version 4.0] streaming rules allow the construct outermost(//section) but do not allow //section; the function can therefore be useful in cases where it is known that sections will not be nested, as well as cases where the application actually wishes to process all sections except those that are nested within another.

If the supplied argument includes a map or an array, it will automatically be coerced to a JNode.

Examples
Expression:
parse-xml("<doc>
     <div id='a'><div id='b'><div id='c'/></div></div>
  </doc>")//div
   => outermost() => for-each(fn{string(@id)})
Result:
"a"
Expression:
[[[1], [2]], [[3], [4]], [[5], [6]]]//jnode(*, array(*))
   => outermost() =!> array:size()
[[[1], [2]], [[3], [4]], [[5], [6]]]//self::jnode(*, array(*))
   => outermost() =!> array:size()
Result:
3

13 Processing function items

The functions included in this section operate on function items, that is, values referring to a function.

[Definition] Functions that accept functions among their arguments, or that return functions in their result, are described in this specification as higher-order functions.

Note:

Some functions such as fn:parse-json allow the option of supplying a callback function for example to define exception behavior. Where this is not essential to the use of the function, the function has not been classified as higher-order for this purpose; in applications where function items cannot be created, these particular options will not be available.

FunctionMeaning
fn:function-lookupReturns a function item having a given name and arity, if there is one.
fn:function-nameReturns the name of the function identified by a function item.
fn:function-arityReturns the arity of the function identified by a function item.
fn:function-identityReturns a string representing the identity of a function item.
fn:function-annotationsReturns the annotations of the function item.

13.1 fn:function-lookup

Summary

Returns a function item having a given name and arity, if there is one.

Signature
fn:function-lookup(
$nameas xs:QName,
$arityas xs:integer
) as fn(*)?
Properties

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

Rules

A call to fn:function-lookup starts by looking for a function definitionXP in the named functions component of the dynamic context (specifically, the dynamic context of the call to fn:function-lookup), using the expanded QName supplied as $name and the arity supplied as $arity. There can be at most one such function definition.

If no function definition can be identified (by name and arity), then the empty sequence is returned.

If a function definition is identified, then a function item is obtained from the function definition using the same rules as for evaluation of a named function reference (see [XML Path Language (XPath) 4.0] section 4.6.5 Named Function References). The captured context of the returned function item (if it is context dependent) is the static and dynamic context of the call on fn:function-lookup.

If the arguments to fn:function-lookup identify a function that is present in the static context of the function call, the function will always return the same function that a static reference to this function would bind to. If there is no such function in the static context, then the results depend on what is present in the dynamic context, which is implementation-defined.

Error Conditions

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

Notes

This function can be useful where there is a need to make a dynamic decision on which of several statically known functions to call. It can thus be used as a substitute for polymorphism, in the case where the application has been designed so several functions implement the same interface.

The function can also be useful in cases where a query or stylesheet module is written to work with alternative versions of a library module. In such cases the author of the main module might wish to test whether an imported library module contains or does not contain a particular function, and to call a function in that module only if it is available in the version that was imported. A static call would cause a static error if the function is not available, whereas getting the function using fn:function-lookup allows the caller to take fallback action in this situation.

If the function that is retrieved by fn:function-lookup is context-dependent, that is, if it has dependencies on the static or dynamic context of its caller, the context that applies is the static and/or dynamic context of the call to the fn:function-lookup function itself. The context thus effectively forms part of the closure of the returned function. This mainly applies when the target of fn:function-lookup is a built-in function, because user-defined functions typically have no dependency on the static or dynamic context of the function call (an exception arises when the expressions used to define default values for parameters are context-dependent). The rule applies recursively, since fn:function-lookup is itself a context-dependent built-in function.

However, the static and dynamic context of the call to fn:function-lookup may play a role even when the selected function definition is not itself context dependent, if the expressions used to establish default parameter values are context dependent.

User-defined XSLT or XQuery functions should be accessible to fn:function-lookup only if they are statically visible at the location where the call to fn:function-lookup appears. This means that private functions, if they are not statically visible in the containing module, should not be accessible using fn:function-lookup.

The function identity is determined in the same way as for a named function reference. Specifically, if there is no context dependency, two calls on fn:function-lookup with the same name and arity must return the same function.

These specifications do not define any circumstances in which the dynamic context will contain functions that are not present in the static context, but neither do they rule this out. For example an API may provide the ability to add functions to the dynamic context, and such functions may potentially be context-dependent.

The mere fact that a function exists and has a name does not of itself mean that the function is present in the dynamic context. For example, functions obtained through use of the fn:load-xquery-module function are not added to the dynamic context.

Examples
Expression:

function-lookup( #fn:substring, 2 )( 'abcd', 2 )

Result:

'bcd'

Expression:

The expression (fn:function-lookup( #xs:dateTimeStamp, 1 ), xs:dateTime#1)[1] ('2011-11-11T11:11:11Z') returns an xs:dateTime value set to the specified date, time, and timezone; if the implementation supports XSD 1.1 then the result will be an instance of the derived type xs:dateTimeStamp. The query is written to ensure that no failure occurs when the implementation does not recognize the type xs:dateTimeStamp.

(fn:function-lookup( #xs:dateTimeStamp, 1 ),
                  xs:dateTime#1)[1] ('2011-11-11T11:11:11Z')
Result:
An
                  xs:dateTime value set to the specified date, time, and timezone; if
               the implementation supports XSD 1.1 then the result will be an instance of the
               derived type xs:dateTimeStamp. The query is written to ensure that no
               failure occurs when the implementation does not recognize the type
                  xs:dateTimeStamp.
Expression:

The expression

let $f := function-lookup( #zip:binary-entry, 2 )
return if (exists($f)) then $f($source, $entry) else ()

returns the result of calling zip:binary-entry($source, $entry) if the function is available, or the empty sequence otherwise.

Result:
The result of
               calling zip:binary-entry($source, $entry) if the function is available, or
               the empty sequence otherwise.

14 Processing maps

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

A map is a kind of item.

[Definition] A map consists of a sequence of entries, also known as key-value pairs. Each entry comprises a key which is an arbitrary atomic item, and an arbitrary sequence called the associated value.

[Definition] Within a map, no two entries have the same key. Two atomic items K1 and K2 are the same key for this purpose if the function call fn:atomic-equal($K1, $K2) returns true.

It is not necessary that all the keys in a map should be of the same type (for example, they can include a mixture of integers and strings).

Maps are immutable, and have no identity separate from their content. For example, the map:remove function returns a map that differs from the supplied map by the omission (typically) of one entry, but the supplied map is not changed by the operation. Two calls on map:remove with the same arguments return maps that are indistinguishable from each other; there is no way of asking whether these are “the same map”.

A map can also be viewed as a function from keys to associated values. To achieve this, a map is also a function item. The function corresponding to the map has the signature function($key as xs:anyAtomicValue) as item()*. Calling the function has the same effect as calling the map:get function: the expression $map($key) returns the same result as get($map, $key). For example, if $books-by-isbn is a map whose keys are ISBNs and whose assocated values are book elements, then the expression $books-by-isbn("0470192747") returns the book element with the given ISBN. The fact that a map 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.

14.4 Functions that operate on maps

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

The function call map:get($map, $key) can be used to retrieve the value associated with a given key.

There is no operation to atomize a map or convert it to a string. The function fn:serialize can in some cases be used to produce a JSON representation of a map.

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

FunctionMeaning
map:buildReturns a map that typically contains one entry for each item in a supplied input sequence.
map:containsTests whether a supplied map contains an entry for a given key.
map:emptyReturns true if the supplied map contains no entries.
map:entriesReturns a sequence containing all the key-value pairs present in a map, each represented as a single-entry map.
map:entryReturns a single-entry map that represents a single key-value pair.
map:filterSelects entries from a map, returning a new map.
map:findSearches the supplied input sequence and any contained maps and arrays for a map entry with the supplied key, and returns the corresponding values.
map:for-eachApplies a supplied function to every entry in a map, returning the sequence concatenationXP of the results.
map:getReturns the value associated with a supplied key in a given map.
map:itemsReturns a sequence containing all the values present in a map, in order.
map:keysReturns a sequence containing all the keys present in a map.
map:keys-whereReturns a sequence containing selected keys present in a map.
map:mergeReturns a map that combines the entries from a number of existing maps.
map:putReturns a map containing all the contents of the supplied map, but with an additional entry, which replaces any existing entry for the same key.
map:removeReturns a map containing all the entries from a supplied map, except those having a specified key.
map:sizeReturns the number of entries in the supplied map.

14.4.1 map:build

Changes in 4.0 (next | previous)

  1. New in 4.0  [Issue 151 PR 203 18 October 2022]

Summary

Returns a map that typically contains one entry for each item in a supplied input sequence.

Signature
map:build(
$inputas item()*,
$keyas (fn($item as item(), $position as xs:integer) as xs:anyAtomicType*)?:= fn:identity#1,
$valueas (fn($item as item(), $position as xs:integer) as item()*)?:= fn:identity#1,
$optionsas map(*)?:= {}
) as map(*)
Properties

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

Rules

Informally, the function processes each item in $input in order. It calls the $key function on that item to obtain a sequence of key values, and the $value function to obtain an associated value. Then, for each key value:

  • If the key is not already present in the target map, the processor adds a new key-value pair to the map, with that key and that value.

  • If the key is already present, the processor combines the new value for the key with the existing value; the way they are combined is determined by the duplicates option.

    By default, when two duplicate entries occur:

    • A single combined entry will be present in the result.

    • This entry will contain the sequence concatenationXP of the supplied values.

    • The position of the combined entry in the entry orderDM of the result map will correspond to the position of the first of the duplicates.

    • The key of the combined entry will correspond to the key of one of the duplicates: it is implementation-dependent which one is chosen. (It is possible for two keys to be considered duplicates even if they differ: for example, they may have different type annotations, or they may be xs:dateTime values in different timezones.)

    The $options argument can be used to control the way in which duplicate keys are handled. The option parameter conventions apply. The entries that may appear in the $options map are as follows:

    record(
    duplicates?as (enum( "reject", "use-first", "use-last", "use-any", "combine") | fn(item()*, item()*) as item()*)?
    )
    KeyValueMeaning

    duplicates?

    Determines the policy for handling duplicate keys: specifically, the action to be taken if two entries in the input sequence have key values K1 and K2 where K1 and K2 are the same key.
    • Type: (enum( "reject", "use-first", "use-last", "use-any", "combine") | fn(item()*, item()*) as item()*)?

    • Default: "combine"

    "reject" Equivalent to supplying a function that raises a dynamic error with error code "FOJS0003". The effect is that duplicate keys result in an error.
    "use-first"Equivalent to supplying the function fn($a, $b){ $a }. The effect is that the first of the duplicates is chosen.
    "use-last"Equivalent to supplying the function fn($a, $b){ $b }. The effect is that the last of the duplicates is chosen.
    "use-any"Equivalent to supplying the function fn($a, $b){ one-of($a, $b) } where one-of chooses either $a or $b in an implementation-dependent way. The effect is that it is implementation-dependent which of the duplicates is chosen.
    "combine"Equivalent to supplying the function fn($a, $b){ $a, $b } (or equivalently, the function op(",")). The effect is that the result contains the sequence concatenationXP of the values having the same key, retaining order.
    function(*) A function with signature fn(item()*, item()*) as item()*. The function is called for any entry in the input sequence that has the same key as a previous entry. The first argument is the existing value associated with the key; the second argument is the value associated with the key in the duplicate input entry, and the result is the new value to be associated with the key. The effect is cumulative: for example if there are three values X, Y, and Z associated with the same key, and the supplied function is F, then the result is an entry whose value is X => F(Y) => F(Z).
Formal Equivalent

The effect of the function is equivalent to the result of the following XPath expression.

for-each(
  $input, 
  fn($item, $pos) {
    for-each($key($item, $pos), fn($k) {
      map:entry($k, $value($item, $pos))
    }
  )}
)
=> map:merge($options)
Error Conditions

An error is raised [err:FOJS0003] if the value of $options indicates that duplicates are to be rejected, and a duplicate key is encountered.

An error is raised [err:FOJS0005] if the value of $options includes an entry whose key is defined in this specification, and whose value is not a permitted value for that key.

Notes

The default function for both $key and $value is the identity function. Although it is permitted to default both, this serves little purpose: usually at least one of these arguments will be supplied.

Examples
Expression:

map:build((), string#1)

Result:

{}

Expression:

map:build(1 to 10, fn { . mod 3 })

Result:

{ 0: (3, 6, 9), 1: (1, 4, 7, 10), 2: (2, 5, 8) }

(Returns a map with one entry for each distinct value of . mod 3. The function to compute the value is the identity function, and duplicates are combined by sequence concatenation.)

Expression:
map:build(
  1 to 5,
  value := format-integer(?, "w")
)
Result:
{ 1: "one", 2: "two", 3: "three", 4: "four", 5: "five" }

(Returns a map with five entries. The function to compute the key is an identity function, the function to compute the value invokes fn:format-integer.)

Expression:
map:build(
  ("January", "February", "March", "April", "May", "June",
   "July", "August", "September", "October", "November", "December"),
  substring(?, 1, 1)
)
Result:
{
  "A": ("April", "August"),
  "D": ("December"),
  "F": ("February"),
  "J": ("January", "June", "July"),
  "M": ("March", "May"),
  "N": ("November"),
  "O": ("October"),
  "S": ("September")
}
Expression:
map:build(1 to 5, {
  1: ("eins", "one"),
  4: ("vier", "four")
})
Result:
{
  "eins": 1,
  "one": 1,
  "vier": 4,
  "four": 4
}
Expression:
map:build(
  ("apple", "apricot", "banana", "blueberry", "cherry"), 
  substring(?, 1, 1),
  string-length#1,
  { "duplicates": op("+") }
)
Result:
{ "a": 12, "b": 15, "c": 6 }

(Constructs a map where the key is the first character of an input item, and where the corresponding value is the total string-length of the items starting with that character.)

Expression:
map:build(
  ('Wang', 'Liu', 'Zhao'),
  key := fn($name, $pos) { $name },
  value := fn($name, $pos) { $pos }
)
Result:
{ "Wang": 1, "Liu": 2, "Zhao": 3 }

(Returns an inverted index for the input sequence with the string stored as key and the position stored as value.)

Expression:
let $titles := <titles>
  <title>A Beginner’s Guide to <ix>Java</ix></title>
  <title>Learning <ix>XML</ix></title>
  <title>Using <ix>XML</ix> with <ix>Java</ix></title>
</titles>
return map:build($titles/title, fn($title) { $title/ix })
Result:
{
  "Java": (
    <title>A Beginner’s Guide to <ix>Java</ix></title>,
    <title>Using <ix>XML</ix> with <ix>Java</ix></title>
  ),
  "XML": (
    <title>Learning <ix>XML</ix></title>,
    <title>Using <ix>XML</ix> with <ix>Java</ix></title>
  )
}
Expression:

The following expression creates a map whose keys are employee @ssn values, and whose corresponding values are the employee nodes:

map:build(//employee, fn { @ssn })
Result:
map:build(//employee, fn { @ssn })
A map whose keys are employee @ssn values, and whose
               corresponding values are the employee nodes

The following expression creates a map whose keys are employee @location values, and whose corresponding values represent the number of employees at each distinct location. Any employees that lack an @location attribute will be excluded from the result.

Expression:
map:build(//employee, fn { @location }, fn { 1 }, { "duplicates": op("+") })
Result:

The following expression creates a map whose keys are employee @location values, and whose corresponding values contain the employee node for the highest-paid employee at each distinct location:

A map whose keys are employee @location values, and whose
               corresponding values represent the number of employees at each distinct location. Any employees that
               lack an @location attribute will be excluded from the result.
Expression:
map:build(
  //employee,
  key := fn { @location }, 
  combine := fn($a, $b) { highest(($a, $b), fn { xs:decimal(@salary) }) }
)
Result:

The following expression creates a map allowing efficient access to every element in a document by means of its fn:generate-id value:

A map whose keys are employee @location values, and whose
               corresponding values contain the employee node for the highest-paid employee at each distinct location
Expression:
map:build(//*, generate-id#1)
Result:
A map allowing efficient access to every element in a document by means
               of its fn:generate-id value.
Expression:
let $tree := parse-json('{
  "type": "package",
  "name": "org",
  "content": [
      { "type": "package",
        "name": "xml,
        "content: [
            { "type": "package",
              "name": "sax",
              "content": [
                  { "type": "class",
                    "name": "Attributes"},
                  { "type": "class",
                    "name": "ContentHandler"},
                  { "type": "class",
                    "name": "XMLReader"}
               ]
            }]
       }]
   }')
   return map:build($tree ? descendant::~[record(type, name, content?)],
                    fn{?ancestor-or-self::name => reverse() => string-join(,)},
                    fn{`{?type} {?name}`})
Result:
{ "org.xml.sax.Attributes": "class Attributes",
  "org.xml.sax.ContentHandler": "class ContentHandler",
  "org.xml.sax.XMLReader": "class XMLReader" }

The following expression creates(Constructs a map allowing efficient access to values in a recursive JSON structure using hierarchic paths:).

let $tree := parse-json('{
  "type": "package",
  "name": "org",
  "content": [
      { "type": "package",
        "name": "xml,
        "content: [
            { "type": "package",
              "name": "sax",
              "content": [
                  { "type": "class",
                    "name": "Attributes"},
                  { "type": "class",
                    "name": "ContentHandler"},
                  { "type": "class",
                    "name": "XMLReader"}
               ]
            }]
       }]
   }')
   return map:build($tree ? descendant::~[record(type, name, content?)],
                    fn{?ancestor-or-self::name => reverse() => string-join(,)},
                    fn{`{?type} {?name}`})

The result is the map:

{ "org.xml.sax.Attributes": "class Attributes",
  "org.xml.sax.ContentHandler": "class ContentHandler",
  "org.xml.sax.XMLReader": "class XMLReader" }

14.6 Other operations on maps

This section is non-normative.

Because a map is a function item, functions that apply to functions also apply to maps. A map is an anonymous function, so fn:function-name returns the empty sequence; fn:function-arity always returns 1.

Maps may be compared using the fn:deep-equal function.

There is no function or operator to atomize a map or convert it to a string (other than fn:serialize, which can be used to serialize some maps as JSON texts).

XPath 4.0 defines a number of syntactic constructs that operate on maps. These all have equivalents in the function library:

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.3 Other Operations on Arrays

This section is non-normative.

Arrays may be compared using the fn:deep-equal function.

The XPath language provides explicit syntax for certain operations on arrays. These constructs can all be specified in terms of function primitives:

16 Processing JNodes

Changes in 4.0 (next | previous)

  1. Introduced the concept of JNodes.   [Issue 2025 PR 2031 11 June 2025]

A JNodeDM is a wrapper around a map or array, or around a value that appears within the content of a map or array. JNodes are described at [XQuery and XPath Data Model (XDM) 4.0] section 8.4 JNodes. Wrapping a map or array in a JNode enables the use of path expressions such as $jnode/descendant::title, as described at [XML Path Language (XPath) 4.0] section 4.7 Path Expressions.

In addition to the functions defined in this section, functions that operate on JNodes include:

fn:distinct-ordered-nodes
fn:generate-id
fn:has-children
fn:innermost
fn:outermost
fn:path
fn:root
fn:siblings
fn:transitive-closure

16.1 Functions on JNodes

16.1.2 fn:jnode-content

Changes in 4.0 (next | previous)

  1. New in 4.0  [Issue 2025 PR 2031 12 June 2025]

Summary

Returns the ·content· property of a JNode.

Signature
fn:jnode-content(
$inputas jnode()?:= .
) as item()*
Properties

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

Rules

If the argument is omitted, it defaults to the context value (.).

If $input is the empty sequence, the function returns the empty sequence.

Otherwise, the function returns the ·content· property of $input.

Error Conditions

The following errors may be raised when $node is omitted:

  • If the context value is absentDM, type error [err:XPDY0002]XP.

  • If the context value is not an instance of the sequence type jnode()?, type error [err:XPTY0004]XP.

Notes

In many cases it is unnecessary to make an explicit call on jnode-content, because the coercion rules will take care of this automatically. For example, in an expression such as $X / descendant::name [matches(., '^J')], the call on matches is supplied with a JNode as its first argument; atomization ensures that the actual value being passed to the first argument of matches is the atomized value of the ·content· property.

Other examples where the ·content· of a JNode is extracted automatically include:

  • Any context where the required type is an atomic value, for example arithmetic operations, value comparisons and general comparisons, and calls on functions that expect an atomic value.

  • Any context where the required type is a map or array, for example the first argument of functions such as map:size or array:size, a free-standing expression within a map constructor such as map{ $jnode }, the constructs for member and for key/value, the left-hand operand of the lookup operator ? (or the context value in the case of a unary lookup operator), and the operand of a map/array filter expression $jnode?[predicate].

Notable places where the ·content· is not automatically extracted include:

  • When computing the effective boolean value. As with XNodes, writing if ($array/child::*[1]) ... tests for the existence of a child, it does not test its value. To test its value, write if (jnode-content($array/child::*[1])) ..., or equivalently if (xs:boolean($array/child::*[1])) ....

  • When calling functions that accept arbitrary sequences, such as count or deep-equal.

It is possible (though probably unwise) to construct a JNode whose ·content· property itself contains another JNode. For example, the expression jtree([jtree([]), jtree([])]) creates a JNode whose ·content· is an array of JNodes, and applying the child axis to this JNode will return a sequence of two JNodes that themselves have further JNodes as their content. The jnode-content returns these contained JNodes, it does not recursively extract their content.

Examples
Expression:
let $array := [1, 3, 4.5, 7, "eight", 10]
return $array / child::type(xs:integer) =!> jnode-content()
let $array := [1, 3, 4.5, 7, "eight", 10]
return $array / child::jnode(*, xs:integer) =!> jnode-content()
Result:
1, 3, 7, 10
Expression:
let $map := {'Mo': 'Monday', 'Tu': 'Tuesday', 'We': 'Wednesday'}
return $map / child::get(("Mo", "We", "Fr", "Su")) =!> jnode-content()
Result:
"Monday", "Wednesday"
Expression:
let $array := [[4, 18], [30, 4, 22]]
return $array / descendant::*[. > 25][1] / ancestor-or-self::* =!> jnode-content()
Result:
[[4, 18], [30, 4, 22]], [30, 4, 22]

16.1.3 fn:jnode-selector

Changes in 4.0 (next | previous)

  1. New in 4.0  [Issue 2025 PR 2031 12 June 2025]

Summary

Returns the ·selector· property of a JNode.

Signature
fn:jnode-selector(
$inputas jnode()?:= .
) as xs:anyAtomicType?
Properties

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

Rules

If the argument is omitted, it defaults to the context value (.).

If $input is the empty sequence, the function returns the empty sequence.

If $input is a root JNode (one in which the ·selector· property is absent), the function returns the empty sequence.

Otherwise, the function returns the ·selector· property of $input. In the case where the parent JNode wraps a map, this will be the key of the relevant entry within that map; in the case where the parent JNode wraps an array, it will be the 1-based index of the relevant member of the array.

Error Conditions

The following errors may be raised when $node is omitted:

  • If the context value is absentDM, type error [err:XPDY0002]XP.

  • If the context value is not an instance of the sequence type jnode()?, type error [err:XPTY0004]XP.

Examples
Expression:
let $array := [1, 3, 4.5, 7, "eight", 10]
return $array / child::type(xs:integer) =!> jnode-selector()
let $array := [1, 3, 4.5, 7, "eight", 10]
return $array / child::jnode(*, xs:integer) =!> jnode-selector()
Result:
1, 2, 4, 6
Expression:
let $map := {'Mo': 'Monday', 'Tu': 'Tuesday', 'We': 'Wednesday'}
return $map / child::get(("Mo", "We", "Fr", "Su")) =!> jnode-selector()
Result:
"Mo", "We"
Expression:
let $array := [[4, 18], [30, 4, 22]]
return $array / descendant::*[. > 25] / ancestor-or-self::* =!> jnode-selector()
Result:
2, 1

17 External resources and data formats

These functions in this section access resources external to a query or stylesheet, and convert between external file formats and their XPath and XQuery data model representation.

17.2 Functions on XML Data

These functions convert between the lexical representation of XML and the tree representation.

(The fn:serialize function also handles HTML and JSON output, but is included in this section for editorial convenience.)

FunctionMeaning
fn:parse-xmlThis function takes as input an XML document, and returns the document node at the root of an XDM tree representing the parsed document.
fn:parse-xml-fragmentThis function takes as input an XML external entity represented as a string, and returns the document node at the root of an XDM tree representing the parsed document fragment.
fn:serializeThis function serializes the supplied input sequence $input as described in [XSLT and XQuery Serialization 3.1], returning the serialized representation of the sequence as a string.
fn:xsd-validatorGiven an XSD schema, delivers a function item that can be invoked to validate a document, element, or attribute node against this schema.

17.2.1 fn:parse-xml

Changes in 4.0 (next | previous)

  1. The $options parameter has been added.  [Issue 305 PR 1257 11 June 2024]

  2. Additional error conditions have been defined.  [Issue 1287 PR 1288 25 June 2024]

  3. Additional options to control DTD and XInclude processing have been added.  [Issues 1857 1860 PR 1879 18 March 2025]

  4. Support for binary input has been added.  [Issue 748 PR 2013 20 May 2025]

Summary

This function takes as input an XML document, and returns the document node at the root of an XDM tree representing the parsed document.

Signature
fn:parse-xml(
$valueas (xs:string | xs:hexBinary | xs:base64Binary)?,
$optionsas map(*)?:= {}
) as document-node(*)?
Properties

This function is nondeterministic, context-dependent, and focus-independent. It depends on executable base URI.

Rules

If $value is the empty sequence, the function returns the empty sequence.

In other cases, $value is expected to contain an XML document supplied either as a string or a binary value. If it is supplied as a binary value, an optional byte order mark or XML declaration may contain the input encoding, and the input will be processed like a resource retrieved by the fn:doc function. Otherwise, if the input is a string, any byte order mark as well as the encoding specified in an optional XML declaration should be ignored.

The $options argument, if present and non-empty, defines the detailed behavior of the function. The option parameter conventions apply. The options available are as follows:

record(
base-uri?as xs:anyURI,
dtd-validation?as xs:boolean,
strip-space?as xs:boolean,
trusted?as xs:boolean,
xinclude?as xs:boolean,
xsd-validation?as xs:string,
use-xsi-schema-location?as xs:boolean
)
KeyValueMeaning

base-uri?

Determines the base URI. This is used both as the base URI used by the XML parser to resolve relative entity references within the document, and as the base URI of the document node that is returned. It defaults to the static base URI of the function call.
  • Type: xs:anyURI

  • Default: static-base-uri()

dtd-validation?

Determines whether DTD validation takes place.
  • Type: xs:boolean

  • Default: false

trueThe input is parsed using a validating XML parser. The input must contain a DOCTYPE declaration to identify the DTD to be used for validation. The DTD may be internal or external.
falseDTD validation does not take place. However, if a DOCTYPE declaration is present, then it is read, for example to perform entity expansion.

strip-space?

Determines whether whitespace-only text nodes are removed from the resulting document. (Note: in XSLT, the xsl:strip-space and xsl:preserve-space declarations are ignored.)
  • Type: xs:boolean

  • Default: false

trueAll whitespace-only text nodes are stripped, unless either (a) they are within the scope of the attribute xml:space="preserve", or (b) XSD validation identifies that the parent element has a simple type or a complex type with simple content.
falseAll whitespace-only text nodes are preserved, unless either (a) DTD validation marks them as ignorable, or (b) XSD validation recognizes the containing element as having element-only or empty content.

trusted?

Indicates whether processing the supplied document may cause external resources to be fetched (including, for example, external entities, an external DTD, or documents referenced using xsi:schemaLocation or XInclude elements).
  • Type: xs:boolean

  • Default: false()

trueThe document may include references to external resources.
falseThe document must not include references to external resources unless access to these resources has been explicitly enabled.

xinclude?

Determines whether any xi:include elements in the input are to be processed using an XInclude processor.
  • Type: xs:boolean

  • Default: false

trueAny xi:include elements are expanded. If there are xi:include elements and no XInclude processor is available then a dynamic error is raised.
falseAny xi:include elements are handled as ordinary elements without expansion.

xsd-validation?

Determines whether XSD validation takes place, using the schema definitions present in the static context. The effect of requesting validation is the same as invoking the parse-xml function without validation, and then applying an XQuery validate expression to the result, with corresponding options.
  • Type: xs:string

  • Default: "skip"

strictStrict XSD validation takes place
laxLax XSD validation takes place
skipNo XSD validation takes place
type Q{uri}localXSD validation takes place against the schema-defined type, present in the static context, that has the given URI and local name.

use-xsi-schema-location?

When XSD validation takes place, determines whether schema components referenced using xsi:schemaLocation or xsi:noNamespaceSchemaLocation attributes within the source document are to be used. The option is ignored if XSD validation does not take place.
  • Type: xs:boolean

  • Default: false

trueXSD validation uses the schema components referenced using xsi:schemaLocation or xsi:noNamespaceSchemaLocation attributes in addition to the schema components present in the static context; these components must be compatible as described in [XQuery and XPath Data Model (XDM) 4.0] section 4.1.2 Schema Consistency.
falseAny xsi:schemaLocation and xsi:noNamespaceSchemaLocation attributes in the document are ignored.

Except to the extent defined by these options, the precise process used to construct the XDM instance is implementation-defined. In particular, it is implementation-defined whether an XML 1.0 or XML 1.1 parser is used.

The document URI of the returned node is absentDM.

The function is notdeterministic: that is, if the function is called twice with the same arguments, it is implementation-dependent whether the same node is returned on both occasions.

Options set in $options may be supplemented or modified based on configuration options defined externally using implementation-defined mechanisms.

Error Conditions

A dynamic error is raised [err:FODC0006] if the content of $value is not a well-formed and namespace-well-formed XML document.

A dynamic error is raised [err:FODC0007] if DTD validation is carried out and the content of $value is not valid against the relevant DTD.

A dynamic error is raised [err:FODC0008] if the value of the xsd-validation option is not one of the permitted values (for example, if the string that follows "type" is not a valid EQName, or if it does not identify a type that is present in the static context).

A dynamic error is raised [err:FODC0009] if the value of the xsd-validation option is set to anything other than skip when the processor is not schema-aware. (XSLT 4.0 and XQuery 4.0 define schema-awareness as an optional feature; other host languages may set their own rules.)

A dynamic error is raised [err:FODC0013] if processor does not have access to an XML parser supporting the requested options, for example the ability to perform DTD validation or XInclude processing or to prevent access to external entities.

A dynamic error is raised [err:FODC0014] if XSD validation is carried out and the content of $value is not valid against the relevant XSD schema.

Notes

Since the XML document is presented to the parser as a string, rather than as a sequence of octets, the encoding specified within the XML declaration has no meaning. If the XML parser accepts input only in the form of a sequence of octets, then the processor must ensure that the string is encoded as octets in a way that is consistent with rules used by the XML parser to detect the encoding.

A common use case for this function is to handle input documents that contain nested XML documents embedded within CDATA sections. Since the content of the CDATA section is exposed as text, the receiving query or stylesheet may pass this text to the fn:parse-xml function to create a tree representation of the nested document.

Similarly, nested XML within comments is sometimes encountered, and lexical XML is sometimes returned by extension functions, for example, functions that access web services or read from databases.

A use case arises in XSLT where there is a need to preprocess an input document before parsing. For example, an application might wish to edit the document to remove its DOCTYPE declaration. This can be done by reading the raw text using the fn:unparsed-text function, editing the resulting string, and then passing it to the fn:parse-xml function.

Examples
ExpressionResult

The expression fn:parse-xml("<alpha>abcd</alpha>") returns a newly created document node, having an alpha element as its only child; the alpha element in turn is the parent of a text node whose string value is "abcd".

fn:parse-xml("<alpha>abcd</alpha>")
A newly
               created document node, having an alpha element as its only child; the
                  alpha element in turn is the parent of a text node whose string value
               is "abcd".

The expression fn:parse-xml("<alpha><beta> </beta></alpha>", { "strip-space": true() }) returns a newly created document node, having an alpha element as its only child; the alpha element in turn is the parent of a beta element whose content is empty, as a result of whitespace stripping.

fn:parse-xml("<alpha><beta> </beta></alpha>", { "strip-space": true() })
A newly
               created document node, having an alpha element as its only child; the
                  alpha element in turn is the parent of a beta
               element whose content is empty, as a result of whitespace stripping.

17.2.2 fn:parse-xml-fragment

Changes in 4.0 (next | previous)

  1. The $options parameter has been added.  [Issue 305 PR 1257 11 June 2024]

  2. Support for binary input has been added.  [Issue 748 PR 2013 20 May 2025]

Summary

This function takes as input an XML external entity represented as a string, and returns the document node at the root of an XDM tree representing the parsed document fragment.

Signature
fn:parse-xml-fragment(
$valueas (xs:string | xs:hexBinary | xs:base64Binary)?,
$optionsas map(*)?:= {}
) as document-node()?
Properties

This function is nondeterministic, context-dependent, and focus-independent. It depends on executable base URI.

Rules

If $value is the empty sequence, the function returns the empty sequence.

If the input is supplied as a binary value, the function detects the encoding using the same rules as the unparsed-text function, except that the special handling of media types such as text/xml and application/xml may be skipped. Otherwise, if the input is a string, any byte order mark as well as the encoding specified in an optional XML declaration should be ignored.

The input must be a namespace-well-formed external general parsed entity. More specifically, it must conform to the production rule extParsedEntXML in [Extensible Markup Language (XML) 1.0 (Fifth Edition)], it must contain no entity references other than references to predefined entities, and it must satisfy all the rules of [Namespaces in XML] for namespace-well-formed documents with the exception that the rule requiring it to be a well-formed document is replaced by the rule requiring it to be a well-formed external general parsed entity.

The input is parsed to form a sequence of nodes which become children of the new document node, in the same way as the content of any element is converted into a sequence of children for the resulting element node.

The $options argument, if present and non-empty, defines the detailed behavior of the function. The option parameter conventions apply. The options available are as follows:

record(
base-uri?as xs:anyURI,
strip-space?as xs:boolean
)
KeyValueMeaning

base-uri?

Determines the base URI. This is used as the base URI of the document node that is returned. It defaults to the static base URI of the function call.
  • Type: xs:anyURI

  • Default: static-base-uri()

strip-space?

Determines whether whitespace-only text nodes are removed from the resulting document.
  • Type: xs:boolean

  • Default: false

trueAll whitespace-only text nodes are stripped, unless they are within the scope of the attribute xml:space="preserve".
falseAll whitespace-only text nodes are preserved.

DTD validation is not invoked (an external general parsed entity cannot contain a DOCTYPE declaration.

Schema validation is not invoked, which means that the nodes in the returned document will all be untyped.

XInclude processing is not invoked.

Except as explicitly defined, the precise process used to construct the XDM instance is implementation-defined. In particular, it is implementation-defined whether an XML 1.0 or XML 1.1 parser is used.

The document URI of the returned node is absentDM.

The function is notdeterministic: that is, if the function is called twice with the same arguments, it is implementation-dependent whether the same node is returned on both occasions.

Error Conditions

A dynamic error is raised [err:FODC0006] if the content of $value is not a well-formed external general parsed entity, if it contains entity references other than references to predefined entities, or if a document that incorporates this well-formed parsed entity would not be namespace-well-formed.

Notes

See also the notes for the fn:parse-xml function.

The main differences between fn:parse-xml and fn:parse-xml-fragment are that for fn:parse-xml, the children of the resulting document node must contain exactly one element node and no text nodes, wheras for fn:parse-xml-fragment, the resulting document node can have any number (including zero) of element and text nodes among its children. An additional difference is that the text declaration at the start of an external entity has slightly different syntax from the XML declaration at the start of a well-formed document.

Note that all whitespace outside the text declaration is significant, including whitespace that precedes the first element node, unless the strip-space option is set.

One use case for this function is to handle XML fragments stored in databases, which frequently allow zero-or-more top level element nodes. Another use case is to parse the contents of a CDATA section embedded within another XML document.

Examples
ExpressionResult

The expression parse-xml-fragment("<alpha>abcd</alpha><beta>abcd</beta>") returns a newly created document node, having two elements named alpha and beta as its children; each of these elements in turn is the parent of a text node.

parse-xml-fragment("<alpha>abcd</alpha><beta>abcd</beta>")
A newly created document node, having two elements named alpha
               and beta as its children; each of these elements in turn is the parent
               of a text node.

The expression parse-xml-fragment("He was <i>so</i> kind") returns a newly created document node having three children: a text node whose string value is "He was ", an element node named i having a child text node with string value "so", and a text node whose string value is " kind".

parse-xml-fragment("He was <i>so</i> kind")
A newly created document node having three children: a text node whose string
               value is "He was ", an element node named i having a child
               text node with string value "so", and a text node whose string value is
                  " kind".

The expression parse-xml-fragment("") returns a document node having no children.

parse-xml-fragment("")
A document node having
               no children.

The expression parse-xml-fragment(" ") returns a document node whose children comprise a single text node whose string value is a single space.

parse-xml-fragment(" ")
A document node whose
               children comprise a single text node whose string value is a single space.
parse-xml-fragment(" ", { "strip-space": true() })

The expression parse-xml-fragment(" ", { "strip-space": true() })A returns a document node having no children.

parse-xml-fragment('<?xml version="1.0" encoding="UTF-8"
                  standalone="yes"?><a/>')

Raises error FODC0006.

The expression parse-xml-fragment('<?xml version="1.0" encoding="UTF-8" standalone="yes"?><a/>')(The results in a dynamic error [err:FODC0006] because the standalone keyword is not permitted in the text declaration that appears at the start of an external general parsed entity. (Thus, it is not the case that any input accepted by the fn:parse-xml function will also be accepted by the fn:parse-xml-fragment.)

20 Accessing the context

The following functions are defined to obtain information from the static or dynamic context.

FunctionMeaning
fn:current-dateReturns the current date.
fn:current-dateTimeReturns the current date and time (with timezone).
fn:current-timeReturns the current time.
fn:default-collationReturns the value of the default collation property from the dynamic context.
fn:default-languageReturns the value of the default language property from the dynamic context.
fn:implicit-timezoneReturns the value of the implicit timezone property from the dynamic context.
fn:lastReturns the context size from the dynamic context.
fn:positionReturns the context position from the dynamic context.
fn:static-base-uriThis function returns the value of the executable base URI property from the dynamic context.

20.1 fn:current-date

Summary

Returns the current date.

Signature
fn:current-date() as xs:date
Properties

This function is deterministic, context-dependent, and focus-independent. It depends on implicit timezone.

Rules

Returns xs:date(fn:current-dateTime()). This is an xs:date (with timezone) that is current at some time during the evaluation of a query or transformation in which fn:current-date is executed.

This function is deterministic. The precise instant during the query or transformation represented by the value of fn:current-date is implementation-dependent.

Notes

The returned date will always have an associated timezone, which will always be the same as the implicit timezone in the dynamic context

Examples
ExpressionResult

current-date() returns an xs:date corresponding to the current date. For example, a call of current-date() might return 2004-05-12+01:00.

current-date()
An xs:date corresponding to the
               current date. For example, a call of current-date() might return
                  2004-05-12+01:00.

20.2 fn:current-dateTime

Summary

Returns the current date and time (with timezone).

Signature
fn:current-dateTime() as xs:dateTimeStamp
Properties

This function is deterministic, context-dependent, and focus-independent. It depends on implicit timezone.

Rules

Returns the current dateTime (with timezone) from the dynamic context. (See [XML Path Language (XPath) 4.0] section B.2 Dynamic Context Components.) This is an xs:dateTime that is current at some time during the evaluation of a query or transformation in which fn:current-dateTime is executed.

This function is deterministic. The precise instant during the query or transformation represented by the value of fn:current-dateTime() is implementation-dependent.

If the implementation supports data types from XSD 1.1 then the returned value will be an instance of xs:dateTimeStamp. Otherwise, the only guarantees are that it will be an instance of xs:dateTime and will have a timezone component.

Notes

The returned xs:dateTime will always have an associated timezone, which will always be the same as the implicit timezone in the dynamic context

Examples
ExpressionResult

current-dateTime() returns an xs:dateTimeStamp corresponding to the current date and time. For example, a call of current-dateTime() might return 2004-05-12T18:17:15.125Z corresponding to the current time on May 12, 2004 in timezone Z.

current-dateTime()
An xs:dateTimeStamp
               corresponding to the current date and time. For example, a call of
                  current-dateTime() might return
                  2024-05-12T18:17:15.125Z corresponding to the current time on May 12,
               2024 in timezone Z.

20.3 fn:current-time

Summary

Returns the current time.

Signature
fn:current-time() as xs:time
Properties

This function is deterministic, context-dependent, and focus-independent. It depends on implicit timezone.

Rules

Returns xs:time(fn:current-dateTime()). This is an xs:time (with timezone) that is current at some time during the evaluation of a query or transformation in which fn:current-time is executed.

This function is deterministic. The precise instant during the query or transformation represented by the value of fn:current-time() is implementation-dependent.

Notes

The returned time will always have an associated timezone, which will always be the same as the implicit timezone in the dynamic context

Examples
ExpressionResult

current-time() returns an xs:time corresponding to the current time. For example, a call of current-time() might return 23:17:00.000-05:00.

current-time()
An xs:time corresponding to the
               current time. For example, a call of current-time() might return
                  23:17:00.000-05:00.

21 Errors and diagnostics

21.2 Diagnostic tracing

21.2.1 fn:trace

Changes in 4.0 (next | previous)

  1. The $label argument can now be set to the empty sequence. Previously if $label was supplied, it could not be empty.  [Issue 895 PR 901 16 December 2023]

Summary

Provides an execution trace intended to be used in debugging queries.

Signature
fn:trace(
$inputas item()*,
$labelas xs:string?:= ()
) as item()*
Properties

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

Rules

The function returns $input, unchanged.

In addition, the values of $input, typically serialized and converted to an xs:string, and $label (if supplied and non-empty) may be output to an implementation-defined destination.

Any serialization of the implementation’s trace output must not raise an error. This can be achieved (for example) by using a serialization method that can handle arbitrary input, such as the adaptive output method (see 10 Adaptive Output Method SER31).

The format of the trace output and its order are implementation-dependent. Therefore, the order in which the output appears is not predictable. This also means that if dynamic errors occur (whether or not they are caught using try/catch), it may be unpredictable whether any output is reported before the error occurs.

Notes

If the trace information is unrelated to a specific value, fn:message can be used instead.

Examples
Expression:

Consider a situation in which a user wants to investigate the actual value passed to a function. Assume that in a particular execution, $v is an xs:decimal with value 124.84. Writing fn:trace($v, 'the value of $v is:') will return $v. The processor may output "124.84" and "the value of $v is:" to an implementation-defined destination.

fn:trace($v, 'the value of $v is: ')
Result:

The following two XPath expressions are identical, but only the second provides trace feedback to the user:

Supposing that $v is an xs:decimal
               with the value 124.84, the function returns the value 124.84,
               while outputting a message such as "the value of $v is: 124.84" to 
               an  destination. The format of the message
               is also .
Expression:
  • //book[xs:decimal(@price) gt 100]

  • //book[xs:decimal(@price) gt 100] => trace('books more expensive than €100:')

//book[xs:decimal(@price) gt 100] 
    => trace('books more expensive than €100:')
Result:
The result of the expression is the same as the result of
               //book[xs:decimal(@price) gt 100], but evaluation has the side-effect of
               providing diagnostic feedback to the user.

21.2.2 fn:message

Changes in 4.0 (next | previous)

  1. New in 4.0  [Issues 574 651 PRs 629 803 7 November 2023]

Summary

Outputs trace information and discards the result.

Signature
fn:message(
$inputas item()*,
$labelas xs:string?:= ()
) as empty-sequence()
Properties

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

Rules

Similar to fn:trace, the values of $input, typically serialized and converted to an xs:string, and $label (if supplied and non-empty) may be output to an implementation-defined destination.

In contrast to fn:trace, the function returns the empty sequence.

Any serialization of the implementation’s log output must not raise an error. This can e.g. be achieved by using a serialization method that can handle arbitrary input, such as the 10 Adaptive Output Method SER31.

The format of the log output and its order are implementation-dependent. Therefore, the order in which the output appears is not predictable. This also means that if dynamic errors occur (whether or not they are caught using try/catch), it may be unpredictable whether any output is logged before the error occurs.

Notes

The function can be used for debugging. It can also be helpful in productive environments, e.g. to store dynamic input and evaluations to log files.

Examples
Expression:

The following two XPath expressions are identical, but only the second logs any feedback:

//book[if (xs:decimal(@price) lt 1000) 
                     then true() 
                     else message(@price, @title || ' is unexpectedly expensive: ')]
Result:
  • //book[xs:decimal(@price) lt 1000]

  • //book[if (xs:decimal(@price) lt 1000) then true() else message(@price, @title || ' is unexpectedly expensive: ')]

The result of the expression is the same as the result of
               //book[xs:decimal(@price) lt 1000], but evaluation has the side-effect of
               providing diagnostic feedback to the user relating to books above this price threshold.

G Implementation-defined features (Non-Normative)

  1. It is implementation-defined which version of Unicode is supported, but it is recommended that the most recent version of Unicode be used. (See Conformance.)

  2. It is implementation-defined whether the type system is based on XML Schema 1.0 or XML Schema 1.1. (See Conformance.)

  3. It is implementation-defined whether definitions that rely on XML (for example, the set of valid XML characters) should use the definitions in XML 1.0 or XML 1.1. (See Conformance.)

  4. Implementations may attach an implementation-defined meaning to options in the map that are not described in this specification. These options should use values of type xs:QName as the option names, using an appropriate namespace. (See Options.)

  5. It is implementation-defined which version of [The Unicode Standard] is supported, but it is recommended that the most recent version of Unicode be used. (See Strings, characters, and codepoints.)

  6. [Definition] Some functions (such as fn:in-scope-prefixes, fn:load-xquery-module, and fn:unordered) produce result sequences or result maps in an implementation-defined or implementation-dependent order. In such cases two calls with the same arguments are not guaranteed to produce the results in the same order. These functions are said to be nondeterministic with respect to ordering. (See Properties of functions.)

  7. Where the results of a function are described as being (to a greater or lesser extent) implementation-defined or implementation-dependent, this does not by itself remove the requirement that the results should be deterministic: that is, that repeated calls with the same explicit and implicit arguments must return identical results. (See Properties of functions.)

  8. They may provide an implementation-defined mechanism that allows users to choose between raising an error and returning a result that is modulo the largest representable integer value. See [ISO 10967]. (See Arithmetic operators on numeric values.)

  9. For xs:decimal values, let N be the number of digits of precision supported by the implementation, and let M (M <= N) be the minimum limit on the number of digits required for conformance (18 digits for XSD 1.0, 16 digits for XSD 1.1). Then for addition, subtraction, and multiplication operations, the returned result should be accurate to N digits of precision, and for division and modulus operations, the returned result should be accurate to at least M digits of precision. The actual precision is implementation-defined. If the number of digits in the mathematical result exceeds the number of digits that the implementation retains for that operation, the result is truncated or rounded in an implementation-defined manner. (See Arithmetic operators on numeric values.)

  10. The [IEEE 754-2019] specification also describes handling of two exception conditions called divideByZero and invalidOperation. The IEEE divideByZero exception is raised not only by a direct attempt to divide by zero, but also by operations such as log(0). The IEEE invalidOperation exception is raised by attempts to call a function with an argument that is outside the function’s domain (for example, sqrt(-1) or log(-1)). Although IEEE defines these as exceptions, it also defines “default non-stop exception handling” in which the operation returns a defined result, typically positive or negative infinity, or NaN. With this function library, these IEEE exceptions do not cause a dynamic error at the application level; rather they result in the relevant function or operator returning the defined non-error result. The underlying IEEE exception may be notified to the application or to the user by some implementation-defined warning condition, but the observable effect on an application using the functions and operators defined in this specification is simply to return the defined result (typically -INF, +INF, or NaN) with no error. (See Arithmetic operators on numeric values.)

  11. The [IEEE 754-2019] specification distinguishes two NaN values: a quiet NaN and a signaling NaN. These two values are not distinguishable in the XDM model: the value spaces of xs:float and xs:double each include only a single NaN value. This does not prevent the implementation distinguishing them internally, and triggering different implementation-defined warning conditions, but such distinctions do not affect the observable behavior of an application using the functions and operators defined in this specification. (See Arithmetic operators on numeric values.)

  12. The implementation may adopt a different algorithm provided that it is equivalent to this formulation in all cases where implementation-dependent or implementation-defined behavior does not affect the outcome, for example, the implementation-defined precision of the result of xs:decimal division. (See op:numeric-integer-divide.)

  13. There may be implementation-defined limits on the precision available. If the requested $precision is outside this range, it should be adjusted to the nearest value supported by the implementation. (See fn:divide-decimals.)

  14. There may be implementation-defined limits on the precision available. If the requested $precision is outside this range, it should be adjusted to the nearest value supported by the implementation. (See fn:round.)

  15. There may be implementation-defined limits on the precision available. If the requested $precision is outside this range, it should be adjusted to the nearest value supported by the implementation. (See fn:round-half-to-even.)

  16. XSD 1.1 allows the string +INF as a representation of positive infinity; XSD 1.0 does not. It is implementation-defined whether XSD 1.1 is supported. (See fn:number.)

  17. Any other format token, which indicates a numbering sequence in which that token represents the number 1 (one) (but see the note below). It is implementation-defined which numbering sequences, additional to those listed above, are supported. If an implementation does not support a numbering sequence represented by the given token, it must use a format token of 1. (See fn:format-integer.)

  18. For all format tokens other than a digit-pattern, there may be implementation-defined lower and upper bounds on the range of numbers that can be formatted using this format token; indeed, for some numbering sequences there may be intrinsic limits. For example, the format token U+2460 (CIRCLED DIGIT ONE, ) has a range imposed by the Unicode character repertoire — zero to 20 in Unicode versions prior to 3.2, or zero to 50 in subsequent versions. For the numbering sequences described above any upper bound imposed by the implementation must not be less than 1000 (one thousand) and any lower bound must not be greater than 1. Numbers that fall outside this range must be formatted using the format token 1. (See fn:format-integer.)

  19. The set of languages for which numbering is supported is implementation-defined. If the $language argument is absent, or is set to the empty sequence, or is invalid, or is not a language supported by the implementation, then the number is formatted using the default language from the dynamic context. (See fn:format-integer.)

  20. ...either a or t, to indicate alphabetic or traditional numbering respectively, the default being implementation-defined. (See fn:format-integer.)

  21. The string of characters between the parentheses, if present, is used to select between other possible variations of cardinal or ordinal numbering sequences. The interpretation of this string is implementation-defined. No error occurs if the implementation does not define any interpretation for the defined string. (See fn:format-integer.)

  22. It is implementation-defined what combinations of values of the format token, the language, and the cardinal/ordinal modifier are supported. If ordinal numbering is not supported for the combination of the format token, the language, and the string appearing in parentheses, the request is ignored and cardinal numbers are generated instead. (See fn:format-integer.)

  23. The use of the a or t modifier disambiguates between numbering sequences that use letters. In many languages there are two commonly used numbering sequences that use letters. One numbering sequence assigns numeric values to letters in alphabetic sequence, and the other assigns numeric values to each letter in some other manner traditional in that language. In English, these would correspond to the numbering sequences specified by the format tokens a and i. In some languages, the first member of each sequence is the same, and so the format token alone would be ambiguous. In the absence of the a or t modifier, the default is implementation-defined. (See fn:format-integer.)

  24. The static context provides a set of decimal formats. One of the decimal formats is unnamed, the others (if any) are identified by a QName. There is always an unnamed decimal format available, but its contents are implementation-defined. (See Defining a decimal format.)

  25. IEEE states that the preferred quantum is language-defined. In this specification, it is implementation-defined. (See Trigonometric and exponential functions.)

  26. IEEE defines various rounding algorithms for inexact results, and states that the choice of rounding direction, and the mechanisms for influencing this choice, are language-defined. In this specification, the rounding direction and any mechanisms for influencing it are implementation-defined. (See Trigonometric and exponential functions.)

  27. The map returned by the fn:random-number-generator function may contain additional entries beyond those specified here, but it must match the record type defined above. The meaning of any additional entries is implementation-defined. To avoid conflict with any future version of this specification, the keys of any such entries should start with an underscore character. (See fn:random-number-generator.)

  28. It is no longer automatically an error if the input contains a codepoint that is not valid in XML. Instead, the codepoint must be a permitted character. The set of permitted characters is implementation-defined, but it is recommended that all Unicode characters should be accepted. (See fn:codepoints-to-string.)

  29. If two query parameters use the same keyword then the last one wins. If a query parameter uses a keyword or value which is not defined in this specification then the meaning is implementation-defined. If the implementation recognizes the meaning of the keyword and value then it should interpret it accordingly; if it does not recognize the keyword or value then if the fallback parameter is present with the value no it should reject the collation as unsupported, otherwise it should ignore the unrecognized parameter. (See The Unicode Collation Algorithm.)

  30. The following query parameters are defined. If any parameter is absent, the default is implementation-defined except where otherwise stated. The meaning given for each parameter is non-normative; the normative specification is found in [UTS #35]. (See The Unicode Collation Algorithm.)

  31. Because the set of collations that are supported is implementation-defined, an implementation has the option to support all collation URIs, in which case it will never raise this error. (See Choosing a collation.)

  32. The properties available are as defined for the Unicode Collation Algorithm (see 5.3.4 The Unicode Collation Algorithm). Additional implementation-defined properties may be specified as described in the rules for UCA collation URIs. (See fn:collation.)

  33. It is possible to define collations that do not have the ability to generate collation keys. Supplying such a collation will cause the function to fail. The ability to generate collation keys is an implementation-defined property of the collation. (See fn:collation-key.)

  34. Conforming implementations must support normalization form NFC and may support normalization forms NFD, NFKC, NFKD, and FULLY-NORMALIZED. They may also support other normalization forms with implementation-defined semantics. (See fn:normalize-unicode.)

  35. It is implementation-defined which version of Unicode (and therefore, of the normalization algorithms and their underlying data) is supported by the implementation. See [UAX #15] for details of the stability policy regarding changes to the normalization rules in future versions of Unicode. If the input string contains codepoints that are unassigned in the relevant version of Unicode, or for which no normalization rules are defined, the fn:normalize-unicode function leaves such codepoints unchanged. If the implementation supports the requested normalization form then it must be able to handle every input string without raising an error. (See fn:normalize-unicode.)

  36. It is possible to define collations that do not have the ability to decompose a string into units suitable for substring matching. An argument to a function defined in this section may be a URI that identifies a collation that is able to compare two strings, but that does not have the capability to split the string into collation units. Such a collation may cause the function to fail, or to give unexpected results, or it may be rejected as an unsuitable argument. The ability to decompose strings into collation units is an implementation-defined property of the collation. The fn:collation-available function can be used to ask whether a particular collation has this property. (See Functions based on substring matching.)

  37. The result of the function will always be such that validation against this schema would succeed. However, it is implementation-defined whether the result is typed or untyped, that is, whether the elements and attributes in the returned tree have type annotations that reflect the result of validating against this schema. (See fn:analyze-string.)

  38. Some URI schemes are hierarchical and some are non-hierarchical. Implementations must treat the following schemes as non-hierarchical: jar, mailto, news, tag, tel, and urn. Whether additional schemes are known to be non-hierarchical implementation-defined. If a scheme is not known to be non-hierarchical, it must be treated as hierarchical. (See Parsing and building URIs.)

  39. If the omit-default-ports option is true, the port is discarded and set to the empty sequence if the port number is the same as the default port for the given scheme. Implementations should recognize the default ports for http (80), https (443), ftp (21), and ssh (22). Exactly which ports are recognized is implementation-defined. (See fn:parse-uri.)

  40. If the omit-default-ports option is true then the $port is set to the empty sequence if the port number is the same as the default port for the given scheme. Implementations should recognize the default ports for http (80), https (443), ftp (21), and ssh (22). Exactly which ports are recognized is implementation-defined. (See fn:build-uri.)

  41. Processors may support a greater range and/or precision. The limits are implementation-defined. (See Limits and precision.)

  42. Similarly, a processor may be unable accurately to represent the result of dividing a duration by 2, or multiplying a duration by 0.5. A processor that limits the precision of the seconds component of duration values must deliver a result that is as close as possible to the mathematically precise result, given these limits; if two values are equally close, the one that is chosen is implementation-defined. (See Limits and precision.)

  43. All conforming processors must support year values in the range 1 to 9999, and a minimum fractional second precision of 1 millisecond or three digits (that is, s.sss). However, processors may set larger implementation-defined limits on the maximum number of digits they support in these two situations. Processors may also choose to support the year 0 and years with negative values. The results of operations on dates that cross the year 0 are implementation-defined. (See Limits and precision.)

  44. Similarly, a processor that limits the precision of the seconds component of date and time or duration values may need to deliver a rounded result for arithmetic operations. Such a processor must deliver a result that is as close as possible to the mathematically precise result, given these limits: if two values are equally close, the one that is chosen is implementation-defined. (See Limits and precision.)

  45. ...the format token n, N, or Nn, indicating that the value of the component is to be output by name, in lower-case, upper-case, or title-case respectively. Components that can be output by name include (but are not limited to) months, days of the week, timezones, and eras. If the processor cannot output these components by name for the chosen calendar and language then it must use an implementation-defined fallback representation. (See The picture string.)

  46. ...indicates alphabetic or traditional numbering respectively, the default being implementation-defined. This has the same meaning as in the second argument of fn:format-integer. (See The picture string.)

  47. The sequence of characters in the (adjusted) first presentation modifier is reversed (for example, 999'### becomes ###'999). If the result is not a valid decimal digit pattern, then the output is implementation-defined. (See Formatting Fractional Seconds.)

  48. The output for these components is entirely implementation-defined. The default presentation modifier for these components is n, indicating that they are output as names (or conventional abbreviations), and the chosen names will in many cases depend on the chosen language: see 9.9.4.8 The language, calendar, and place arguments. (See Formatting Other Components.)

  49. The set of languages, calendars, and places that are supported in the date formatting functions is implementation-defined. When any of these arguments is omitted or is the empty sequence, an implementation-defined default value is used. (See The language, calendar, and place arguments.)

  50. The choice of the names and abbreviations used in any given language is implementation-defined. For example, one implementation might abbreviate July as Jul while another uses Jly. In German, one implementation might represent Saturday as Samstag while another uses Sonnabend. Implementations may provide mechanisms allowing users to control such choices. (See The language, calendar, and place arguments.)

  51. The choice of the names and abbreviations used in any given language for calendar units such as days of the week and months of the year is implementation-defined. (See The language, calendar, and place arguments.)

  52. The calendar value if present must be a valid EQName (dynamic error: [err:FOFD1340]). If it is a lexical QName then it is expanded into an expanded QName using the statically known namespaces; if it has no prefix then it represents an expanded-QName in no namespace. If the expanded QName is in no namespace, then it must identify a calendar with a designator specified below (dynamic error: [err:FOFD1340]). If the expanded QName is in a namespace then it identifies the calendar in an implementation-defined way. (See The language, calendar, and place arguments.)

  53. At least one of the above calendars must be supported. It is implementation-defined which calendars are supported. (See The language, calendar, and place arguments.)

  54. If the arguments to fn:function-lookup identify a function that is present in the static context of the function call, the function will always return the same function that a static reference to this function would bind to. If there is no such function in the static context, then the results depend on what is present in the dynamic context, which is implementation-defined. (See fn:function-lookup.)

  55. It is to some extent implementation-defined whether two maps or arrays have the same function identity. Processors should ensure as a minimum that when a variable $m is bound to a map or array, calling jtree($m) more than once (with the same variable reference) will deliver the same JNode each time. (See fn:jtree.)

  56. The requirement to deliver a deterministic result has performance implications, and for this reason implementations may provide a user option to evaluate the function without a guarantee of determinism. The manner in which any such option is provided is implementation-defined. If the user has not selected such an option, a call of the function must either return a deterministic result or must raise a dynamic error [err:FODC0003]. (See fn:doc.)

  57. Various aspects of this processing are implementation-defined. Implementations may provide external configuration options that allow any aspect of the processing to be controlled by the user. In particular:... (See fn:doc.)

  58. It is implementation-defined whether DTD validation and/or schema validation is applied to the source document. (See fn:doc.)

  59. The effect of a fragment identifier in the supplied URI is implementation-defined. One possible interpretation is to treat the fragment identifier as an ID attribute value, and to return a document node having the element with the selected ID value as its only child. (See fn:doc.)

  60. By default, this function is deterministic. This means that repeated calls on the function with the same argument will return the same result. However, for performance reasons, implementations may provide a user option to evaluate the function without a guarantee of determinism. The manner in which any such option is provided is implementation-defined. If the user has not selected such an option, a call to this function must either return a deterministic result or must raise a dynamic error [err:FODC0003]. (See fn:collection.)

  61. By default, this function is deterministic. This means that repeated calls on the function with the same argument will return the same result. However, for performance reasons, implementations may provide a user option to evaluate the function without a guarantee of determinism. The manner in which any such option is provided is implementation-defined. If the user has not selected such an option, a call to this function must either return a deterministic result or must raise a dynamic error [err:FODC0003]. (See fn:uri-collection.)

  62. It is no longer automatically an error if the resource (after decoding) contains a codepoint that is not valid in XML. Instead, the codepoint must be a permitted character. The set of permitted characters is implementation-defined, but it is recommended that all Unicode characters should be accepted. (See fn:unparsed-text.)

  63. ...the encoding inferred from the initial octets of the resource, or from implementation-defined heuristics as defined by the rules of the bin:infer-encoding function. (See fn:unparsed-text.)

  64. The fact that the resolution of URIs is defined by a mapping in the dynamic context means that in effect, various aspects of the behavior of this function are implementation-defined. Implementations may provide external configuration options that allow any aspect of the processing to be controlled by the user. In particular:... (See fn:unparsed-text.)

  65. The fact that the resolution of URIs is defined by a mapping in the dynamic context means that in effect, various aspects of the behavior of this function are implementation-defined. Implementations may provide external configuration options that allow any aspect of the processing to be controlled by the user. In particular:... (See fn:unparsed-binary.)

  66. The collation used for matching names is implementation-defined, but must be the same as the collation used to ensure that the names of all environment variables are unique. (See fn:environment-variable.)

  67. Except to the extent defined by these options, the precise process used to construct the XDM instance is implementation-defined. In particular, it is implementation-defined whether an XML 1.0 or XML 1.1 parser is used. (See fn:parse-xml.)

  68. Options set in $options may be supplemented or modified based on configuration options defined externally using implementation-defined mechanisms. (See fn:parse-xml.)

  69. Except as explicitly defined, the precise process used to construct the XDM instance is implementation-defined. In particular, it is implementation-defined whether an XML 1.0 or XML 1.1 parser is used. (See fn:parse-xml-fragment.)

  70. If the second argument is omitted, or is supplied in the form of an output:serialization-parameters element, then the values of any serialization parameters that are not explicitly specified is implementation-defined, and may depend on the context. (See fn:serialize.)

  71. A list of target namespaces identifying schema components to be used for validation. The way in which the processor locates schema components for the specified target namespaces is implementation-defined. A zero-length string denotes a no-namespace schema.... (See fn:xsd-validator.)

  72. Set to the decimal value 1.0 or 1.1 to indicate which version of XSD is to be used. The default is implementation-defined. A processor may use a later version of XSD than the version requested, but must not use an earlier version.... (See fn:xsd-validator.)

  73. The XSD specification allows a schema to be used for validation even when it contains unresolved references to absent schema components. It is implementation-defined whether this function allows the schema to be incomplete in this way. For example, some processors might allow validation using a schema in which an element declaration contains a reference to a type declaration that is not present in the schema, provided that the element declaration is never needed in the course of a particular validation episode. (See fn:xsd-validator.)

  74. ...error-details as map(*)*. This field is present only when (a) the option return-error-details was set to true, and (b) the supplied document was found to be invalid. The value is a sequence of maps, each containing details of one invalidity that was found. The precise details of the invalidities are implementation-defined, but they may include the following fields, if the information is available:... (See fn:xsd-validator.)

  75. Because the [DOM: Living Standard] and [HTML: Living Standard] are not fixed, it is implementation-defined which versions are used. (See XDM Mapping from HTML DOM Nodes.)

  76. If an implementation allows these nodes to be passed in via an API or similar mechanism, their behaviour is implementation-defined. (See XDM Mapping from HTML DOM Nodes.)

  77. If the local name contains a character that is not a valid XML NameStartChar or NameChar, then an implementation-defined replacement string is used. The result must be a valid NCName. (See node-name Accessor.)

  78. If the local name contains a character that is not a valid XML NameStartChar or NameChar, then an implementation-defined replacement string is used. The result must be a valid NCName. (See node-name Accessor.)

  79. The input may contain deviations from the grammar of [RFC 7159], which are handled in an implementation-defined way. (Note: some popular extensions include allowing quotes on keys to be omitted, allowing a comma to appear after the last item in an array, allowing leading zeroes in numbers, and allowing control characters such as tab and newline to be present in unescaped form.) Since the extensions accepted are implementation-defined, an error may be raised [err:FOJS0001] if the input does not conform to the grammar. (See fn:parse-json.)

  80. The supplied function is called to process the string value of any JSON number in the input. By default, numbers are processed by converting to xs:double using the XPath casting rules. Supplying the value xs:decimal#1 will instead convert to xs:decimal (which potentially retains more precision, but disallows exponential notation), while supplying a function that casts to (xs:decimal | xs:double) will treat the value as xs:decimal if there is no exponent, or as xs:double otherwise. Supplying the value fn:identity#1 causes the value to be retained unchanged as an xs:untypedAtomic. If the liberal option is false (the default), then the supplied number-parser is called if and only if the value conforms to the JSON grammar for numbers (for example, a leading plus sign and redundant leading zeroes are not allowed). If the liberal option is true then it is also called if the value conforms to an implementation-defined extension of this grammar. (See fn:parse-json.)

  81. It is no longer automatically an error if the input contains a codepoint that is not valid in XML. Instead, the codepoint must be a permitted character. The set of permitted characters is implementation-defined, but it is recommended that all Unicode characters should be accepted. (See fn:json-doc.)

  82. The input may contain deviations from the grammar of [RFC 7159], which are handled in an implementation-defined way. (Note: some popular extensions include allowing quotes on keys to be omitted, allowing a comma to appear after the last item in an array, allowing leading zeroes in numbers, and allowing control characters such as tab and newline to be present in unescaped form.) Since the extensions accepted are implementation-defined, an error may be raised (see below) if the input does not conform to the grammar. (See fn:json-to-xml.)

  83. Default: Implementation-defined. (See fn:json-to-xml.)

  84. Indicates that the resulting XDM instance must be typed; that is, the element and attribute nodes must carry the type annotations that result from validation against the schema given at D.2 Schema for the result of fn:json-to-xml, or against an implementation-defined schema if the liberal option has the value true. (See fn:json-to-xml.)

  85. The result of the function will always be such that validation against this schema would succeed. However, it is implementation-defined whether the result is typed or untyped, that is, whether the elements and attributes in the returned tree have type annotations that reflect the result of validating against this schema. (See fn:csv-to-xml.)

  86. Additional, implementation-defined options may be available, for example, to control aspects of the XML serialization, to specify the grammar start symbol, or to produce output formats other than XML. (See fn:invisible-xml.)

  87. Default: The version given in the prolog of the library module; or implementation-defined if this is absent. (See fn:load-xquery-module.)

  88. A sequence of URIs (in the form of xs:string values) which may be used or ignored in an implementation-defined way.... (See fn:load-xquery-module.)

  89. Values for vendor-defined configuration options for the XQuery processor used to process the request. The key is the name of an option, expressed as a QName: the namespace URI of the QName should be a URI controlled by the vendor of the XQuery processor. The meaning of the associated value is implementation-defined. Implementations should ignore options whose names are in an unrecognized namespace. The option parameter conventions do not apply to this contained map.... (See fn:load-xquery-module.)

  90. It is implementation-defined whether constructs in the library module are evaluated in the same execution scope as the calling module. (See fn:load-xquery-module.)

  91. The library module that is loaded may import schema declarations using an import schema declaration. It is implementation-defined whether schema components in the in-scope schema definitions of the calling module are automatically added to the in-scope schema definitions of the dynamically loaded module. The in-scope schema definitions of the calling and called modules must be consistent, according to the rules defined in 2.2.5 Consistency Constraints XQ31. (See fn:load-xquery-module.)

  92. The serialized result is written to persistent storage. This means that the fn:transform function has side-effects and becomes nondeterministic, so the option should be used with care, and the precise behavior may be implementation-defined. When this option is used, the URIs used for the base-output-uri and the URIs of any secondary result documents must be writable locations. (See fn:transform.)

  93. Indicates whether any xsl:message instructions in the stylesheet are to be evaluated. The destination and formatting of any such messages is implementation-defined. (See fn:transform.)

  94. Default: Implementation-defined. (See fn:transform.)

  95. Default: Implementation-defined. (See fn:transform.)

  96. If the implementation provides a way of writing or invoking functions with side-effects, this post-processing function might be used to save a copy of the result document to persistent storage. For example, if the implementation provides access to the EXPath File library [EXPath], then a serialized document might be written to filestore by calling the file:write function. Similar mechanisms might be used to issue an HTTP POST request that posts the result to an HTTP server, or to send the document to an email recipient. The semantics of calling functions with side-effects are entirely implementation-defined. (See fn:transform.)

  97. Calls to fn:transform can potentially have side-effects even in the absence of the post-processing option, because the XSLT specification allows a stylesheet to invoke extension functions that have side-effects. The semantics in this case are implementation-defined. (See fn:transform.)

  98. A string intended to be used as the static base URI of the principal stylesheet module. This value must be used if no other static base URI is available. If the supplied stylesheet already has a base URI (which will generally be the case if the stylesheet is supplied using stylesheet-node or stylesheet-location) then it is implementation-defined whether this parameter has any effect. If the value is a relative reference, it is resolved against the executable base URIXP of the fn:transform function call.... (See fn:transform.)

  99. Values for vendor-defined configuration options for the XSLT processor used to process the request. The key is the name of an option, expressed as a QName: the namespace URI of the QName should be a URI controlled by the vendor of the XSLT processor. The meaning of the associated value is implementation-defined. Implementations should ignore options whose names are in an unrecognized namespace. Default is the empty map.... (See fn:transform.)

  100. It is implementation-defined whether the XSLT transformation is executed within the same execution scope as the calling code. (See fn:transform.)

  101. XSLT 1.0 does not define any error codes, so this is the likely outcome with an XSLT 1.0 processor. XSLT 2.0 and 3.0 do define error codes, but some APIs do not expose them. If multiple errors are signaled by the transformation (which is most likely to happen with static errors) then the error code should where possible be that of one of these errors, chosen arbitrarily; the processor may make details of additional errors available to the application in an implementation-defined way. (See fn:transform.)

  102. In addition, the values of $input, typically serialized and converted to an xs:string, and $label (if supplied and non-empty) may be output to an implementation-defined destination. (See fn:trace.)

  103. Consider a situation in which a user wants to investigate the actual value passed to a function. Assume that in a particular execution, $v is an xs:decimal with value 124.84. Writing fn:trace($v, 'the value of $v is:') will return $v. The processor may output "124.84" and "the value of $v is:" to an implementation-defined destination. (See fn:trace.)

  104. Similar to fn:trace, the values of $input, typically serialized and converted to an xs:string, and $label (if supplied and non-empty) may be output to an implementation-defined destination. (See fn:message.)

  105. If ST is xs:float or xs:double, then TV is the xs:decimal value, within the set of xs:decimal values that the implementation is capable of representing, that is numerically closest to SV. If two values are equally close, then the one that is closest to zero is chosen. If SV is too large to be accommodated as an xs:decimal, (see [XML Schema Part 2: Datatypes Second Edition] for implementation-defined limits on numeric values) a dynamic error is raised [err:FOCA0001]. If SV is one of the special xs:float or xs:double values NaN, INF, or -INF, a dynamic error is raised [err:FOCA0002]. (See Casting to xs:decimal.)

  106. In casting to xs:decimal or to a type derived from xs:decimal, if the value is not too large or too small but nevertheless cannot be represented accurately with the number of decimal digits available to the implementation, the implementation may round to the nearest representable value or may raise a dynamic error [err:FOCA0006]. The choice of rounding algorithm and the choice between rounding and error behavior is implementation-defined. (See Casting from xs:string and xs:untypedAtomic.)

  107. If ST is xs:decimal, xs:float or xs:double, then TV is SV with the fractional part discarded and the value converted to xs:integer. Thus, casting 3.1456 returns 3 while -17.89 returns -17. Casting 3.124E1 returns 31. If SV is too large to be accommodated as an integer, (see [XML Schema Part 2: Datatypes Second Edition] for implementation-defined limits on numeric values) a dynamic error is raised [err:FOCA0003]. If SV is one of the special xs:float or xs:double values NaN, INF, or -INF, a dynamic error is raised [err:FOCA0002]. (See Casting to xs:integer.)

  108. The tz timezone database, available at http://www.iana.org/time-zones. It is implementation-defined which version of the database is used. (See IANA Timezone Database.)

  109. Unicode Standard Annex #15: Unicode Normalization Forms. Ed. Mark Davis and Ken Whistler, Unicode Consortium. The current version is 16.0.0, dated 2024-08-14. As with [The Unicode Standard], the version to be used is implementation-defined. Available at: http://www.unicode.org/reports/tr15/. (See UAX #15.)

  110. Unicode Standard Annex #29: Unicode Text Segmentation. Ed. Josh Hadley, Unicode Consortium. The current version is 16.0.0, dated 2024-08-28. As with [The Unicode Standard], the version to be used is implementation-defined. Available at: http://www.unicode.org/reports/tr29/. (See UAX #29.)

  111. The Unicode Consortium, Reading, MA, Addison-Wesley, 2016. The Unicode Standard as updated from time to time by the publication of new versions. See http://www.unicode.org/standard/versions/ for the latest version and additional information on versions of the standard and of the Unicode Character Database. The version of Unicode to be used is implementation-defined, but implementations are recommended to use the latest Unicode version; currently, Version 9.0.0. (See The Unicode Standard.)

  112. Unicode Technical Standard #10: Unicode Collation Algorithm. Ed. Mark Davis and Ken Whistler, Unicode Consortium. The current version is 16.0.0, dated 2024-08-22. As with [The Unicode Standard], the version to be used is implementation-defined. Available at: http://www.unicode.org/reports/tr10/. (See UTS #10.)

  113. Unicode Technical Standard #35: Unicode Locale Data Markup Language. Ed Mark Davis et al, Unicode Consortium. The current version is 47, dated 2025-03-11. As with [The Unicode Standard], the version to be used is implementation-defined. Available at: http://www.unicode.org/reports/tr35/. (See UTS #35.)