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 2 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/>

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

See also translations.

This document is also available in these non-normative formats: Specification in XML format using HTML5 vocabulary, XML function catalog, and HTML with change markings relative to version 3.0.


Abstract

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

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

Status of this Document

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

Dedication

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


2 Functions on nodes and node sequences

2.1 Accessors

Accessors and their semantics are described in [XQuery and XPath Data Model (XDM) 3.1]. Some of these accessors are exposed to the user through the functions described below.

Each of these functions has an arity-zero signature which is equivalent to the arity-one form, with the context value supplied as the implicit first argument. In addition, each of the arity-one functions accepts an empty sequence as the argument, in which case it generally delivers an empty sequence as the result: the exception is fn:string, which delivers a zero-length string.

FunctionAccessorAcceptsReturns
fn:node-namenode-namenode (optional)xs:QName (optional)
fn:nillednillednode (optional)xs:boolean (optional)
fn:stringstring-valueitem (optional)xs:string
fn:datatyped-valuezero or more itemsa sequence of atomic items
fn:base-uribase-urinode (optional)xs:anyURI (optional)
fn:document-uridocument-urinode (optional)xs:anyURI (optional)
FunctionMeaning
fn:node-nameReturns the name of a node, as an xs:QName.
fn:nilledReturns true for an element that is nilled.
fn:stringReturns the value of $value represented as an xs:string.
fn:dataReturns the result of atomizing a sequence. This process flattens arrays, and replaces nodes by their typed values.
fn:base-uriReturns the base URI of a node.
fn:document-uriReturns the URI of a resource where a document can be found, if available.

2.1.1 fn:node-name

Summary

Returns the name of a node, as an xs:QName.

Signature
fn:node-name(
$nodeas node()?:= .
) as xs:QName?
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 (.).

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

Otherwise, the function returns the result of the dm:node-name accessor as defined in [XQuery and XPath Data Model (XDM) 3.1] (see Section 4.10 node-name AccessorDM).

Error Conditions

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

Notes

For element and attribute nodes, the name of the node is returned as an xs:QName, retaining the prefix, namespace URI, and local part.

For processing instructions, the name of the node is returned as an xs:QName in which the prefix and namespace URI are absentDM.

For a namespace node, the function returns an empty sequence if the node represents the default namespace; otherwise it returns an xs:QName in which prefix and namespace URI are absentDM and the local part is the namespace prefix being bound.

For all other kinds of node, the function returns the empty sequence.

For element and attribute nodes, the name of the node is returned as an xs:QName, retaining the prefix, namespace URI, and local part.

For processing instructions, the name of the node is returned as an xs:QName in which the prefix and namespace URI are absentDM.

For a namespace node, the function returns an empty sequence if the node represents the default namespace; otherwise it returns an xs:QName in which prefix and namespace URI are absentDM and the local part is the namespace prefix being bound.

For all other kinds of node, the function returns the empty sequence.

Examples
Variables
let $e := <doc>
  <p id="alpha" xml:id="beta">One</p>
  <p id="gamma" xmlns="http://example.com/ns">Two</p>
  <ex:p id="delta" xmlns:ex="http://example.com/ns">Three</ex:p>
  <?pi 3.14159?>
</doc>
ExpressionResult
node-name($e//*[@id = 'alpha'])
QName("", "p")
node-name($e//*[@id = 'gamma'])
QName("http://example.com/ns", "p")
node-name($e//*[@id = 'delta'])
QName("http://example.com/ns", "ex:p")
node-name($e//processing-instruction())
QName("", "pi")
node-name($e//*[@id = 'alpha']/text())
()
node-name($e//*[@id = 'alpha']/@id)
QName("", "id")
node-name($e//*[@id = 'alpha']/@xml:id)
xs:QName("xml:id")

2.1.2 fn:nilled

Summary

Returns true for an element that is nilled.

Signature
fn:nilled(
$nodeas node()?:= .
) 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 (.).

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

Otherwise the function returns the result of the dm:nilled accessor as defined in [XQuery and XPath Data Model (XDM) 3.1] (see Section 4.8 nilled AccessorDM).

Error Conditions

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

Notes

If $node is not an element node, the function returns the empty sequence.

If $node is an untyped element node, the function returns false.

In practice, the function returns true only for an element node that has the attribute xsi:nil="true" and that is successfully validated against a schema that defines the element to be nillable; the detailed rules, however, are defined in [XQuery and XPath Data Model (XDM) 3.1].

If $node is not an element node, the function returns the empty sequence.

If $node is an untyped element node, the function returns false.

In practice, the function returns true only for an element node that has the attribute xsi:nil="true" and that is successfully validated against a schema that defines the element to be nillable; the detailed rules, however, are defined in [XQuery and XPath Data Model (XDM) 3.1].

2.1.3 fn:string

Summary

Returns the value of $value represented as an xs:string.

Signature
fn:string(
$valueas item()?:= .
) 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·.

Rules

In the zero-argument version of the function, $value defaults to the context value. That is, calling fn:string() is equivalent to calling fn:string(.).

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

If $value is a node, the function returns the string value of the node, as obtained using the dm:string-value accessor defined in [XQuery and XPath Data Model (XDM) 3.1] (see Section 4.12 string-value AccessorDM).

If $value is an atomic item, the function returns the result of the expression $value cast as xs:string (see 21 Casting).

In all other cases, a dynamic error occurs (see below).

Error Conditions

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

A type error is raised [err:FOTY0014] if $value is a function item (this includes maps and arrays).

Notes

Every node has a string value, even an element with element-only content (which has no typed value). Moreover, casting an atomic item to a string always succeeds. Functions, maps, and arrays have no string value, so these are the only arguments that satisfy the type signature but cause failure.

Every node has a string value, even an element with element-only content (which has no typed value). Moreover, casting an atomic item to a string always succeeds. Functions, maps, and arrays have no string value, so these are the only arguments that satisfy the type signature but cause failure.

Examples
Variables
let $para := <para>There lived a <term author="Tolkien">hobbit</term>.</para>
ExpressionResult
string(23)
"23"
string(false())
"false"
string("Paris")
"Paris"
string((1, 2, 3))

Raises error XPTY0004.

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

Raises error FOTY0014.

string(abs#1)

Raises error FOTY0014.

string($para)
"There lived a hobbit."

2.1.4 fn:data

Summary

Returns the result of atomizing a sequence. This process flattens arrays, and replaces nodes by their typed values.

Signature
fn:data(
$inputas item()*:= .
) as xs:anyAtomicType*
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 (.).

The result of fn:data is the sequence of atomic items produced by applying the following rules to each item in $input:

  • If the item is an atomic item, it is appended to the result sequence.

  • If the item is a node, the typed value of the node is appended to the result sequence. The typed value is a sequence of zero or more atomic items: specifically, the result of the dm:typed-value accessor as defined in [XQuery and XPath Data Model (XDM) 3.1] (See Section 4.14 typed-value AccessorDM).

  • If the item is an array, the result of applying fn:data to each member of the array, in order, is appended to the result sequence.

Error Conditions

A type error is raised [err:FOTY0012] if an item in the sequence $input is a node that does not have a typed value.

A type error is raised [err:FOTY0013] if an item in the sequence $input is a function item other than an array.

A type error is raised [err:XPDY0002]XP if $input is omitted and the context value is absentDM.

Notes

The process of applying the fn:data function to a sequence is referred to as atomization. In many cases an explicit call on fn:data is not required, because atomization is invoked implicitly when a node or sequence of nodes is supplied in a context where an atomic item or sequence of atomic items is required.

The result of atomizing an empty sequence is an empty sequence.

The result of atomizing an empty array is an empty sequence.

The process of applying the fn:data function to a sequence is referred to as atomization. In many cases an explicit call on fn:data is not required, because atomization is invoked implicitly when a node or sequence of nodes is supplied in a context where an atomic item or sequence of atomic items is required.

The result of atomizing an empty sequence is an empty sequence.

The result of atomizing an empty array is an empty sequence.

Examples
Variables
let $para := <para>There lived a <term author="Tolkien">hobbit</term>.</para>
ExpressionResult
data(123)
123
data((123, 456))
123, 456
data([ [ 1, 2 ], [ 3, 4 ] ])
1, 2, 3, 4
data($para)
xs:untypedAtomic("There lived a hobbit.")
data($para/term/@author)
xs:untypedAtomic("Tolkien")
data(abs#1)

Raises error FOTY0013.

2.1.6 fn:document-uri

Changes in 4.0  

  1. The constraints on the result of the function have been relaxed.  [Issues 898 1161 PR 1265 2 July 2024]

Summary

Returns the URI of a resource where a document can be found, if available.

Signature
fn:document-uri(
$nodeas node()?:= .
) as xs:anyURI?
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 (.).

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

If $node is not a document node, the function returns the empty sequence.

Otherwise, the function returns the value of the document-uri accessor applied to $node, as defined in [XQuery and XPath Data Model (XDM) 3.1] (See Section 5.1.2 AccessorsDM).

Error Conditions

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

Notes

In the 3.1 version of this specification, it was mandated that two distinct documents could not have the same document-uri property: more specifically, it was guaranteed that for any document node $D, either document-uri($D) would be absent, or doc(document-uri($D)) would return $D.

For various reasons, this constraint has proved impractical. Different parts of an application may read the same external resource in different ways, for example with or without validation or whitespace stripping, leading to different document nodes derived from the same external resource having the same document-uri property. In addition, the specification explicitly allows implementations, at user request, to relax the requirements for determinism of resource access functions, which makes it possible for multiple calls of functions such as fn:doc, fn:json-doc, or fn:collection to return different results for the same supplied URI.

Although the uniqueness of the document-uri property is no longer an absolute constraint, it is still desirable that implementations should where possible respect the principle that URIs are usable as identifiers for resources.

In the case of a document node $D returned by the fn:doc function, it will generally be the case that fn:document-uri($D) returns a URI $U such that a call on fn:doc($U) in the same dynamic context will return the same document node $D. The URI $U will not necessarily be the same URI that was originally passed to the fn:doc function, since several URIs may identify the same resource.

It is recommended that implementations of fn:collection should ensure that any documents included in the returned collection, if they have a non-empty fn:document-uri property, should be such that a call on fn:doc supplying this URI returns the same document node.

In the 3.1 version of this specification, it was mandated that two distinct documents could not have the same document-uri property: more specifically, it was guaranteed that for any document node $D, either document-uri($D) would be absent, or doc(document-uri($D)) would return $D.

For various reasons, this constraint has proved impractical. Different parts of an application may read the same external resource in different ways, for example with or without validation or whitespace stripping, leading to different document nodes derived from the same external resource having the same document-uri property. In addition, the specification explicitly allows implementations, at user request, to relax the requirements for determinism of resource access functions, which makes it possible for multiple calls of functions such as fn:doc, fn:json-doc, or fn:collection to return different results for the same supplied URI.

Although the uniqueness of the document-uri property is no longer an absolute constraint, it is still desirable that implementations should where possible respect the principle that URIs are usable as identifiers for resources.

In the case of a document node $D returned by the fn:doc function, it will generally be the case that fn:document-uri($D) returns a URI $U such that a call on fn:doc($U) in the same dynamic context will return the same document node $D. The URI $U will not necessarily be the same URI that was originally passed to the fn:doc function, since several URIs may identify the same resource.

It is recommended that implementations of fn:collection should ensure that any documents included in the returned collection, if they have a non-empty fn:document-uri property, should be such that a call on fn:doc supplying this URI returns the same document node.

2.2 Other functions on nodes

This section specifies further functions on nodes. Nodes are formally defined in Section 6 Nodes DM31.

FunctionMeaning
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: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:namespace-uriReturns the namespace URI part of the name of $node, as an xs:anyURI value.
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:rootReturns the root of the tree to which $node belongs. This will usually, but not necessarily, be a document node.
fn:pathReturns a path expression that can be used to select the supplied node relative to the root of its containing document.
fn:has-childrenReturns true if the supplied node has one or more child nodes (of any kind).
fn:siblingsReturns the supplied node together with its siblings, in document order.

2.2.1 fn:name

Summary

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

Signature
fn:name(
$nodeas node()?:= .
) 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·.

Rules

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

If the argument is supplied and is the empty sequence, the function returns the zero-length string.

If the node identified by $node has no name (that is, if it is a document node, a comment, a text node, or a namespace node having no name), the function returns the zero-length string.

Otherwise, the function returns the value of the expression fn:string(fn:node-name($node)).

Error Conditions

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

Notes

Because the result depends on the choice of namespace prefixes in the source document, it is not good practice to use the result of this function for anything other than display purposes. For example, the test name(.) = 'my:profile' will fail if the source document uses an unexpected namespace prefix. Such a test (assuming it relates to an element node) is better written as boolean(self::my:profile).

Because the result depends on the choice of namespace prefixes in the source document, it is not good practice to use the result of this function for anything other than display purposes. For example, the test name(.) = 'my:profile' will fail if the source document uses an unexpected namespace prefix. Such a test (assuming it relates to an element node) is better written as boolean(self::my:profile).

Examples
Variables
let $e := <doc>
  <p id="alpha" xml:id="beta">One</p>
  <p id="gamma" xmlns="http://example.com/ns">Two</p>
  <ex:p id="delta" xmlns:ex="http://example.com/ns">Three</ex:p>
  <?pi 3.14159?>
</doc>
ExpressionResult
name($e//*[@id = 'alpha'])
"p"
name($e//*[@id = 'gamma'])
"p"
name($e//*[@id = 'delta'])
"ex:p"
name($e//processing-instruction())
"pi"
name($e//*[@id = 'alpha']/text())
""
name($e//*[@id = 'alpha']/@id)
"id"
name($e//*[@id = 'alpha']/@xml:id)
"xml:id"

2.2.6 fn:path

Changes in 4.0  

  1. Options are added to customize the form of the output.  [Issue 332  29 November 2024]

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 node()?:= .,
$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(
namespaces?as map((xs:NCName | enum('')), xs:anyURI)?,
indexes?as xs:boolean
)
KeyMeaning

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

If $node is a document node, 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 other than the root node.

If the root node is not a document node then this string is preceded by a string notionally representing a call to the fn:root function, expressed as follows:

  • 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 consists of the character "/" followed by a string whose form depends on the kind of node selected by that step, as follows:

  1. For an element node, then by default Q{uri}local[position], where uri is the namespace URI of the node name or the empty string if the node is in no namespace, local is the local part of the node name, and position is an integer representing the one-based position of the selected node among its like-named siblings.

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

    If the namespaces option is present, and if it includes a mapping from a namespace prefix to the namespace URI of the element, or to the empty string if the element is in no namespace, then:

    • If there is more than one such prefix, then one of them is chosen arbitrarily.

    • If the namespace prefix is the zero-length string, then the Q{uri} part of the step is replaced by the empty string.

    • If the prefix is an NCName P, then the Q{uri} part of the step is replaced by P:.

  2. For an attribute node:

    1. If the node is in no namespace, @local, where local is the local part of the node name.

    2. Otherwise, by default @Q{uri}local, where uri is the namespace URI of the node name, and local is the local part of the node name.

      If the namespaces option is present , and if it includes a mapping from a non-empty namespace prefix to the namespace URI of the attribute, then the Q{uri} part of the step is replaced with a namespace prefix in the same way as for element nodes, described above.

  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.

Error Conditions

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

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.

A map returned by fn:in-scope-namespaces will never contain an entry that maps any prefix to the zero-length URI. Such an entry can, however, be added manually, and can be used to control how no-namespace names are represented in the output (including the option of giving them a non-empty prefix).

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.

A map returned by fn:in-scope-namespaces will never contain an entry that maps any prefix to the zero-length URI. Such an entry can, however, be added manually, and can be used to control how no-namespace names are represented in the output (including the option of giving them a non-empty prefix).

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($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, 
     { 'namespaces': { 'fn': 'http://www.w3.org/2005/xpath-functions', 
                       '': '' }
     })
Result:
'fn:root()/empnr[1]'

2.2.7 fn:has-children

Summary

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

Signature
fn:has-children(
$nodeas node()?:= .
) 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 node()?, 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::node()).

Error Conditions

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

Notes

If $node is an 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>

If $node is an 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.

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.

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()

2.2.8 fn:siblings

Changes in 4.0  

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

Summary

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

Signature
fn:siblings(
$nodeas node()?:= .
) as node()*
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 an empty sequence, the function returns an empty sequence.

If $node is a child of some parent node P, the function returns all the children of P (including $node), in document order.

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::node()/child::node())
then $node/parent::node()/child::node()
else $node
Error Conditions

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

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.

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"

2.3 Functions on sequences of nodes

This section specifies functions on sequences of nodes.

FunctionMeaning
fn:distinct-ordered-nodesRemoves duplicate nodes and sorts the input into document order.
fn:innermostReturns every node within the input sequence that is not an ancestor of another member of the input sequence; the nodes are returned in document order with duplicates eliminated.
fn:outermostReturns every node 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.

2.3.1 fn:distinct-ordered-nodes

Changes in 4.0  

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

Summary

Removes duplicate nodes and sorts the input into document order.

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

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

Rules

Any duplicate nodes in the input (based on node identity) are discarded. The remaining nodes are returned in document orderXP.

Notes

Document order is ·implementation-dependent· (but stable) for nodes in different documents. If some node in document A precedes some node in document B, then every node in A precedes every node in B.

Document order is ·implementation-dependent· (but stable) for nodes in different documents. If some node in document A precedes some node in document B, then every node in A precedes every node 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.)

2.3.3 fn:outermost

Summary

Returns every node 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 node()*
) as node()*
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::node() intersect $nodes)]/.

That is, the function takes as input a sequence of nodes, and returns every node within the sequence that does not have another node within the sequence as an ancestor; the nodes 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.

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.

Examples

If the source document contains nested sections represented by div elements, the expression outermost(//div) returns those div elements that are not contained within further div elements.

3 Errors and diagnostics

3.1 Raising errors

In this document, as well as in [XQuery 4.0: An XML Query Language] and [XML Path Language (XPath) 4.0], the phrase “an error is raised” is used. Raising an error is equivalent to calling the fn:error function defined in this section with the provided error code. Except where otherwise specified, errors defined in this specification are dynamic errors. Some errors, however, are classified as type errors. Type errors are typically used where the presence of the error can be inferred from knowledge of the type of the actual arguments to a function, for example with a call such as fn:string(fn:abs#1). Host languages may allow type errors to be reported statically if they are discovered during static analysis.

When function specifications indicate that an error is to be raised, the notation “[error code ]” is used to specify an error code. Each error defined in this document is identified by an xs:QName that is in the http://www.w3.org/2005/xqt-errors namespace, represented in this document by the err prefix. It is this xs:QName that is actually passed as an argument to the fn:error function. Calling this function raises an error. For a more detailed treatment of error handing, see Section 2.3.3 Handling Dynamic Errors XP31.

The fn:error function is a general function that may be called as above but may also be called from [XQuery 4.0: An XML Query Language] or [XML Path Language (XPath) 4.0] applications with, for example, an xs:QName argument.

3.1.1 fn:error

Changes in 4.0  

  1. All three arguments are now optional, and each argument can be set to an empty sequence. Previously if $description was supplied, it could not be empty.  [Issue 895 PR 901 16 December 2023]

Summary

Calling the fn:error function raises an application-defined error.

Signature
fn:error(
$codeas xs:QName?:= (),
$descriptionas xs:string?:= (),
$valueas item()*:= .
) as item()*
Properties

This function is ·nondeterministic·, ·context-independent·, and ·focus-independent·.

Rules

This function never returns a value. Instead it always raises an error. The effect of the error is identical to the effect of dynamic errors raised implicitly, for example when an incorrect argument is supplied to a function.

The parameters to the fn:error function supply information that is associated with the error condition and that is made available to a caller that asks for information about the error. The error may be caught either by the host language (using a try/catch construct in XSLT or XQuery, for example), or by the calling application or external processing environment. The way in which error information is returned to the external processing environment is ·implementation-dependent·.

There are three pieces of information that may be associated with an error.

  • The $code is an error code that distinguishes this error from others. It is an xs:QName; the namespace URI conventionally identifies the component, subsystem, or authority responsible for defining the meaning of the error code, while the local part identifies the specific error condition. The namespace URI http://www.w3.org/2005/xqt-errors is used for errors defined in this specification; other namespace URIs may be used for errors defined by the application.

    If the external processing environment expects the error code to be returned as a URI or a string rather than as an xs:QName, then an error code with namespace URI NS and local part LP will be returned in the form NS#LP. The namespace URI part of the error code should therefore not include a fragment identifier.

    If no value is supplied for the $code argument, or if the value supplied is an empty sequence, the effective value of the error code is fn:QName('http://www.w3.org/2005/xqt-errors', 'err:FOER0000').

  • The $description is a natural-language description of the error condition.

    If no value is supplied for the $description argument, or if the value supplied is an empty sequence, then the effective value of the description is ·implementation-dependent·.

  • The $value is an arbitrary value used to convey additional information about the error, and may be used in any way the application chooses.

    If no value is supplied for the $value argument or if the value supplied is an empty sequence, then the effective value of the error object is ·implementation-dependent·.

Error Conditions

This function always raises a dynamic error. By default, it raises [err:FOER0000]

Notes

The value of the $description parameter may need to be localized.

Since the function never returns a value, the declared return type of item()* is a convenient fiction. It is relevant insofar as a function item such as error#1 may (as a consequence of function coercion) be supplied in contexts where a function with a more specific return type is required.

Any QName may be used as an error code; there are no reserved names or namespaces. The error is always classified as a dynamic error, even if the error code used is one that is normally used for static errors or type errors.

The value of the $description parameter may need to be localized.

Since the function never returns a value, the declared return type of item()* is a convenient fiction. It is relevant insofar as a function item such as error#1 may (as a consequence of function coercion) be supplied in contexts where a function with a more specific return type is required.

Any QName may be used as an error code; there are no reserved names or namespaces. The error is always classified as a dynamic error, even if the error code used is one that is normally used for static errors or type errors.

Examples
Expression:

error()

Result:

Raises error FOER0000.

(This returns the URI http://www.w3.org/2005/xqt-errors#FOER0000 (or the corresponding xs:QName) to the external processing environment, unless the error is caught using a try/catch construct in the host language.)

Expression:
error(
  QName('http://www.example.com/HR', 'myerr:toohighsal'),
  'Salary is too high'
)
Result:

Raises error myerr:toohighsal.

(This returns http://www.example.com/HR#toohighsal and the xs:string"Salary is too high" (or the corresponding xs:QName) to the external processing environment, unless the error is caught using a try/catch construct in the host language.)

3.2 Diagnostic tracing

3.2.1 fn:trace

Changes in 4.0  

  1. The $label argument can now be set to an 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 Section 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.

If the trace information is unrelated to a specific value, fn:message can be used instead.

Examples

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.

The following two XPath expressions are identical, but only the second provides trace feedback to the user:

  • //book[xs:decimal(@price) gt 100]

  • //book[xs:decimal(@price) gt 100] => trace('books more expensive than €100:')

3.2.2 fn:message

Changes in 4.0  

  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 an 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 Section 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.

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

The following two XPath expressions are identical, but only the second logs any feedback:

  • //book[xs:decimal(@price) lt 1000]

  • //book[if (xs:decimal(@price) lt 1000) then true() else message(@price, @title || ' is unexpectedly expensive: ')]

4 Functions and operators on numerics

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

4.2 Arithmetic operators on numeric values

The following functions define the semantics of arithmetic operators defined in [XQuery 4.0: An XML Query Language] and [XML Path Language (XPath) 4.0] on these numeric types.

OperatorMeaning
op:numeric-addAddition
op:numeric-subtractSubtraction
op:numeric-multiplyMultiplication
op:numeric-divideDivision
op:numeric-integer-divideInteger division
op:numeric-modModulus
op:numeric-unary-plusUnary plus
op:numeric-unary-minusUnary minus (negation)

The parameters and return types for the above operators are in most cases declared to be of type xs:numeric, which permits the basic numeric types: xs:integer, xs:decimal, xs:float and xs:double, and types derived from them. In general the two-argument functions require that both arguments are of the same primitive type, and they return a value of this same type. The exceptions are op:numeric-divide, which returns an xs:decimal if called with two xs:integer operands, and op:numeric-integer-divide which always returns an xs:integer.

If the two operands of an arithmetic expression are not of the same type, subtype substitution and numeric type promotion are used to obtain two operands of the same type. Section B.1 Type Promotion XP31 and Section B.2 Operator Mapping XP31 describe the semantics of these operations in detail.

The result type of operations depends on their argument datatypes and is defined in the following table:

OperatorReturns
op:operation(xs:integer, xs:integer)xs:integer (except for op:numeric-divide(integer, integer), which returns xs:decimal)
op:operation(xs:decimal, xs:decimal)xs:decimal
op:operation(xs:float, xs:float)xs:float
op:operation(xs:double, xs:double)xs:double
op:operation(xs:integer)xs:integer
op:operation(xs:decimal)xs:decimal
op:operation(xs:float)xs:float
op:operation(xs:double)xs:double

These rules define any operation on any pair of arithmetic types. Consider the following example:

op:operation(xs:int, xs:double) => op:operation(xs:double, xs:double)

For this operation, xs:int must be converted to xs:double. This can be done, since by the rules above: xs:int can be substituted for xs:integer, xs:integer can be substituted for xs:decimal, xs:decimal can be promoted to xs:double. As far as possible, the promotions should be done in a single step. Specifically, when an xs:decimal is promoted to an xs:double, it should not be converted to an xs:float and then to xs:double, as this risks loss of precision.

As another example, a user may define height as a derived type of xs:integer with a minimum value of 20 and a maximum value of 100. They may then derive fenceHeight using an enumeration to restrict the permitted set of values to, say, 36, 48 and 60.

op:operation(fenceHeight, xs:integer) => op:operation(xs:integer, xs:integer)

fenceHeight can be substituted for its base type height and height can be substituted for its base type xs:integer.

The basic rules for addition, subtraction, and multiplication of ordinary numbers are not set out in this specification; they are taken as given. In the case of xs:double and xs:float the rules are as defined in [IEEE 754-2019]. The rules for handling division and modulus operations, as well as the rules for handling special values such as infinity and NaN, and exception conditions such as overflow and underflow, are described more explicitly since they are not necessarily obvious.

On overflow and underflow situations during arithmetic operations, conforming implementations must behave as follows:

  • For xs:float and xs:double operations, overflow behavior must be conformant with [IEEE 754-2019]. This specification allows the following options:

    • Raising a dynamic error [err:FOAR0002] via an overflow trap.

    • Returning INF or -INF.

    • Returning the largest (positive or negative) non-infinite number.

  • For xs:float and xs:double operations, underflow behavior must be conformant with [IEEE 754-2019]. This specification allows the following options:

    • Raising a dynamic error [err:FOAR0002] via an underflow trap.

    • Returning 0.0E0 or +/- 2**Emin or a denormalized value; where Emin is the smallest possible xs:float or xs:double exponent.

  • For xs:decimal operations, overflow behavior must raise a dynamic error [err:FOAR0002]. On underflow, 0.0 must be returned.

  • For xs:integer operations, implementations that support limited-precision integer operations must select from the following options:

    • They may choose to always raise a dynamic error [err:FOAR0002].

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

The functions op:numeric-add, op:numeric-subtract, op:numeric-multiply, op:numeric-divide, op:numeric-integer-divide and op:numeric-mod are each defined for pairs of numeric operands, each of which has the same type:xs:integer, xs:decimal, xs:float, or xs:double. The functions op:numeric-unary-plus and op:numeric-unary-minus are defined for a single operand whose type is one of those same numeric types.

For xs:float and xs:double arguments, if either argument is NaN, the result is NaN.

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.

Note:

This specification does not determine whether xs:decimal operations are fixed point or floating point. In an implementation using floating point it is possible for very simple operations to require more digits of precision than are available; for example, adding 1e100 to 1e-100 requires 200 digits of precision for an accurate representation of the result.

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.

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.

4.2.1 op:numeric-add

Summary

Returns the arithmetic sum of its operands: ($arg1 + $arg2).

Operator Mapping

Defines the semantics of the + operator when applied to two numeric values

Signature
op:numeric-add(
$arg1as xs:numeric,
$arg2as xs:numeric
) as xs:numeric
Rules

General rules: see 4.2 Arithmetic operators on numeric values.

Notes

For xs:float or xs:double values, if one of the operands is a zero or a finite number and the other is INF or -INF, INF or -INF is returned. If both operands are INF, INF is returned. If both operands are -INF, -INF is returned. If one of the operands is INF and the other is -INF, NaN is returned.

For xs:float or xs:double values, if one of the operands is a zero or a finite number and the other is INF or -INF, INF or -INF is returned. If both operands are INF, INF is returned. If both operands are -INF, -INF is returned. If one of the operands is INF and the other is -INF, NaN is returned.

4.2.2 op:numeric-subtract

Summary

Returns the arithmetic difference of its operands: ($arg1 - $arg2).

Operator Mapping

Defines the semantics of the - operator when applied to two numeric values.

Signature
op:numeric-subtract(
$arg1as xs:numeric,
$arg2as xs:numeric
) as xs:numeric
Rules

General rules: see 4.2 Arithmetic operators on numeric values.

Notes

For xs:float or xs:double values, if one of the operands is a zero or a finite number and the other is INF or -INF, an infinity of the appropriate sign is returned. If both operands are INF or -INF, NaN is returned. If one of the operands is INF and the other is -INF, an infinity of the appropriate sign is returned.

For xs:float or xs:double values, if one of the operands is a zero or a finite number and the other is INF or -INF, an infinity of the appropriate sign is returned. If both operands are INF or -INF, NaN is returned. If one of the operands is INF and the other is -INF, an infinity of the appropriate sign is returned.

4.2.3 op:numeric-multiply

Summary

Returns the arithmetic product of its operands: ($arg1 * $arg2).

Operator Mapping

Defines the semantics of the * operator when applied to two numeric values.

Signature
op:numeric-multiply(
$arg1as xs:numeric,
$arg2as xs:numeric
) as xs:numeric
Rules

General rules: see 4.2 Arithmetic operators on numeric values.

Notes

For xs:float or xs:double values, if one of the operands is a zero and the other is an infinity, NaN is returned. If one of the operands is a non-zero number and the other is an infinity, an infinity with the appropriate sign is returned.

For xs:float or xs:double values, if one of the operands is a zero and the other is an infinity, NaN is returned. If one of the operands is a non-zero number and the other is an infinity, an infinity with the appropriate sign is returned.

4.2.4 op:numeric-divide

Summary

Returns the arithmetic quotient of its operands: ($arg1 div $arg2).

Operator Mapping

Defines the semantics of the div operator when applied to two numeric values.

Signature
op:numeric-divide(
$arg1as xs:numeric,
$arg2as xs:numeric
) as xs:numeric
Rules

General rules: see 4.2 Arithmetic operators on numeric values.

As a special case, if the types of both $arg1 and $arg2 are xs:integer, then the return type is xs:decimal.

Error Conditions

A dynamic error is raised [err:FOAR0001] for xs:decimal and xs:integer operands, if the divisor is (positive or negative) zero.

Notes

For xs:float and xs:double operands, floating point division is performed as specified in [IEEE 754-2019]. A positive number divided by positive zero returns INF. A negative number divided by positive zero returns -INF. Division by negative zero returns -INF and INF, respectively. Positive or negative zero divided by positive or negative zero returns NaN. Also, INF or -INF divided by INF or -INF returns NaN.

For xs:float and xs:double operands, floating point division is performed as specified in [IEEE 754-2019]. A positive number divided by positive zero returns INF. A negative number divided by positive zero returns -INF. Division by negative zero returns -INF and INF, respectively. Positive or negative zero divided by positive or negative zero returns NaN. Also, INF or -INF divided by INF or -INF returns NaN.

4.2.5 op:numeric-integer-divide

Summary

Performs an integer division.

Operator Mapping

Defines the semantics of the idiv operator when applied to two numeric values.

Signature
op:numeric-integer-divide(
$arg1as xs:numeric,
$arg2as xs:numeric
) as xs:integer
Rules

General rules: see 4.2 Arithmetic operators on numeric values.

If $arg2 is INF or -INF, and $arg1 is not INF or -INF, then the result is zero.

Otherwise, subject to limits of precision and overflow/underflow conditions, the result is the largest (furthest from zero) xs:integer value $N such that the following expression is true:

abs($N * $arg2) le abs($arg1) and
compare($N * $arg2, 0) eq compare($arg1, 0).

Note:

The second term in this condition ensures that the result has the correct sign.

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.

Error Conditions

A dynamic error is raised [err:FOAR0001] if the divisor is (positive or negative) zero.

A dynamic error is raised [err:FOAR0002] if either operand is NaN or if $arg1 is INF or -INF.

Notes

Except in situations involving errors, loss of precision, or overflow/underflow, the result of $a idiv $b is the same as ($a div $b) cast as xs:integer.

The semantics of this function are different from integer division as defined in programming languages such as Java and C++.

Except in situations involving errors, loss of precision, or overflow/underflow, the result of $a idiv $b is the same as ($a div $b) cast as xs:integer.

The semantics of this function are different from integer division as defined in programming languages such as Java and C++.

Examples
ExpressionResult
op:numeric-integer-divide(10, 3)
3
op:numeric-integer-divide(3, -2)
-1
op:numeric-integer-divide(-3, 2)
-1
op:numeric-integer-divide(-3, -2)
1
op:numeric-integer-divide(9.0, 3)
3
op:numeric-integer-divide(-3.5, 3)
-1
op:numeric-integer-divide(3.0, 4)
0
op:numeric-integer-divide(3.1E1, 6)
5
op:numeric-integer-divide(3.1E1, 7)
4

4.2.7 op:numeric-unary-plus

Summary

Returns its operand with the sign unchanged: (+ $arg).

Operator Mapping

Defines the semantics of the unary + operator applied to a numeric value.

Signature
op:numeric-unary-plus(
$argas xs:numeric
) as xs:numeric
Rules

General rules: see 4.2 Arithmetic operators on numeric values.

The returned value is equal to $arg, and is an instance of xs:integer, xs:decimal, xs:double, or xs:float depending on the type of $arg.

Notes

Because coercion rules are applied in the normal way, the unary + operator can be used to force conversion of an untyped node to a number: the result of +@price is the same as xs:double(@price) if the type of @price is xs:untypedAtomic.

Because coercion rules are applied in the normal way, the unary + operator can be used to force conversion of an untyped node to a number: the result of +@price is the same as xs:double(@price) if the type of @price is xs:untypedAtomic.

4.3 Comparison operators on numeric values

Changes in 4.0  

  1. Deleted an inaccurate statement concerning the behavior of NaN.  [Issue 473 PR 482]

The six value comparison operators eq, ne, lt, le, gt, and ge are defined in terms of two underlying functions: op:numeric-equal and op:numeric-less-than. These functions are defined to operate on values of the same type.

If the arguments are of different types, one argument is promoted to the type of the other as described above in 4.2 Arithmetic operators on numeric values. Each comparison operator returns a boolean value.

Note:

For a description of the different ways of comparing numeric values using the operators = and eq and the functions fn:deep-equal and fn:atomic-equal, see Section H Atomic Comparisons: An Overview (Non-Normative)XP.

Note:

See also the function fn:compare.

FunctionMeaning
op:numeric-equalReturns true if and only if the value of $arg1 is equal to the value of $arg2.
op:numeric-less-thanReturns true if and only if $arg1 is numerically less than $arg2.

4.3.1 op:numeric-equal

Summary

Returns true if and only if the value of $arg1 is equal to the value of $arg2.

Operator Mapping

Defines the semantics of the eq operator when applied to two numeric values, and is also used in defining the semantics of ne, le and ge.

Signature
op:numeric-equal(
$arg1as xs:numeric,
$arg2as xs:numeric
) as xs:boolean
Rules

General rules: see 4.2 Arithmetic operators on numeric values and 4.3 Comparison operators on numeric values.

Notes

For xs:float and xs:double values, positive zero and negative zero compare equal. INF equals INF and -INF equals -INF. If $arg1 or $arg2 is NaN, the function returns false.

For xs:float and xs:double values, positive zero and negative zero compare equal. INF equals INF and -INF equals -INF. If $arg1 or $arg2 is NaN, the function returns false.

4.3.2 op:numeric-less-than

Summary

Returns true if and only if $arg1 is numerically less than $arg2.

Operator Mapping

Defines the semantics of the lt operator when applied to two numeric values, and is also used in defining the semantics of le, gt, and ge.

Signature
op:numeric-less-than(
$arg1as xs:numeric,
$arg2as xs:numeric
) as xs:boolean
Rules

General rules: see 4.2 Arithmetic operators on numeric values and 4.3 Comparison operators on numeric values.

Notes

For xs:float and xs:double values, positive infinity is greater than all other non-NaN values; negative infinity is less than all other non-NaN values. Positive and negative zero compare equal. If $arg1 or $arg2 is NaN, the function returns false.

For xs:float and xs:double values, positive infinity is greater than all other non-NaN values; negative infinity is less than all other non-NaN values. Positive and negative zero compare equal. If $arg1 or $arg2 is NaN, the function returns false.

4.4 Functions on numeric values

The following functions are defined on numeric types. Each function returns a value of the same type as the type of its argument.

  • If the argument is the empty sequence, the empty sequence is returned.

  • For xs:float and xs:double arguments, if the argument is NaN, NaN is returned.

  • With the exception of fn:abs, functions with arguments of type xs:float and xs:double that are positive or negative infinity return positive or negative infinity.

FunctionMeaning
fn:absReturns the absolute value of $value.
fn:ceilingRounds $value upwards to a whole number.
fn:floorRounds $value downwards to a whole number.
fn:roundRounds a value to a specified number of decimal places, with control over how the rounding takes place.
fn:round-half-to-evenRounds a value to a specified number of decimal places, rounding to make the last digit even if two such values are equally near.
fn:divide-decimalsDivides one xs:decimal by another to a defined precision, returning both the quotient and the remainder.
fn:is-NaNReturns true if the argument is the xs:float or xs:double value NaN.

Note:

The fn:round function has been extended with a third argument in version 4.0 of this specification; this means that the fn:ceiling, fn:floor, and fn:round-half-to-even functions are now technically redundant. They are retained, however, both for backwards compatibility and for convenience.

4.4.4 fn:round

Changes in 4.0  

  1. A third argument has been added, providing control over the rounding mode.  [Issues 1187 1274 PRs 1260 1275 11 June 2024]

  2. It is explicitly stated that the limits for $precision are implementation-defined.  [Issue 1705  1 January 2025]

Summary

Rounds a value to a specified number of decimal places, with control over how the rounding takes place.

Signature
fn:round(
$valueas xs:numeric?,
$precisionas xs:integer?:= 0,
$modeas enum('floor', 'ceiling', 'toward-zero', 'away-from-zero', 'half-to-floor', 'half-to-ceiling', 'half-toward-zero', 'half-away-from-zero', 'half-to-even')?:= 'half-to-ceiling'
) as xs:numeric?
Properties

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

Rules

General rules: see 4.4 Functions on numeric values.

The function returns a value that is close to $value and that is a multiple of ten to the power of minus $precision. The default value of $precision is zero, in which case the function returns a whole number (but not necessarily an xs:integer).

The detailed way in which rounding is performed depends on the value of $mode, as follows. Here L means the highest multiple of ten to the power of minus $precision that is less than or equal to $value, U means the lowest multiple of ten to the power of minus $precision that is greater than or equal to $value, N means the multiple of ten to the power of minus $precision that is numerically closest to $value, and midway means that $value is equal to the arithmetic mean of L and U.

Rounding Modes
Rounding ModeMeaning

'floor'

Returns L.

'ceiling'

Returns U.

'toward-zero'

Returns L if $value is positive, otherwise U.

'away-from-zero'

Returns U if $value is positive, otherwise L

'half-to-floor'

Returns N, unless midway, in which case L.

'half-to-ceiling'

Returns N, unless midway, in which case U. This is the default.

'half-toward-zero'

Returns N, unless midway, in which case it returns L if $value is positive, otherwise U.

'half-away-from-zero'

Returns N, unless midway, in which case it returns U if $value is positive, otherwise L.

'half-to-even'

Returns N, unless midway, in which case it returns whichever of L and U has a last significant digit that is even.

For the four types xs:float, xs:double, xs:decimal and xs:integer, it is guaranteed that if the type of $value is an instance of type T then the result will also be an instance of T. The result may also be an instance of a type derived from one of these four by restriction. For example, if $value is an instance of xs:decimal and $precision is less than one, then the result may be an instance of xs:integer.

If the second argument is omitted or is an empty sequence, the function produces the same result as when $precision = 0 (that is, it rounds to a whole number).

When $value is of type xs:float and xs:double:

  1. If $value is NaN, positive or negative zero, or positive or negative infinity, then the result is the same as the argument.

  2. For other values, the argument is cast to xs:decimal using an implementation of xs:decimal that imposes no limits on the number of digits that can be represented. The function is applied to this xs:decimal value, and the resulting xs:decimal is cast back to xs:float or xs:double as appropriate to form the function result. If the resulting xs:decimal value is zero, then positive or negative zero is returned according to the sign of $value.

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.

Notes

This function is typically used with a non-zero $precision in financial applications where the argument is of type xs:decimal. For arguments of type xs:float and xs:double the results may be counter-intuitive. For example, consider round(35.425e0, 2). The result is not 35.43, as might be expected, but 35.42. This is because the xs:double written as 35.425e0 has an exact value equal to 35.42499999999..., which is closer to 35.42 than to 35.43.

The call round($v, 0, "floor") is equivalent to floor($v).

The call round($v, 0, "ceiling") is equivalent to ceiling($v).

The call round($v, $p, "half-to-even") is equivalent to round-half-to-even($v, $p).

This function is typically used with a non-zero $precision in financial applications where the argument is of type xs:decimal. For arguments of type xs:float and xs:double the results may be counter-intuitive. For example, consider round(35.425e0, 2). The result is not 35.43, as might be expected, but 35.42. This is because the xs:double written as 35.425e0 has an exact value equal to 35.42499999999..., which is closer to 35.42 than to 35.43.

The call round($v, 0, "floor") is equivalent to floor($v).

The call round($v, 0, "ceiling") is equivalent to ceiling($v).

The call round($v, $p, "half-to-even") is equivalent to round-half-to-even($v, $p).

Examples
ExpressionResult
round(2.5)
3.0
round(2.4999)
2.0
round(-2.5)
-2.0
round(1.125, 2)
1.13
round(8452, -2)
8500
round(3.1415e0, 2)
3.14e0
math:log(0) => round()
-xs:double('INF')
round(1.7, 0, "floor")
1
round(-1.7, 0, "floor")
-2
round(1.7, 0, "ceiling")
2
round(-1.7, 0, "ceiling")
-1
round(1.7, 0, "toward-zero")
1
round(-1.7, 0, "toward-zero")
-1
round(1.7, 0, "away-from-zero")
2
round(-1.7, 0, "away-from-zero")
-2
round(1.125, 2, "half-to-floor")
1.12
round(-1.125, 2, "half-to-floor")
-1.13
round(1.125, 2, "half-to-ceiling")
1.13
round(-1.125, 2, "half-to-ceiling")
-1.12
round(1.125, 2, "half-toward-zero")
1.12
round(-1.125, 2, "half-toward-zero")
-1.12
round(1.125, 2, "half-away-from-zero")
1.13
round(-1.125, 2, "half-away-from-zero")
-1.13
round(1.125, 2, "half-to-even")
1.12
round(-1.125, 2, "half-to-even")
-1.12

4.4.5 fn:round-half-to-even

Changes in 4.0  

  1. It is explicitly stated that the limits for $precision are implementation-defined.  [Issue 1705  1 January 2025]

Summary

Rounds a value to a specified number of decimal places, rounding to make the last digit even if two such values are equally near.

Signature
fn:round-half-to-even(
$valueas xs:numeric?,
$precisionas xs:integer?:= 0
) as xs:numeric?
Properties

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

Rules

General rules: see 4.4 Functions on numeric values.

The function returns the nearest (that is, numerically closest) value to $value that is a multiple of ten to the power of minus $precision. If two such values are equally near (e.g. if the fractional part in $value is exactly .500...), the function returns the one whose least significant digit is even.

For the four types xs:float, xs:double, xs:decimal and xs:integer, it is guaranteed that if the type of $value is an instance of type T then the result will also be an instance of T. The result may also be an instance of a type derived from one of these four by restriction. For example, if $value is an instance of xs:decimal and $precision is less than one, then the result may be an instance of xs:integer.

If the second argument is omitted or an empty sequence, the function produces the same result as the two-argument version with $precision = 0.

For arguments of type xs:float and xs:double:

  1. If the argument is NaN, positive or negative zero, or positive or negative infinity, then the result is the same as the argument.

  2. In all other cases, the argument is cast to xs:decimal using an implementation of xs:decimal that imposes no limits on the number of digits that can be represented. The function is applied to this xs:decimal value, and the resulting xs:decimal is cast back to xs:float or xs:double as appropriate to form the function result. If the resulting xs:decimal value is zero, then positive or negative zero is returned according to the sign of the original argument.

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.

Notes

This function is typically used in financial applications where the argument is of type xs:decimal. For arguments of type xs:float and xs:double the results may be counter-intuitive. For example, consider round-half-to-even(xs:float(150.015), 2). The result is not 150.02 as might be expected, but 150.01. This is because the conversion of the xs:float value represented by the literal 150.015 to an xs:decimal produces the xs:decimal value 150.014999389..., which is closer to 150.01 than to 150.02.

From 4.0, the effect of this function can also be achieved by calling fn:round with the third argument set to "half-to-even".

This function is typically used in financial applications where the argument is of type xs:decimal. For arguments of type xs:float and xs:double the results may be counter-intuitive. For example, consider round-half-to-even(xs:float(150.015), 2). The result is not 150.02 as might be expected, but 150.01. This is because the conversion of the xs:float value represented by the literal 150.015 to an xs:decimal produces the xs:decimal value 150.014999389..., which is closer to 150.01 than to 150.02.

From 4.0, the effect of this function can also be achieved by calling fn:round with the third argument set to "half-to-even".

Examples
ExpressionResult
round-half-to-even(0.5)
0.0
round-half-to-even(1.5)
2.0
round-half-to-even(2.5)
2.0
round-half-to-even(3.567812e+3, 2)
3567.81e0
round-half-to-even(4.7564e-3, 2)
0.0e0
round-half-to-even(35612.25, -2)
35600
math:log(0) => round-half-to-even()
-xs:double('INF')

4.5 Parsing numbers

It is possible to convert strings to values of type xs:integer, xs:float, xs:decimal, or xs:double using the constructor functions described in 20 Constructor functions or using cast expressions as described in 21 Casting.

In addition the fn:number function is available to convert strings to values of type xs:double. It differs from the xs:double constructor function in that any value outside the lexical space of the xs:double datatype is converted to the xs:double value NaN.

FunctionMeaning
fn:numberReturns the value indicated by $value or, if $value is not specified, the context value after atomization, converted to an xs:double.
fn:parse-integerConverts a string to an integer, recognizing any radix in the range 2 to 36.

4.5.1 fn:number

Summary

Returns the value indicated by $value or, if $value is not specified, the context value after atomization, converted to an xs:double.

Signature
fn:number(
$valueas xs:anyAtomicType?:= .
) as xs:double
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

Calling the zero-argument version of the function is defined to give the same result as calling the single-argument version with the context value (.). That is, fn:number() is equivalent to fn:number(.), as defined by the rules that follow.

If $value is the empty sequence or if $value cannot be converted to an xs:double, the xs:double value NaN is returned.

Otherwise, $value is converted to an xs:double following the rules of 21.1.3.2 Casting to xs:double. If the conversion to xs:double fails, the xs:double value NaN is returned.

Error Conditions

A type error is raised [err:XPDY0002]XP if $value is omitted and the context value is absentDM.

As a consequence of the rules given above, a type error is raised [err:XPTY0004]XP if the context value cannot be atomized, or if the result of atomizing the context value is a sequence containing more than one atomic item.

Notes

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.

Generally fn:number returns NaN rather than raising a dynamic error if the argument cannot be converted to xs:double. However, a type error is raised in the usual way if the supplied argument cannot be atomized or if the result of atomization does not match the required argument type.

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.

Generally fn:number returns NaN rather than raising a dynamic error if the argument cannot be converted to xs:double. However, a type error is raised in the usual way if the supplied argument cannot be atomized or if the result of atomization does not match the required argument type.

Examples
Variables
let $e := <e price="12.1" discount="NONE"/>
ExpressionResult
number(12)
1.2e1
number('12')
1.2e1
number('INF')
xs:double('INF')
number('NaN')
xs:double('NaN')
number('non-numeric')
xs:double('NaN')
number($e/@price)
1.21e1
number($e/@discount)
xs:double('NaN')
number($e/@misspelt)
xs:double('NaN')
("10", "11", "12") ! number()
1.0e1, 1.1e1, 1.2e1

4.5.2 fn:parse-integer

Changes in 4.0  

  1. New in 4.0  [Issue 241 PR 434 25 April 2023]

Summary

Converts a string to an integer, recognizing any radix in the range 2 to 36.

Signature
fn:parse-integer(
$valueas xs:string?,
$radixas xs:integer?:= 10
) as xs:integer?
Properties

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

Rules

If $value is an empty sequence, the result is an empty sequence.

The supplied $radix must be in the range 2 to 36 inclusive.

The string $value is preprocessed by stripping all whitespace characters (including internal whitespace) and underscore characters.

After this process, the supplied value must consist of an optional sign (+ or -) followed by a sequence of one or more generalized digits drawn from the first $radix characters in the alphabet 0123456789abcdefghijklmnopqrstuvwxyz; upper-case alphabetics A-Z may be used in place of their lower-case equivalents.

The value of a generalized digit corresponds to its position in this alphabet.

Formal Equivalent

The effect of the function is equivalent to the result of the following XPath expression, except in error cases.

let $alphabet := characters("0123456789abcdefghijklmnopqrstuvwxyz")
let $preprocessed := translate(
  $value, 
  codepoints-to-string((9, 10, 13, 32, 95)), 
  ""
)
let $digits := translate($preprocessed, "+-", "")
let $abs := sum(
  for $char at $p in reverse(characters(lower-case($digits)))
  return (index-of($alphabet, $char) - 1) * xs:integer(math:pow($radix, $p - 1))
)
return if (starts-with($preprocessed, "-")) then -$abs else +$abs
Error Conditions

A dynamic error is raised [err:FORG0011] if $radix is not in the range 2 to 36.

A dynamic error is raised [err:FORG0012] if, after stripping whitespace and underscores and the optional leading sign, $value is a zero-length string, or if it contains a character that is not among the first $radix characters in the alphabet 0123456789abcdefghijklmnopqrstuvwxyz, or the upper-case equivalent of such a character.

A dynamic error is raised [err:FOCA0003] if the value of the resulting integer exceeds the implementation-dependent limit on the size of an xs:integer.

Notes

When $radix takes its default value of 10, the function delivers the same result as casting $value (after removal of whitespace and underscores) to xs:integer.

If underscores or whitespace in the input need to be rejected, then the string should first be validated, perhaps using fn:matches.

If other characters may legitimately appear in the input, for example a leading 0x, then this must first be removed by pre-processing the input.

If the input uses a different family of digits, then the value should first be converted to the required digits using fn:translate.

A string in the lexical space of xs:hexBinary will always be an acceptable input, provided it is not too long. So, for example, the expression "1DE=" => xs:base64Binary() => xs:hexBinary() => xs:string() => parse-integer(16) can be used to convert the Base 64 value 1DE= to the integer 54321, via the hexadecimal string D431.

When $radix takes its default value of 10, the function delivers the same result as casting $value (after removal of whitespace and underscores) to xs:integer.

If underscores or whitespace in the input need to be rejected, then the string should first be validated, perhaps using fn:matches.

If other characters may legitimately appear in the input, for example a leading 0x, then this must first be removed by pre-processing the input.

If the input uses a different family of digits, then the value should first be converted to the required digits using fn:translate.

A string in the lexical space of xs:hexBinary will always be an acceptable input, provided it is not too long. So, for example, the expression "1DE=" => xs:base64Binary() => xs:hexBinary() => xs:string() => parse-integer(16) can be used to convert the Base 64 value 1DE= to the integer 54321, via the hexadecimal string D431.

Examples
Expression:

parse-integer(" 200 ")

Result:
200
Expression:

parse-integer("-20")

Result:
-20
Expression:

parse-integer(" +100")

Result:
100
Expression:

parse-integer("ff", 16)

Result:
255
Expression:

parse-integer("FFFF FFFF", 16)

Result:
4294967295
Expression:

parse-integer("-FFFF_FFFF", 16)

Result:
-4294967295
Expression:

parse-integer("377", 8)

Result:
255
Expression:

parse-integer("101", 2)

Result:
5
Expression:

parse-integer("vv", 32)

Result:
1023

Alphabetic base-26 numbering systems (hexavigesimal) can be parsed via translation. Note, enumerating systems that do not assign a symbol to zero (e.g., spreadsheet columns) must be preprocessed in a different fashion.

Expression:
lower-case("AAB")
=> translate("abcdefghijklmnopqrstuvwxyz", "0123456789abcdefghijklmnop")
=> parse-integer(26)
Result:
1

Digit-based numeration systems comparable to the Arabic numbers 0 through 9 can be parsed via translation.

Expression:
translate(value := '٢٠٢٣', replace := '٠١٢٣٤٥٦٧٨٩', with := '0123456789')
=> parse-integer()
Result:
2023

4.7 Formatting numbers

This section defines a function for formatting decimal and floating point numbers.

FunctionMeaning
fn:format-numberReturns a string containing a number formatted according to a given picture string and decimal format.

Note:

This function can be used to format any numeric quantity, including an integer. For integers, however, the fn:format-integer function offers additional possibilities. Note also that the picture strings used by the two functions are not 100% compatible, though they share some options in common.

4.7.2 fn:format-number

Changes in 4.0  

  1. The decimal format name can now be supplied as a value of type xs:QName, as an alternative to supplying a lexical QName as an instance of xs:string.  [Issue 780 PR 925 9 January 2024]

  2. Decimal format parameters can now be supplied directly as a map in the third argument, rather than referencing a format defined in the static context.  [Issues 340 1138 PRs 1049 1151 5 March 2024]

  3. For selected properties including percent and exponent-separator, it is now possible to specify a single-character marker to be used in the picture string, together with a multi-character rendition to be used in the formatted output.  [Issue 1048 PR 1250 11 June 2024]

Summary

Returns a string containing a number formatted according to a given picture string and decimal format.

Signature
fn:format-number(
$valueas xs:numeric?,
$pictureas xs:string,
$optionsas (xs:string | map(*))?:= ()
) as xs:string
Properties

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

The three-argument form of this function is ·deterministic·, ·context-dependent·, and ·focus-independent·. It depends on decimal formats, and namespaces.

Rules

The function formats $value as a string using the ·picture string· specified by the $picture argument and a decimal format.

The $value argument may be of any numeric data type (xs:double, xs:float, xs:decimal, or their subtypes including xs:integer). Note that if an xs:decimal is supplied, it is not automatically promoted to an xs:double, as such promotion can involve a loss of precision.

If the supplied value of the $value argument is an empty sequence, the function behaves as if the supplied value were the xs:double value NaN.

If $options is absent, or if it is supplied as an empty sequence or an empty map, then the number is formatted using the properties of the unnamed decimal format in the static context.

For backwards compatibility reasons, the decimal format can be supplied as an instance of xs:string. If the value of the $options argument is an xs:string, then its value must be a string which after removal of leading and trailing whitespace is in the form of an EQName as defined in the XPath 4.0 grammar, that is one of the following:

  • A lexical QName, which is expanded using the statically known namespaces. The default namespace is not used (no prefix means no namespace).

  • A URIQualifiedName using the syntax Q{uri}local, where the URI can be zero-length to indicate a name in no namespace.

The effective value of the $options argument is then the map { 'format-name': $FN } where $FN is the xs:QName result of expanding this EQName.

The entries that may appear in the $options map are as follows. The ·option parameter conventions· apply. The detailed rules for the interpretation of each option appear later.

In the table, the type xs:string (: matching '.' :) represents a single-character string, that is, a restriction of xs:string with the facet pattern=".", while the type xs:string (: matching '.|.:.*' :) indicates a string that is either a single character, or a single character followed by U+003A (COLON, :) followed by an arbitrary string. Such a property identifies two values: a single character called the marker, which is used to represent the property in the picture string; and an arbitrary string called the rendition which is used to represent in the property in the result string. In the absence of the colon the single character value is used both as the marker and the rendition.

The default value for absent options (other than format-name) is taken from a decimal format in the static context; the default values shown in the table are the values used if no specific value is assigned in the static context.

record(
format-name?as (xs:NCName | xs:QName)?,
decimal-separator?as xs:string (: matching '.|.:.*' :),
grouping-separator?as xs:string (: matching '.|.:.*' :),
exponent-separator?as xs:string (: matching '.|.:.*' :),
infinity?as xs:string,
minus-sign?as xs:string,
NaN?as xs:string,
percent?as xs:string (: matching '.|.:.*' :),
per-mille?as xs:string (: matching '.|.:.*' :),
zero-digit?as xs:string (: matching '.' :),
digit?as xs:string (: matching '.' :),
pattern-separator?as xs:string (: matching '.' :)
)
KeyMeaning

format-name?

The name of a decimal format in the static context; if absent, the unnamed decimal format in the static context is used. An xs:NCName represents the local part of an xs:QName in no namespace.
  • Type: (xs:NCName | xs:QName)?

  • Default: ()

decimal-separator?

The marker used to represent the decimal point in the picture string, and the rendition of the decimal point in the formatted number.
  • Type: xs:string (: matching '.|.:.*' :)

  • Default: "."

grouping-separator?

The marker used to separate groups of digits in the picture string, and the rendition of the grouping separator in the formatted number.
  • Type: xs:string (: matching '.|.:.*' :)

  • Default: ","

exponent-separator?

The marker used to separate the mantissa from the exponent in scientific notation in the picture string, and the rendition of the exponent separator in the formatted number.
  • Type: xs:string (: matching '.|.:.*' :)

  • Default: "e"

infinity?

The string used to represent the value positive or negative infinity in the formatted number.
  • Type: xs:string

  • Default: "Infinity"

minus-sign?

The string used as a minus sign in the formatted number if there is no subpicture for formatting negative numbers.
  • Type: xs:string

  • Default: "-"

NaN?

The string used to represent the value NaN in the formatted number.
  • Type: xs:string

  • Default: "NaN"

percent?

The marker used to indicate the presence of a percent sign in the picture string, and the rendition of the percent sign in the formatted number.
  • Type: xs:string (: matching '.|.:.*' :)

  • Default: "%"

per-mille?

marker used to indicate the presence of a per-mille sign in the picture string, and the rendition of the per-mille sign in the formatted number.
  • Type: xs:string (: matching '.|.:.*' :)

  • Default: "‰" (0x2030)

zero-digit?

Defines the characters used in the picture string to represent a mandatory digit: for example, if the zero-digit is 0 then any of the digits 0 to 9 may be used (interchangeably) in the picture string to represent a mandatory digit, and in the formatted number the characters 0 to 9 will be used to represent the digits zero to nine. The value must be a character in Unicode category Nd with decimal digit value 0 (zero).
  • Type: xs:string (: matching '.' :)

  • Default: "0"

digit?

The character used in the picture string to represent an optional digit.
  • Type: xs:string (: matching '.' :)

  • Default: "#"

pattern-separator?

The character used in the picture string to separate the positive and negative subpictures.
  • Type: xs:string (: matching '.' :)

  • Default: ";"

A base decimal format is established as follows:

  • If the format-name option is present, then the decimal format in the static context identified by this name.

  • Otherwise, the unnamed decimal format in the static context.

The base decimal format is then modified using the other entries in the supplied $options map.

The evaluation of the fn:format-number function takes place in two phases, an analysis phase described in 4.7.4 Analyzing the picture string and a formatting phase described in 4.7.5 Formatting the number.

The analysis phase takes as its inputs the ·picture string· and the variables derived from the relevant decimal format in the static context, and produces as its output a number of variables with defined values. The formatting phase takes as its inputs the number to be formatted and the variables produced by the analysis phase, and produces as its output a string containing a formatted representation of the number.

The result of the function is the formatted string representation of the supplied number.

Error Conditions

A dynamic error is raised [err:FODF1280] if the $options argument is supplied as an xs:string that is neither a valid lexical QName nor a valid URIQualifiedName, or if it uses a prefix that is not found in the statically known namespaces; or if the static context does not contain a declaration of a decimal format with a matching expanded QName; or if $options?format-name is present and the static context does not contain a declaration of a decimal format whose name matches $options?format-name. If the processor is able to detect the error statically (for example, when the argument is supplied as a string literal), then the processor may optionally signal this as a static error.

A dynamic error is raised [err:FODF1290] if a value of $format is not valid for the associated property, or if the properties of the decimal format resulting from a supplied $options map do not have distinct values.

Notes

A string is an ordered sequence of characters, and this specification uses terms such as “left” and “right”, “preceding” and “following” in relation to this ordering, irrespective of the position of the characters when visually rendered on some output medium. Both in the picture string and in the result string, digits with higher significance (that is, representing higher powers of ten) always precede digits with lower significance, even when the rendered text flow is from right to left.

In previous versions of XSLT and XQuery, decimal formats were typically defined in the static context using custom declarations (<xsl:decimal-format> in XSLT, declare decimal-format in XQuery) and then selected by name in a call on fn:format-number. This mechanism remains available, but in 4.0, it may be more convenient to dispense with these declarations, and instead to define a decimal format as a map bound to a global variable, which can be referenced in the $options argument of the fn:format-number call.

A string is an ordered sequence of characters, and this specification uses terms such as “left” and “right”, “preceding” and “following” in relation to this ordering, irrespective of the position of the characters when visually rendered on some output medium. Both in the picture string and in the result string, digits with higher significance (that is, representing higher powers of ten) always precede digits with lower significance, even when the rendered text flow is from right to left.

In previous versions of XSLT and XQuery, decimal formats were typically defined in the static context using custom declarations (<xsl:decimal-format> in XSLT, declare decimal-format in XQuery) and then selected by name in a call on fn:format-number. This mechanism remains available, but in 4.0, it may be more convenient to dispense with these declarations, and instead to define a decimal format as a map bound to a global variable, which can be referenced in the $options argument of the fn:format-number call.

Examples

The following examples assume a default decimal format in which the chosen digits are the ASCII digits 0-9, the decimal separator is ., the grouping separator is ,, the minus-sign is -, and the percent-sign is %.

Expression:

format-number(12345.6, '#,###.00')

Result:
"12,345.60"
Expression:

format-number(12345678.9, '9,999.99')

Result:
"12,345,678.90"
Expression:

format-number(123.9, '9999')

Result:
"0124"
Expression:

format-number(0.14, '01%')

Result:
"14%"
Expression:

format-number(0.14, '01%', { 'percent': '%:pc' })

Result:
"14pc"
Expression:
format-number(12345, '0.0###^0', { 
   'exponent-separator': '^:×10^' 
})
Result:
"1.2345×10^4"
Expression:

format-number(-6, '000')

Result:
"-006"
Expression:
format-number(1234567.8, '0.000,0', {
   'grouping-separator': '.',
   'decimal-separator': ','
 })
Result:
"1.234.567,8"

The following examples assume the existence of a decimal format named de in which the grouping separator is . and the decimal separator is ,:

Expression:

format-number(1234.5678, '#.##0,00', { 'format-name': 'de' })

Result:
"1.234,57"
Expression:
format-number(12345, '0,###^0', {
  'format-name': 'de',
  'exponent-separator': '^'
})
Result:
"1,234^4"
Expression:
format-number(12345, '0,###^0', {
  'format-name': 'de',
  'exponent-separator': '^:×10^'
})
Result:
"1,234×10^4"

The following examples assume that the exponent separator in decimal format fortran is E:

Expression:

format-number(1234.5678, '00.000E0', 'fortran')

Result:
"12.346E2"
Expression:

format-number(0.234, '0.0E0', 'fortran')

Result:
"2.3E-1"
Expression:

format-number(0.234, '#.00E0', 'fortran')

Result:
"0.23E0"
Expression:

format-number(0.234, '.00E0', 'fortran')

Result:
".23E0"

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: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:sqrtReturns the non-negative square root of the argument.
math:sinReturns the sine of the argument. The argument is an angle in radians.
math:cosReturns the cosine of the argument. The argument is an angle in radians.
math:tanReturns the tangent of the argument. The argument is an angle in radians.
math:asinReturns the arc sine of the argument.
math:acosReturns the arc cosine 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:sinhReturns the hyperbolic sine of the argument.
math:coshReturns the hyperbolic cosine of the argument.
math:tanhReturns the hyperbolic tangent of the argument.

4.8.3 math:exp

Summary

Returns the value of ex where x is the argument value.

Signature
math:exp(
$valueas xs:double?
) as xs:double?
Properties

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

Rules

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

Otherwise the result is the mathematical constant e raised to the power of $value, as defined in the [IEEE 754-2019] specification of the exp function applied to 64-bit binary floating point values.

Notes

The treatment of overflow and underflow is defined in 4.2 Arithmetic operators on numeric values.

The treatment of overflow and underflow is defined in 4.2 Arithmetic operators on numeric values.

Examples
ExpressionResult
math:exp(())
()
math:exp(0)
1.0e0
math:exp(1)
2.7182818284590455e0

(approximately)

math:exp(2)
7.38905609893065e0
math:exp(-1)
0.36787944117144233e0
math:exp(math:pi())
23.140692632779267e0
math:exp(xs:double('NaN'))
xs:double('NaN')
math:exp(xs:double('INF'))
xs:double('INF')
math:exp(xs:double('-INF'))
0.0e0

4.8.4 math:exp10

Summary

Returns the value of 10x, where x is the supplied argument value.

Signature
math:exp10(
$valueas xs:double?
) as xs:double?
Properties

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

Rules

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

Otherwise the result is ten raised to the power of $value, as defined in the [IEEE 754-2019] specification of the exp10 function applied to 64-bit binary floating point values.

Notes

The treatment of overflow and underflow is defined in 4.2 Arithmetic operators on numeric values.

The treatment of overflow and underflow is defined in 4.2 Arithmetic operators on numeric values.

Examples
ExpressionResult
math:exp10(())
()
math:exp10(0)
1.0e0
math:exp10(1)
1.0e1
math:exp10(0.5)
3.1622776601683795e0
math:exp10(-1)
1.0e-1
math:exp10(xs:double('NaN'))
xs:double('NaN')
math:exp10(xs:double('INF'))
xs:double('INF')
math:exp10(xs:double('-INF'))
0.0e0

4.8.5 math:log

Summary

Returns the natural logarithm of the argument.

Signature
math:log(
$valueas xs:double?
) as xs:double?
Properties

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

Rules

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

Otherwise the result is the natural logarithm of $value, as defined in the [IEEE 754-2019] specification of the log function applied to 64-bit binary floating point values.

Notes

The treatment of divideByZero and invalidOperation exceptions is defined in 4.2 Arithmetic operators on numeric values. The effect is that if the argument is zero, the result is -INF, and if it is negative, the result is NaN.

The treatment of divideByZero and invalidOperation exceptions is defined in 4.2 Arithmetic operators on numeric values. The effect is that if the argument is zero, the result is -INF, and if it is negative, the result is NaN.

Examples
ExpressionResult
math:log(())
()
math:log(0)
xs:double('-INF')
math:log(math:exp(1))
1.0e0
math:log(1.0e-3)
-6.907755278982137e0
math:log(2)
0.6931471805599453e0
math:log(-1)
xs:double('NaN')
math:log(xs:double('NaN'))
xs:double('NaN')
math:log(xs:double('INF'))
xs:double('INF')
math:log(xs:double('-INF'))
xs:double('NaN')

4.8.6 math:log10

Summary

Returns the base-ten logarithm of the argument.

Signature
math:log10(
$valueas xs:double?
) as xs:double?
Properties

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

Rules

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

Otherwise the result is the base-10 logarithm of $value, as defined in the [IEEE 754-2019] specification of the log10 function applied to 64-bit binary floating point values.

Notes

The treatment of divideByZero and invalidOperation exceptions is defined in 4.2 Arithmetic operators on numeric values. The effect is that if the argument is zero, the result is -INF, and if it is negative, the result is NaN.

The treatment of divideByZero and invalidOperation exceptions is defined in 4.2 Arithmetic operators on numeric values. The effect is that if the argument is zero, the result is -INF, and if it is negative, the result is NaN.

Examples
ExpressionResult
math:log10(())
()
math:log10(0)
xs:double('-INF')
math:log10(1.0e3)
3.0e0
math:log10(1.0e-3)
-3.0e0
math:log10(2)
0.3010299956639812e0
math:log10(-1)
xs:double('NaN')
math:log10(xs:double('NaN'))
xs:double('NaN')
math:log10(xs:double('INF'))
xs:double('INF')
math:log10(xs:double('-INF'))
xs:double('NaN')

4.8.7 math:pow

Summary

Returns the result of raising the first argument to the power of the second.

Signature
math:pow(
$xas xs:double?,
$yas xs:numeric
) as xs:double?
Properties

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

Rules

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

If $y is an instance of xs:integer, the result is $x raised to the power of $y as defined in the [IEEE 754-2019] specification of the pown function applied to a 64-bit binary floating point value and an integer.

Otherwise $y is converted to an xs:double by numeric promotion, and the result is $x raised to the power of $y as defined in the [IEEE 754-2019] specification of the pow function applied to two 64-bit binary floating point values.

Notes

The treatment of the divideByZero and invalidOperation exceptions is defined in 4.2 Arithmetic operators on numeric values. Some of the consequences are illustrated in the examples below.

The treatment of the divideByZero and invalidOperation exceptions is defined in 4.2 Arithmetic operators on numeric values. Some of the consequences are illustrated in the examples below.

Examples
ExpressionResult
math:pow((), 93.7)
()
math:pow(2, 3)
8.0e0
math:pow(-2, 3)
-8.0e0
math:pow(2, -3)
0.125e0
math:pow(-2, -3)
-0.125e0
math:pow(2, 0)
1.0e0
math:pow(0, 0)
1.0e0
math:pow(xs:double('INF'), 0)
1.0e0
math:pow(xs:double('NaN'), 0)
1.0e0
math:pow(-math:pi(), 0)
1.0e0
math:pow(0e0, 3)
0.0e0
math:pow(0e0, 4)
0.0e0
math:pow(-0e0, 3)
-0.0e0
math:pow(0, 4)
0.0e0
math:pow(0e0, -3)
xs:double('INF')
math:pow(0e0, -4)
xs:double('INF')
math:pow(-0e0, -3)
xs:double('-INF')
math:pow(0, -4)
xs:double('INF')
math:pow(16, 0.5e0)
4.0e0
math:pow(16, 0.25e0)
2.0e0
math:pow(0e0, -3.0e0)
xs:double('INF')
math:pow(-0e0, -3.0e0)
xs:double('-INF')

(Odd-valued whole numbers are treated specially).

math:pow(0e0, -3.1e0)
xs:double('INF')
math:pow(-0e0, -3.1e0)
xs:double('INF')
math:pow(0e0, 3.0e0)
0.0e0
math:pow(-0e0, 3.0e0)
-0.0e0

(Odd-valued whole numbers are treated specially).

math:pow(0e0, 3.1e0)
0.0e0
math:pow(-0e0, 3.1e0)
0.0e0
math:pow(-1, xs:double('INF'))
1.0e0
math:pow(-1, xs:double('-INF'))
1.0e0
math:pow(1, xs:double('INF'))
1.0e0
math:pow(1, xs:double('-INF'))
1.0e0
math:pow(1, xs:double('NaN'))
1.0e0
math:pow(-2.5e0, 2.0e0)
6.25e0
math:pow(-2.5e0, 2.00000001e0)
xs:double('NaN')

4.8.8 math:sqrt

Summary

Returns the non-negative square root of the argument.

Signature
math:sqrt(
$valueas xs:double?
) as xs:double?
Properties

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

Rules

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

Otherwise the result is the mathematical non-negative square root of $value as defined in the [IEEE 754-2019] specification of the squareRoot function applied to 64-bit binary floating point values.

Notes

The treatment of the invalidOperation exception is defined in 4.2 Arithmetic operators on numeric values. The effect is that if the argument is less than zero, the result is NaN.

If $value is positive or negative zero, positive infinity, or NaN, then the result is $value. (Negative zero is the only case where the result can have negative sign)

The treatment of the invalidOperation exception is defined in 4.2 Arithmetic operators on numeric values. The effect is that if the argument is less than zero, the result is NaN.

If $value is positive or negative zero, positive infinity, or NaN, then the result is $value. (Negative zero is the only case where the result can have negative sign)

Examples
ExpressionResult
math:sqrt(())
()
math:sqrt(0.0e0)
0.0e0
math:sqrt(-0.0e0)
-0.0e0
math:sqrt(1.0e6)
1.0e3
math:sqrt(2.0e0)
1.4142135623730951e0
math:sqrt(-2.0e0)
xs:double('NaN')
math:sqrt(xs:double('NaN'))
xs:double('NaN')
math:sqrt(xs:double('INF'))
xs:double('INF')
math:sqrt(xs:double('-INF'))
xs:double('NaN')

4.8.9 math:sin

Summary

Returns the sine of the argument. The argument is an angle in radians.

Signature
math:sin(
$radiansas xs:double?
) as xs:double?
Properties

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

Rules

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

Otherwise the result is the sine of $radians (which is treated as an angle in radians) as defined in the [IEEE 754-2019] specification of the sin function applied to 64-bit binary floating point values.

Notes

The treatment of the invalidOperation and underflow exceptions is defined in 4.2 Arithmetic operators on numeric values.

If $radians is positive or negative zero, the result is $radians.

If $radians is positive or negative infinity, or NaN, then the result is NaN.

Otherwise the result is always in the range -1.0e0 to +1.0e0

The treatment of the invalidOperation and underflow exceptions is defined in 4.2 Arithmetic operators on numeric values.

If $radians is positive or negative zero, the result is $radians.

If $radians is positive or negative infinity, or NaN, then the result is NaN.

Otherwise the result is always in the range -1.0e0 to +1.0e0

Examples
ExpressionResult
math:sin(())
()
math:sin(0)
0.0e0
math:sin(-0.0e0)
-0.0e0
math:sin(math:pi() div 2)
1.0e0

(approximately)

math:sin(-math:pi() div 2)
-1.0e0

(approximately)

math:sin(math:pi())
0.0e0

(approximately)

math:sin(xs:double('NaN'))
xs:double('NaN')
math:sin(xs:double('INF'))
xs:double('NaN')
math:sin(xs:double('-INF'))
xs:double('NaN')

4.8.10 math:cos

Summary

Returns the cosine of the argument. The argument is an angle in radians.

Signature
math:cos(
$radiansas xs:double?
) as xs:double?
Properties

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

Rules

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

If $radians is positive or negative infinity, or NaN, then the result is NaN.

Otherwise the result is the cosine of $radians (which is treated as an angle in radians) as defined in the [IEEE 754-2019] specification of the cos function applied to 64-bit binary floating point values.

Notes

The treatment of the invalidOperation exception is defined in 4.2 Arithmetic operators on numeric values.

If $radians is positive or negative zero, the result is $radians.

If $radiansis positive or negative infinity, or NaN, then the result is NaN.

Otherwise the result is always in the range -1.0e0 to +1.0e0

The treatment of the invalidOperation exception is defined in 4.2 Arithmetic operators on numeric values.

If $radians is positive or negative zero, the result is $radians.

If $radiansis positive or negative infinity, or NaN, then the result is NaN.

Otherwise the result is always in the range -1.0e0 to +1.0e0

Examples
ExpressionResult
math:cos(())
()
math:cos(0)
1.0e0
math:cos(-0.0e0)
1.0e0
math:cos(math:pi() div 2)
0.0e0

(approximately)

math:cos(-math:pi() div 2)
0.0e0

(approximately)

math:cos(math:pi())
-1.0e0

(approximately)

math:cos(xs:double('NaN'))
xs:double('NaN')
math:cos(xs:double('INF'))
xs:double('NaN')
math:cos(xs:double('-INF'))
xs:double('NaN')

4.8.11 math:tan

Summary

Returns the tangent of the argument. The argument is an angle in radians.

Signature
math:tan(
$radiansas xs:double?
) as xs:double?
Properties

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

Rules

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

Otherwise the result is the tangent of $radians (which is treated as an angle in radians) as defined in the [IEEE 754-2019] specification of the tan function applied to 64-bit binary floating point values.

Notes

The treatment of the invalidOperation and underflow exceptions is defined in 4.2 Arithmetic operators on numeric values.

If $radians is positive or negative infinity, or NaN, then the result is NaN.

The treatment of the invalidOperation and underflow exceptions is defined in 4.2 Arithmetic operators on numeric values.

If $radians is positive or negative infinity, or NaN, then the result is NaN.

Examples
ExpressionResult
math:tan(())
()
math:tan(0)
0.0e0
math:tan(-0.0e0)
-0.0e0
math:tan(math:pi() div 4)
1.0e0

(approximately)

math:tan(-math:pi() div 4)
-1.0e0

(approximately)

1 div math:tan(math:pi() div 2)
0.0e0

(approximately)

(Mathematically, tan(π/2) is positive infinity. But because math:pi() div 2 returns an approximation, the result of math:tan(math:pi() div 2) will be a large but finite number.)

1 div math:tan(-math:pi() div 2)
-0.0e0

(approximately)

(Mathematically, tan(-π/2) is negative infinity. But because -math:pi() div 2 returns an approximation, the result of math:tan(-math:pi() div 2) will be a large but finite negative number.)

math:tan(math:pi())
0.0e0

(approximately)

math:tan(xs:double('NaN'))
xs:double('NaN')
math:tan(xs:double('INF'))
xs:double('NaN')
math:tan(xs:double('-INF'))
xs:double('NaN')

4.8.12 math:asin

Summary

Returns the arc sine of the argument.

Signature
math:asin(
$valueas xs:double?
) as xs:double?
Properties

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

Rules

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

Otherwise the result is the arc sine of $value as defined in the [IEEE 754-2019] specification of the asin function applied to 64-bit binary floating point values. The result is in the range -π/2 to +π/2 radians.

Notes

The treatment of the invalidOperation and underflow exceptions is defined in 4.2 Arithmetic operators on numeric values.

If $value is positive or negative zero, the result is $value.

If $value is NaN, or if its absolute value is greater than one, then the result is NaN.

In other cases, the result is an xs:double value representing an angle θ in radians in the range -math:pi() div 2 <= θ <= math:pi() div 2.

The treatment of the invalidOperation and underflow exceptions is defined in 4.2 Arithmetic operators on numeric values.

If $value is positive or negative zero, the result is $value.

If $value is NaN, or if its absolute value is greater than one, then the result is NaN.

In other cases, the result is an xs:double value representing an angle θ in radians in the range -math:pi() div 2 <= θ <= math:pi() div 2.

Examples
ExpressionResult
math:asin(())
()
math:asin(0)
0.0e0
math:asin(-0.0e0)
-0.0e0
math:asin(1.0e0)
1.5707963267948966e0

(approximately)

math:asin(-1.0e0)
-1.5707963267948966e0

(approximately)

math:asin(2.0e0)
xs:double('NaN')
math:asin(xs:double('NaN'))
xs:double('NaN')
math:asin(xs:double('INF'))
xs:double('NaN')
math:asin(xs:double('-INF'))
xs:double('NaN')

4.8.13 math:acos

Summary

Returns the arc cosine of the argument.

Signature
math:acos(
$valueas xs:double?
) as xs:double?
Properties

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

Rules

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

Otherwise the result is the arc cosine of $value, as defined in the [IEEE 754-2019] specification of the acos function applied to 64-bit binary floating point values. The result is in the range zero to +π radians.

Notes

The treatment of the invalidOperation exception is defined in 4.2 Arithmetic operators on numeric values.

If $value is NaN, or if its absolute value is greater than one, then the result is NaN.

In other cases, the result is an xs:double value representing an angle θ in radians in the range 0 <= θ <= math:pi().

The treatment of the invalidOperation exception is defined in 4.2 Arithmetic operators on numeric values.

If $value is NaN, or if its absolute value is greater than one, then the result is NaN.

In other cases, the result is an xs:double value representing an angle θ in radians in the range 0 <= θ <= math:pi().

Examples
ExpressionResult
math:acos(())
()
math:acos(0)
1.5707963267948966e0

(approximately)

math:acos(-0.0e0)
1.5707963267948966e0

(approximately)

math:acos(1.0e0)
0.0e0
math:acos(-1.0e0)
3.141592653589793e0

(approximately)

math:acos(2.0e0)
xs:double('NaN')
math:acos(xs:double('NaN'))
xs:double('NaN')
math:acos(xs:double('INF'))
xs:double('NaN')
math:acos(xs:double('-INF'))
xs:double('NaN')

4.8.14 math:atan

Summary

Returns the arc tangent of the argument.

Signature
math:atan(
$valueas xs:double?
) as xs:double?
Properties

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

Rules

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

Otherwise the result is the arc tangent of $value, as defined in the [IEEE 754-2019] specification of the atan function applied to 64-bit binary floating point values. The result is in the range -π/2 to +π/2 radians.

Notes

The treatment of the underflow exception is defined in 4.2 Arithmetic operators on numeric values.

If $value is positive or negative zero, the result is $value.

If $value is NaN then the result is NaN.

In other cases, the result is an xs:double value representing an angle θ in radians in the range -math:pi() div 2 <= θ <= math:pi() div 2.

The treatment of the underflow exception is defined in 4.2 Arithmetic operators on numeric values.

If $value is positive or negative zero, the result is $value.

If $value is NaN then the result is NaN.

In other cases, the result is an xs:double value representing an angle θ in radians in the range -math:pi() div 2 <= θ <= math:pi() div 2.

Examples
ExpressionResult
math:atan(())
()
math:atan(0)
0.0e0
math:atan(-0.0e0)
-0.0e0
math:atan(1.0e0)
0.7853981633974483e0

(approximately)

math:atan(-1.0e0)
-0.7853981633974483e0

(approximately)

math:atan(xs:double('NaN'))
xs:double('NaN')
math:atan(xs:double('INF'))
1.5707963267948966e0

(approximately)

math:atan(xs:double('-INF'))
-1.5707963267948966e0

(approximately)

4.8.15 math:atan2

Summary

Returns the angle in radians subtended at the origin by the point on a plane with coordinates (x, y) and the positive x-axis.

Signature
math:atan2(
$yas xs:double,
$xas xs:double
) as xs:double
Properties

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

Rules

The result is the value of atan2(y, x) as defined in the [IEEE 754-2019] specification of the atan2 function applied to 64-bit binary floating point values. The result is in the range -π to +π radians.

Notes

The treatment of the underflow exception is defined in 4.2 Arithmetic operators on numeric values. The following rules apply when the values are finite and non-zero, (subject to rules for overflow, underflow and approximation).

If either argument is NaN then the result is NaN.

If $x is positive, then the value of atan2($y, $x) is atan($y div $x).

If $x is negative, then:

The treatment of the underflow exception is defined in 4.2 Arithmetic operators on numeric values. The following rules apply when the values are finite and non-zero, (subject to rules for overflow, underflow and approximation).

If either argument is NaN then the result is NaN.

If $x is positive, then the value of atan2($y, $x) is atan($y div $x).

If $x is negative, then:

  • If $y is positive, then the value of atan2($y, $x) is atan($y div $x) + π.

  • If $y is negative, then the value of atan2($y, $x) is atan($y div $x) - π.

Some results for special values of the arguments are shown in the examples below.

Some results for special values of the arguments are shown in the examples below.

Examples
ExpressionResult
math:atan2(+0.0e0, 0.0e0)
0.0e0
math:atan2(-0.0e0, 0.0e0)
-0.0e0
math:atan2(+0.0e0, -0.0e0)
3.141592653589793e0
math:atan2(-0.0e0, -0.0e0)
-3.141592653589793e0
math:atan2(-1, 0.0e0)
-1.5707963267948966e0
math:atan2(+1, 0.0e0)
1.5707963267948966e0
math:atan2(-0.0e0, -1)
-3.141592653589793e0
math:atan2(+0.0e0, -1)
3.141592653589793e0
math:atan2(-0.0e0, +1)
-0.0e0
math:atan2(+0.0e0, +1)
+0.0e0

4.8.16 math:sinh

Changes in 4.0  

  1. New in 4.0  [Issues 1196 1216 PRs 1205 1230 14 May 2024]

Summary

Returns the hyperbolic sine of the argument.

Signature
math:sinh(
$valueas xs:double?
) as xs:double?
Properties

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

Rules

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

Otherwise the result is the hyperbolic sine of $value as defined in the [IEEE 754-2019] specification of the sinh function applied to 64-bit binary floating point values.

Notes

The treatment of the overflow and underflow exceptions is defined in 4.2 Arithmetic operators on numeric values.

If $value is positive or negative zero, the result is $value.

If $value is positive or negative infinity, or NaN, the result is NaN.

The treatment of the overflow and underflow exceptions is defined in 4.2 Arithmetic operators on numeric values.

If $value is positive or negative zero, the result is $value.

If $value is positive or negative infinity, or NaN, the result is NaN.

Examples
ExpressionResult
math:sinh(1)
1.1752011936438014e0

(approximately)

math:sinh(math:pi())
11.548739357257748e0

(approximately)

4.8.17 math:cosh

Changes in 4.0  

  1. New in 4.0  [Issues 1196 1216 PRs 1205 1230 14 May 2024]

Summary

Returns the hyperbolic cosine of the argument.

Signature
math:cosh(
$valueas xs:double?
) as xs:double?
Properties

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

Rules

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

Otherwise the result is the hyperbolic cosine of $value as defined in the [IEEE 754-2019] specification of the cosh function applied to 64-bit binary floating point values.

Notes

The treatment of the overflow exception is defined in 4.2 Arithmetic operators on numeric values.

If $value is positive or negative zero, the result is 1.

If $value is positive or negative infinity, the result is INF.

If $value is NaN, the result is NaN.

In other cases, the result is an xs:double in the range +1.0 to INF.

The treatment of the overflow exception is defined in 4.2 Arithmetic operators on numeric values.

If $value is positive or negative zero, the result is 1.

If $value is positive or negative infinity, the result is INF.

If $value is NaN, the result is NaN.

In other cases, the result is an xs:double in the range +1.0 to INF.

Examples
ExpressionResult
math:cosh(0)
1.0e0
math:cosh(math:pi())
11.591953275521519e0

(approximately)

4.8.18 math:tanh

Changes in 4.0  

  1. New in 4.0  [Issues 1196 1216 PRs 1205 1230 14 May 2024]

Summary

Returns the hyperbolic tangent of the argument.

Signature
math:tanh(
$valueas xs:double?
) as xs:double?
Properties

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

Rules

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

Otherwise the result is the hyperbolic tangent of $value as defined in the [IEEE 754-2019] specification of the tanh function applied to 64-bit binary floating point values.

Notes

The treatment of the underflow exception is defined in 4.2 Arithmetic operators on numeric values.

If $value is positive or negative zero, the result is $value.

If $value is positive infinity, the result is +1.0.

If $value is negative infinity, the result is -1.0.

In other cases, the result is an xs:double in the range -1.0 to +1.0.

The treatment of the underflow exception is defined in 4.2 Arithmetic operators on numeric values.

If $value is positive or negative zero, the result is $value.

If $value is positive infinity, the result is +1.0.

If $value is negative infinity, the result is -1.0.

In other cases, the result is an xs:double in the range -1.0 to +1.0.

Examples
ExpressionResult
math:tanh(1)
0.7615941559557649e0

(approximately)

math:tanh(math:pi())
0.99627207622075e0

(approximately)

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  

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

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:

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

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

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

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 Functions on 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.7 fn:codepoint-equal

Summary

Returns true if two strings are equal, considered codepoint-by-codepoint.

Signature
fn:codepoint-equal(
$value1as xs:string?,
$value2as xs:string?
) as xs:boolean?
Properties

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

Rules

If either argument is the empty sequence, the function returns the empty sequence.

Otherwise, the function returns true or false depending on whether $value1 is equal to $value2, according to the Unicode codepoint collation (http://www.w3.org/2005/xpath-functions/collation/codepoint).

Notes

This function allows xs:anyURI values to be compared without having to specify the Unicode codepoint collation.

This function allows xs:anyURI values to be compared without having to specify the Unicode codepoint collation.

Examples
ExpressionResult
codepoint-equal("abcd", "abcd")
true()
codepoint-equal("abcd", "abcd ")
false()
codepoint-equal("", "")
true()
codepoint-equal("", ())
()
codepoint-equal((), ())
()

5.3.9 fn:collation-available

Changes in 4.0  

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

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()

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

5.3.10 fn:collation-key

Summary

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

Signature
fn:collation-key(
$valueas xs:string,
$collationas xs:string?:= fn:default-collation()
) as xs:base64Binary
Properties

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

Rules

Calling the one-argument version of this function is equivalent to calling the two-argument version supplying the default collation as the second argument.

The function returns an ·implementation-dependent· value with the property that, for any two strings $K1 and $K2:

  • collation-key($K1, $C) eq collation-key($K2, $C) if and only if compare($K1, $K2, $C) eq 0

  • collation-key($K1, $C) lt collation-key($K2, $C) if and only if compare($K1, $K2, $C) lt 0

The collation used by this function is determined according to the rules in 5.3.6 Choosing a collation. Collation keys are defined as xs:base64Binary values to ensure unambiguous and context-free comparison semantics.

An implementation is free to generate a collation key in any convenient way provided that it always generates the same collation key for two strings that are equal under the collation, and different collation keys for strings that are not equal. This holds only within a single ·execution scope·; an implementation is under no obligation to generate the same collation keys during a subsequent unrelated query or transformation.

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.

Error Conditions

An error is raised [err:FOCH0004] if the specified collation does not support the generation of collation keys.

Notes

The function is provided primarily for use with maps. If a map is required where codepoint equality is inappropriate for comparing keys, then a common technique is to normalize the key so that equality matching becomes feasible. There are many ways keys can be normalized, for example by use of functions such as fn:upper-case, fn:lower-case, fn:normalize-space, or fn:normalize-unicode, but this function provides a way of normalizing them according to the rules of a specified collation. For example, if the collation ignores accents, then the function will generate the same collation key for two input strings that differ only in their use of accents.

The result of the function is defined to be an xs:base64Binary value. Binary values are chosen because they have unambiguous and context-free comparison semantics, because the value space is unbounded, and because the ordering rules are such that between any two values in the ordered value space, an arbitrary number of further values can be interpolated. The choice between xs:base64Binary and xs:hexBinary is arbitrary; the only operation that behaves differently between the two binary data types is conversion to/from a string, and this operation is not one that is normally required for effective use of collation keys.

For collations based on the Unicode Collation Algorithm, an algorithm for computing collation keys is provided in [UTS #10]. Implementations are not required to use this algorithm.

The fact that collation keys are ordered can be exploited in XQuery, whose order by clause does not allow the collation to be selected dynamically. This restriction can be circumvented by rewriting the clause order by $e/@key collation "URI" as order by fn:collation-key($e/@key, $collation), where $collation allows the collation to be chosen dynamically.

Note that xs:base64Binary becomes an ordered type in XPath 3.1, making binary collation keys possible.

The fn:collation-available can be used to ask whether a particular collation is capable of delivering collation keys.

The function is provided primarily for use with maps. If a map is required where codepoint equality is inappropriate for comparing keys, then a common technique is to normalize the key so that equality matching becomes feasible. There are many ways keys can be normalized, for example by use of functions such as fn:upper-case, fn:lower-case, fn:normalize-space, or fn:normalize-unicode, but this function provides a way of normalizing them according to the rules of a specified collation. For example, if the collation ignores accents, then the function will generate the same collation key for two input strings that differ only in their use of accents.

The result of the function is defined to be an xs:base64Binary value. Binary values are chosen because they have unambiguous and context-free comparison semantics, because the value space is unbounded, and because the ordering rules are such that between any two values in the ordered value space, an arbitrary number of further values can be interpolated. The choice between xs:base64Binary and xs:hexBinary is arbitrary; the only operation that behaves differently between the two binary data types is conversion to/from a string, and this operation is not one that is normally required for effective use of collation keys.

For collations based on the Unicode Collation Algorithm, an algorithm for computing collation keys is provided in [UTS #10]. Implementations are not required to use this algorithm.

The fact that collation keys are ordered can be exploited in XQuery, whose order by clause does not allow the collation to be selected dynamically. This restriction can be circumvented by rewriting the clause order by $e/@key collation "URI" as order by fn:collation-key($e/@key, $collation), where $collation allows the collation to be chosen dynamically.

Note that xs:base64Binary becomes an ordered type in XPath 3.1, making binary collation keys possible.

The fn:collation-available can be used to ask whether a particular collation is capable of delivering collation keys.

Examples
Variables
let $C := collation({ 'strength': 'primary' })
Expression:
map:merge(
  ({ collation-key("A", $C): 1 }, { collation-key("a", $C): 2 }),
  { "duplicates": "use-last" }
)(collation-key("A", $C))
Result:
2

(Given that the keys of the two entries are equal under the rules of the chosen collation, only one of the entries can appear in the result; the one that is chosen is the one from the last map in the input sequence.)

Expression:
let $M := {
  collation-key("A", $C): 1,
  collation-key("B", $C): 2
}
return $M(collation-key("a", $C))
Result:
1

(The strings "A" and "a" have the same collation key under this collation.)

As the above examples illustrate, it is important that when the collation-key function is used to add entries to a map, then it must also be used when retrieving entries from the map. This process can be made less error-prone by encapsulating the map within a function: fn($k) { $M(collation-key($k, $collation) }.

5.3.11 fn:contains-token

Summary

Determines whether or not any of the supplied strings, when tokenized at whitespace boundaries, contains the supplied token, under the rules of the supplied collation.

Signature
fn:contains-token(
$valueas xs:string*,
$tokenas xs:string,
$collationas xs:string?:= fn:default-collation()
) as xs:boolean
Properties

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

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

Rules

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

Leading and trailing whitespace is trimmed from $token. If the trimmed value of $token is a zero-length string, the function returns false.

The collation used by this function is determined according to the rules in 5.3.6 Choosing a collation.

The function returns true if and only if there is string in $value which, after tokenizing at whitespace boundaries, contains a token that is equal to the trimmed value of $token under the rules of the selected collation.

Formal Equivalent

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

some $t in $value ! tokenize(.) satisfies
  compare($t, replace($token, '^\s*|\s*$', ''), $collation) eq 0
Notes

Interior whitespace within $token will cause the function to return false, unless such whitespace is ignored by the selected collation.

This function can be used for processing space-separated attribute values (for example, the XHTML and DITA class attribute), where one often needs to test for the presence of a single token in a space-separated list. The function is designed to work both when the attribute has been validated against an XSD list type, and when it appears as a single untyped string. It differs from the HTML 5 definition in that HTML 5 recognizes form feed (x0C) as a separator. To reproduce the HTML token matching behavior, the HTML ASCII case-insensitive collation should be used: see 5.3.5 The HTML ASCII Case-Insensitive Collation.

Interior whitespace within $token will cause the function to return false, unless such whitespace is ignored by the selected collation.

This function can be used for processing space-separated attribute values (for example, the XHTML and DITA class attribute), where one often needs to test for the presence of a single token in a space-separated list. The function is designed to work both when the attribute has been validated against an XSD list type, and when it appears as a single untyped string. It differs from the HTML 5 definition in that HTML 5 recognizes form feed (x0C) as a separator. To reproduce the HTML token matching behavior, the HTML ASCII case-insensitive collation should be used: see 5.3.5 The HTML ASCII Case-Insensitive Collation.

Examples
Expression:

contains-token("red green blue ", "red")

Result:
true()
Expression:

contains-token(("red", "green", "blue"), " red ")

Result:
true()
Expression:

contains-token("red, green, blue", "red")

Result:
false()
Expression:
contains-token(
  "red green blue",
  "RED",
  "http://www.w3.org/2005/xpath-functions/collation/html-ascii-case-insensitive"
)
Result:
true()

5.4 Functions on string values

The following functions are defined on values of type xs:string and types derived from it.

FunctionMeaning
fn:charReturns a string containing a particular character or glyph.
fn:charactersSplits the supplied string into a sequence of single-character strings.
fn:graphemesSplits the supplied string into a sequence of single-grapheme strings.
fn:concatReturns the concatenation of the arguments, treated as sequences of strings.
fn:string-joinReturns a string created by concatenating the items in a sequence, with a defined separator between adjacent items.
fn:substringReturns the part of $value beginning at the position indicated by $start and continuing for the number of ·characters· indicated by $length.
fn:string-lengthReturns the number of ·characters· in a string.
fn:normalize-spaceReturns $value with leading and trailing whitespace removed, and sequences of internal whitespace reduced to a single space character.
fn:normalize-unicodeReturns $value after applying Unicode normalization.
fn:upper-caseConverts a string to upper case.
fn:lower-caseConverts a string to lower case.
fn:translateReturns $value modified by replacing or removing individual characters.
fn:hashReturns the results of a specified hash, checksum, or cyclic redundancy check function applied to the input.

Notes:

When the above operators and functions are applied to datatypes derived from xs:string, they are guaranteed to return values that are instances of xs:string, but the value might or might not be an instance of the particular subtype of xs:string to which they were applied.

The strings returned by fn:concat and fn:string-join are not guaranteed to be normalized. But see note in fn:concat.

5.4.1 fn:char

Changes in 4.0  

  1. New in 4.0  [Issues 121 989 PRs 261 306 993 10 January 2023]

Summary

Returns a string containing a particular character or glyph.

Signature
fn:char(
$valueas (xs:string | xs:positiveInteger)
) as xs:string
Properties

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

Rules

The function returns a string, generally containing a single ·character· or glyph, identified by $value.

The supplied value of $value must be one of the following:

  1. A Unicode codepoint, supplied as an integer. For example fn:char(9) returns the tab character.

  2. An HTML5 character reference name (often referred to as an entity name) as defined at https://html.spec.whatwg.org/multipage/named-characters.html. The name is written with no leading ampersand and no trailing semicolon. For example fn:char("pi") represents the character U+03C0 (GREEK SMALL LETTER PI, π) and fn:char("nbsp") returns U+00A0 (NON-BREAKING SPACE, NBSP) .

    A processor may recognize additional character reference names defined in other versions of HTML. Character reference names are case-sensitive.

    In the event that the HTML5 character reference name identifies a string comprising multiple codepoints, that string is returned.

    [TODO: add a proper bibliographic reference.]

  3. A backslash-escape sequence from the set \n (U+000A (NEWLINE) ), \r (U+000D (CARRIAGE RETURN) ), or \t (U+0009 (TAB) ).

The result must consist of ·permitted characters·. For example fn:char(0xDEAD) is invalid because it is in the surrogate range.

Error Conditions

The function fails with a dynamic error [err:FOCH0005] if $value is not a valid representation of a ·permitted character· or sequence of permitted characters.

Notes

Although all Unicode characters can appear in string literals (the delimiting quotation marks can be escaped by doubling them), some characters are not visually distinctive, so representing them by name may make code more readable. In addition, there may be contexts where it is necessary or prudent to write XPath expressions using ASCII characters only, for example where an expression is used in the query part of a URI.

A few HTML5 character reference names identify glyphs whose Unicode representation uses multiple codepoints. For example, the name NotEqualTilde refers to the glyph ≂̸ which is expressed using the two codepoints U+2242 (MINUS TILDE, ) , U+0338 (COMBINING LONG SOLIDUS OVERLAY) . In such cases the string length of the result of the function will exceed one.

Although all Unicode characters can appear in string literals (the delimiting quotation marks can be escaped by doubling them), some characters are not visually distinctive, so representing them by name may make code more readable. In addition, there may be contexts where it is necessary or prudent to write XPath expressions using ASCII characters only, for example where an expression is used in the query part of a URI.

A few HTML5 character reference names identify glyphs whose Unicode representation uses multiple codepoints. For example, the name NotEqualTilde refers to the glyph ≂̸ which is expressed using the two codepoints U+2242 (MINUS TILDE, ) , U+0338 (COMBINING LONG SOLIDUS OVERLAY) . In such cases the string length of the result of the function will exceed one.

Examples
ExpressionResult
char("aacute")
"á"
char("eth")
"ð"
char(9)
codepoints-to-string(9)

(The character tab).

char("\t")
codepoints-to-string(9)

(The character tab).

char(0x20)
" "
char(0x1D1CA)
"𝇊"

(The character MUSICAL SYMBOL TEMPUS IMPERFECTUM CUM PROLATIONE PERFECTA).

char("NotEqualTilde")
codepoints-to-string((8770, 824))

(This HTML5 character reference name expands to multiple codepoints.)

5.4.3 fn:graphemes

Changes in 4.0  

  1. New in 4.0  [Issue 73 PR 1068 15 May 2024]

Summary

Splits the supplied string into a sequence of single-grapheme strings.

Signature
fn:graphemes(
$valueas xs:string?
) as xs:string*
Properties

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

Rules

The function returns a sequence of strings. Each string in the sequence contains one or more ·character·s that collectively constitute a single extended grapheme cluster, as defined by [UAX #29].

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

Notes

The resultant sequence of strings are extended graphemes, not legacy graphemes (see [UAX #29]).

The resultant sequence of strings are extended graphemes, not legacy graphemes (see [UAX #29]).

Examples
ExpressionResult
graphemes("a" || char(0x308) || "b")
"a" || char(0x308), "b"

(a + ◌̈ + b, three characters, two graphemes).

graphemes("")
()
graphemes(())
()
graphemes(char('\r') || char('\n'))
char('\r') || char('\n')

(Carriage return + line feed, two characters, one grapheme).

graphemes(char(0x1F476) || char(0x200D) || char(0x1F6D1))
char(0x1F476) || char(0x200D) || char(0x1F6D1)

(👶 +ZWJ + 🛑, three characters, one grapheme).

graphemes("कत")
"क", "त"

(क + त, two characters, two graphemes).

graphemes("क" || char(0x93C) || char(0x200D) || char(0x94D) || "त")
"क" || char(0x93C) || char(0x200D) || char(0x94D) || "त"

(क + ◌़ + ZWJ + ◌् + त, five characters, one grapheme).

5.4.4 fn:concat

Changes in 4.0  

  1. The function can now take any number of arguments (previously it had to be two or more), and the arguments can be sequences of strings rather than single strings.  [Issue 701 PR 702 19 September 2023]

Summary

Returns the concatenation of the arguments, treated as sequences of strings.

Operator Mapping

The two-argument form of this function defines the semantics of the || operator.

Signature
fn:concat(
$valuesas xs:anyAtomicType* ...:= ()
) as xs:string
Properties

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

Rules

Unlike all other functions, this function is defined to be variadic, as indicated by the ellipsis in the function signature. Conceptually, there is an infinite set of functions with different numbers of arguments (minimum arity zero, maximum arity unbounded):

  • concat() returns a zero-length string, "".

  • concat("a") returns "a".

  • concat("a", "b") returns "ab".

  • concat("a", "b", "c") returns "abc".

  • concat("a", "b", "c", "d") returns "abcd".

  • and so on.

It is equally possible to supply a single argument containing a sequence of strings:

  • concat(()) returns a zero-length string, "".

  • concat(("a")) returns "a".

  • concat(("a", "b")) returns "ab".

  • concat(("a", "b", "c")) returns "abc".

  • concat(("a", "b", "c", "d")) returns "abcd".

  • and so on.

More generally, any argument can be a sequence of strings:

  • concat(("a", "b"), "c") returns "abc".

  • concat(("a", "b"), (), ("c", "d")) returns "abcd".

A static call on the fn:concat function must use positional arguments, it cannot use keywords.

Each of the parameters has the required type xs:anyAtomicType*. The coercion rules ensure that each supplied argument is first converted to a sequence of atomic items by applying atomization. These sequences are then combined (by sequence concatenationXP) into a single sequence, and each item in the combined sequence is converted to a string using the fn:string function. The strings are then concatenated with no separator.

If XPath 1.0 compatibility mode is set to true in the static context of a static function call to fn:concat, then each supplied argument $v is first reduced to a single string, the result of the expression xs:string($v[1]). This is special-case processing for the fn:concat function, it is not something that follows from the general rules for calling variadic functions. This reflects the fact that fn:concat had custom behavior in XPath 1.0. This rule applies only to static function calls.

A named function reference can be used to create a function item with any arity: for example concat#3 returns a function item that takes three arguments, which it concatenates. Similarly partial function application can be used to construct a function that concatenates fixed and variable values: for example concat('[', ?, ']') returns a function item that takes a single argument and wraps the string value of this argument in square brackets. Similarly, concat(?, '-', ?) returns a function item of arity two; it returns the string values of the two arguments separated by a hyphen.

Notes

As mentioned in 5.1 String types Unicode normalization is not automatically applied to the result of fn:concat. If a normalized result is required, fn:normalize-unicode can be applied to the xs:string returned by fn:concat. The following XQuery:

let $v1 := "I plan to go to Mu"
let $v2 := "?nchen in September"
return concat($v1, $v2)

As mentioned in 5.1 String types Unicode normalization is not automatically applied to the result of fn:concat. If a normalized result is required, fn:normalize-unicode can be applied to the xs:string returned by fn:concat. The following XQuery:

let $v1 := "I plan to go to Mu"
let $v2 := "?nchen in September"
return concat($v1, $v2)

where the ? represents either the actual Unicode character U+0308 (COMBINING DIAERESIS) or the numeric character reference &#x0308;, will return:

"I plan to go to Mu?nchen in September"

where the ? again represents either the actual Unicode character U+0308 (COMBINING DIAERESIS) or the numeric character reference &#x0308;. It is worth noting that the returned value is not normalized in NFC; however, it is normalized in NFD.

However, the following XQuery:

let $v1 := "I plan to go to Mu"
let $v2 := "?nchen in September"
return normalize-unicode(concat($v1, $v2))

where ? represents either the actual Unicode character U+0308 (COMBINING DIAERESIS) or the numeric character reference &#x0308;, will return:

"I plan to go to München in September"

This returned result is normalized in NFC.

Alternatives to the fn:concat function include the concatenation operator || (for example $x || '-' || $y), the use of string templates (for example `{$x}-{$y}`), and the fn:string-join function.

where the ? represents either the actual Unicode character U+0308 (COMBINING DIAERESIS) or the numeric character reference &#x0308;, will return:

"I plan to go to Mu?nchen in September"

where the ? again represents either the actual Unicode character U+0308 (COMBINING DIAERESIS) or the numeric character reference &#x0308;. It is worth noting that the returned value is not normalized in NFC; however, it is normalized in NFD.

However, the following XQuery:

let $v1 := "I plan to go to Mu"
let $v2 := "?nchen in September"
return normalize-unicode(concat($v1, $v2))

where ? represents either the actual Unicode character U+0308 (COMBINING DIAERESIS) or the numeric character reference &#x0308;, will return:

"I plan to go to München in September"

This returned result is normalized in NFC.

Alternatives to the fn:concat function include the concatenation operator || (for example $x || '-' || $y), the use of string templates (for example `{$x}-{$y}`), and the fn:string-join function.

Examples
Expression:

concat('un', 'grateful')

Result:
"ungrateful"
Expression:

concat(('un', 'grateful'))

Result:
"ungrateful"
Expression:
concat(
  'Thy ', (), 'old ', "groans", "", ' ring',
  ' yet', ' in', ' my', ' ancient',' ears.'
)
Result:
"Thy old groans ring yet in my ancient ears."
Expression:

concat('Ciao!', ())

Result:
"Ciao!"
Expression:

concat('Ingratitude, ', 'thou ', ('marble-hearted', ' fiend!'))

Result:
"Ingratitude, thou marble-hearted fiend!"
Expression:

concat(01, 02, 03, 04, true())

Result:
"1234true"
Expression:

concat()

Result:
""
Expression:

10 || '/' || 6

Result:
"10/6"

5.4.5 fn:string-join

Summary

Returns a string created by concatenating the items in a sequence, with a defined separator between adjacent items.

Signature
fn:string-join(
$valuesas xs:anyAtomicType*,
$separatoras xs:string?:= ""
) as xs:string
Properties

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

Rules

If the second argument is omitted or an empty sequence, the effect is the same as calling the two-argument version with $separator set to a zero-length string.

The coercion rules ensure that the supplied $values argument is first converted to a sequence of atomic items by applying atomization.

The function then returns an xs:string created by casting each item in the atomized sequence to an xs:string, and then concatenating the result strings in order, using the value of $separator as a separator between adjacent strings. If $separator is the zero-length string, then the items in $values are concatenated without a separator.

Notes

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

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

Examples
Variables
let $doc := <doc><chap><section xml:id="xyz"/></chap></doc>
Expression:

string-join(1 to 9)

Result:
"123456789"
Expression:

string-join(('Now', 'is', 'the', 'time', '...'), ' ')

Result:
"Now is the time ..."
Expression:
string-join(
  ('Blow, ', 'blow, ', 'thou ', 'winter ', 'wind!'),
  ''
)
Result:
"Blow, blow, thou winter wind!"
Expression:

string-join((), 'separator')

Result:
""
Expression:

string-join(1 to 5, ', ')

Result:
"1, 2, 3, 4, 5"
Expression:
$doc//@xml:id
! string-join((node-name(), '="', ., '"'))
Result:
'xml:id="xyz"'
Expression:
$doc//section
! string-join(ancestor-or-self::*/name(), '/')
Result:
"doc/chap/section"

5.4.6 fn:substring

Changes in 4.0  

  1. The third argument can now be supplied as an empty sequence.  [Issue 895 PR 901 16 December 2023]

Summary

Returns the part of $value beginning at the position indicated by $start and continuing for the number of ·characters· indicated by $length.

Signature
fn:substring(
$valueas xs:string?,
$startas xs:double,
$lengthas xs:double?:= ()
) as xs:string
Properties

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

Rules

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

Otherwise, the function returns a string comprising those ·characters· of $value whose index position (counting from one) is greater than or equal to $start (rounded to an integer), and (if $length is specified and non-empty) less than the sum of $start and $length (both rounded to integers).

The characters returned do not extend beyond $value. If $start is zero or negative, only those characters in positions greater than zero are returned.

More specifically, the three argument version of the function returns the characters in $value whose position $p satisfies:

fn:round($start) <= $p and $p < fn:round($start) + fn:round($length)

The two argument version of the function assumes that $length is infinite and thus returns the ·characters· in $value whose position $p satisfies:

fn:round($start) <= $p

In the above computations, the rules for op:numeric-less-than apply.

Notes

The first character of a string is located at position 1, not position 0.

The second and third arguments allow xs:double values (rather than requiring xs:integer) in order to achieve compatibility with XPath 1.0.

A surrogate pair counts as one character, not two.

The consequences of supplying values such as NaN or positive or negative infinity for the $start or $length arguments follow from the above rules, and are not always intuitive.

The first character of a string is located at position 1, not position 0.

The second and third arguments allow xs:double values (rather than requiring xs:integer) in order to achieve compatibility with XPath 1.0.

A surrogate pair counts as one character, not two.

The consequences of supplying values such as NaN or positive or negative infinity for the $start or $length arguments follow from the above rules, and are not always intuitive.

Examples
ExpressionResult
substring("motor car", 6)
" car"

(Characters starting at position 6 to the end of $sourceString are selected.)

substring("metadata", 4, 3)
"ada"

(Characters at positions greater than or equal to 4 and less than 7 are selected.)

substring("12345", 1.5, 2.6)
"234"

(Characters at positions greater than or equal to 2 and less than 5 are selected.)

substring("12345", 0, 3)
"12"

(Characters at positions greater than or equal to 0 and less than 3 are selected. Since the first position is 1, these are the characters at positions 1 and 2.)

substring("12345", 5, -3)
""

(Characters at positions greater than or equal to 5 and less than 2 are selected.)

substring("12345", -3, 5)
"1"

(Characters at positions greater than or equal to -3 and less than 2 are selected. Since the first position is 1, this is the character at position 1.)

substring("12345", 0 div 0E0, 3)
""

(Since 0 div 0E0 returns NaN, and NaN compared to any other number returns false, no characters are selected.)

substring("12345", 1, 0 div 0E0)
""

(As above.)

substring((), 1, 3)
""
substring("12345", -42, 1 div 0E0)
"12345"

(Characters at positions greater than or equal to -42 and less than INF are selected.)

substring("12345", -1 div 0E0, 1 div 0E0)
""

(Since the value of -INF + INF is NaN, no characters are selected.)

5.4.7 fn:string-length

Summary

Returns the number of ·characters· in a string.

Signature
fn:string-length(
$valueas xs:string?:= fn:string(.)
) as xs:integer
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

The function returns an xs:integer equal to the length in ·characters· of $value.

Calling the zero-argument version of the function is equivalent to calling fn:string-length(fn:string(.)).

If $value is the empty sequence, the function returns the xs:integer value 0.

Error Conditions

If $value is not specified and the context value is absentDM, a type error is raised: [err:XPDY0002]XP.

As a consequence of the rules given above, a type error is raised [err:XPTY0004]XP if the context value cannot be atomized, or if the result of atomizing the context value is a sequence containing more than one atomic item.

Notes

Unlike some programming languages, a ·codepoint· greater than 65535 counts as one character, not two.

There are situations where fn:string-length() has a different effect from fn:string-length(.). For example, if the context value is an attribute node typed as an xs:integer with the string value 000001, then fn:string-length() returns 6 (the length of the string value of the node), while fn:string-length(.) raises a type error (because the result of atomization is not an xs:string).

Unlike some programming languages, a ·codepoint· greater than 65535 counts as one character, not two.

There are situations where fn:string-length() has a different effect from fn:string-length(.). For example, if the context value is an attribute node typed as an xs:integer with the string value 000001, then fn:string-length() returns 6 (the length of the string value of the node), while fn:string-length(.) raises a type error (because the result of atomization is not an xs:string).

Examples
Expression:
string-length(
  "Harp not on that string, madam; that is past."
)
Result:
45
Expression:
"ᾧ" => string-length()
Result:
1
Expression:
"ᾧ" => normalize-unicode("NFD") => string-length()
Result:
4

(For strings that consist of a base character with combining characters, each combining character is length 1.)

Expression:

string-length(())

Result:
0

5.4.8 fn:normalize-space

Summary

Returns $value with leading and trailing whitespace removed, and sequences of internal whitespace reduced to a single space character.

Signature
fn:normalize-space(
$valueas xs:string?:= fn:string(.)
) 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·.

Rules

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

The function returns a string constructed by stripping leading and trailing whitespace from $value, and replacing sequences of one or more adjacent whitespace characters with a single space, U+0020 (SPACE) .

The whitespace characters are defined in the metasymbol S (Production 3) of [Extensible Markup Language (XML) 1.0 (Fifth Edition)].

If no argument is supplied, then $value defaults to the string value (calculated using fn:string) of the context value (.).

Error Conditions

If no argument is supplied and the context value is absentDM, a type error is raised [err:XPDY0002]XP.

As a consequence of the rules given above, a type error is raised [err:XPTY0004]XP if the context value cannot be atomized, or if the result of atomizing the context value is a sequence containing more than one atomic item.

Notes

The definition of whitespace is unchanged in [Extensible Markup Language (XML) 1.1 Recommendation]. It is repeated here for convenience:

S ::= (#x20 | #x9 | #xD | #xA)+

The definition of whitespace is unchanged in [Extensible Markup Language (XML) 1.1 Recommendation]. It is repeated here for convenience:

S ::= (#x20 | #x9 | #xD | #xA)+

Examples
Expression:
normalize-space(" The    wealthy curled darlings
           of    our    nation. ")
Result:
"The wealthy curled darlings of our nation."
Expression:

normalize-space(())

Result:
""

5.4.10 fn:upper-case

Summary

Converts a string to upper case.

Signature
fn:upper-case(
$valueas xs:string?
) as xs:string
Properties

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

Rules

If $value is the empty sequence, the zero-length string is returned.

Otherwise, the function returns $value after translating every ·character· to its upper-case correspondent as defined in the appropriate case mappings section in the Unicode standard [The Unicode Standard]. For versions of Unicode beginning with the 2.1.8 update, only locale-insensitive case mappings should be applied. Beginning with version 3.2.0 (and likely future versions) of Unicode, precise mappings are described in default case operations, which are full case mappings in the absence of tailoring for particular languages and environments. Every lower-case character that does not have an upper-case correspondent, as well as every upper-case character, is included in the returned value in its original form.

Notes

Case mappings may change the length of a string. In general, the fn:upper-case and fn:lower-case functions are not inverses of each other: fn:lower-case(fn:upper-case($s)) is not guaranteed to return $s, nor is fn:upper-case(fn:lower-case($s)). The character U+0131 (LATIN SMALL LETTER DOTLESS I, ı) (used in Turkish) is perhaps the most prominent lower-case letter which will not round-trip. The character U+0130 (LATIN CAPITAL LETTER I WITH DOT ABOVE, İ) is the most prominent upper-case letter which will not round trip; there are others, such as U+1E9E (LATIN CAPITAL LETTER SHARP S, ) , which was introduced in Unicode 5.1.

These functions may not always be linguistically appropriate (e.g. Turkish i without dot) or appropriate for the application (e.g. titlecase). In cases such as Turkish, a simple translation should be used first.

Because the function is not sensitive to locale, results will not always match user expectations. In Quebec, for example, the standard uppercase equivalent of è is È, while in metropolitan France it is more commonly E; only one of these is supported by the functions as defined.

Many characters of class Ll lack uppercase equivalents in the Unicode case mapping tables; many characters of class Lu lack lowercase equivalents.

Case mappings may change the length of a string. In general, the fn:upper-case and fn:lower-case functions are not inverses of each other: fn:lower-case(fn:upper-case($s)) is not guaranteed to return $s, nor is fn:upper-case(fn:lower-case($s)). The character U+0131 (LATIN SMALL LETTER DOTLESS I, ı) (used in Turkish) is perhaps the most prominent lower-case letter which will not round-trip. The character U+0130 (LATIN CAPITAL LETTER I WITH DOT ABOVE, İ) is the most prominent upper-case letter which will not round trip; there are others, such as U+1E9E (LATIN CAPITAL LETTER SHARP S, ) , which was introduced in Unicode 5.1.

These functions may not always be linguistically appropriate (e.g. Turkish i without dot) or appropriate for the application (e.g. titlecase). In cases such as Turkish, a simple translation should be used first.

Because the function is not sensitive to locale, results will not always match user expectations. In Quebec, for example, the standard uppercase equivalent of è is È, while in metropolitan France it is more commonly E; only one of these is supported by the functions as defined.

Many characters of class Ll lack uppercase equivalents in the Unicode case mapping tables; many characters of class Lu lack lowercase equivalents.

Examples
ExpressionResult
upper-case("abCd0")
"ABCD0"

5.4.11 fn:lower-case

Summary

Converts a string to lower case.

Signature
fn:lower-case(
$valueas xs:string?
) as xs:string
Properties

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

Rules

If t$value is the empty sequence, the zero-length string is returned.

Otherwise, the function returns $value after translating every ·character· to its lower-case correspondent as defined in the appropriate case mappings section in the Unicode standard [The Unicode Standard]. For versions of Unicode beginning with the 2.1.8 update, only locale-insensitive case mappings should be applied. Beginning with version 3.2.0 (and likely future versions) of Unicode, precise mappings are described in default case operations, which are full case mappings in the absence of tailoring for particular languages and environments. Every upper-case character that does not have a lower-case correspondent, as well as every lower-case character, is included in the returned value in its original form.

Notes

Case mappings may change the length of a string. In general, the fn:upper-case and fn:lower-case functions are not inverses of each other: fn:lower-case(fn:upper-case($s)) is not guaranteed to return $s, nor is fn:upper-case(fn:lower-case($s)). The character U+0131 (LATIN SMALL LETTER DOTLESS I, ı) (used in Turkish) is perhaps the most prominent lower-case letter which will not round-trip. The character U+0130 (LATIN CAPITAL LETTER I WITH DOT ABOVE, İ) is the most prominent upper-case letter which will not round trip; there are others, such as U+1E9E (LATIN CAPITAL LETTER SHARP S, ) , which was introduced in Unicode 5.1.

These functions may not always be linguistically appropriate (e.g. Turkish i without dot) or appropriate for the application (e.g. titlecase). In cases such as Turkish, a simple translation should be used first.

Because the function is not sensitive to locale, results will not always match user expectations. In Quebec, for example, the standard uppercase equivalent of è is È, while in metropolitan France it is more commonly E; only one of these is supported by the functions as defined.

Many characters of class Ll lack uppercase equivalents in the Unicode case mapping tables; many characters of class Lu lack lowercase equivalents.

Case mappings may change the length of a string. In general, the fn:upper-case and fn:lower-case functions are not inverses of each other: fn:lower-case(fn:upper-case($s)) is not guaranteed to return $s, nor is fn:upper-case(fn:lower-case($s)). The character U+0131 (LATIN SMALL LETTER DOTLESS I, ı) (used in Turkish) is perhaps the most prominent lower-case letter which will not round-trip. The character U+0130 (LATIN CAPITAL LETTER I WITH DOT ABOVE, İ) is the most prominent upper-case letter which will not round trip; there are others, such as U+1E9E (LATIN CAPITAL LETTER SHARP S, ) , which was introduced in Unicode 5.1.

These functions may not always be linguistically appropriate (e.g. Turkish i without dot) or appropriate for the application (e.g. titlecase). In cases such as Turkish, a simple translation should be used first.

Because the function is not sensitive to locale, results will not always match user expectations. In Quebec, for example, the standard uppercase equivalent of è is È, while in metropolitan France it is more commonly E; only one of these is supported by the functions as defined.

Many characters of class Ll lack uppercase equivalents in the Unicode case mapping tables; many characters of class Lu lack lowercase equivalents.

Examples
ExpressionResult
lower-case("ABc!D")
"abc!d"

5.4.12 fn:translate

Summary

Returns $value modified by replacing or removing individual characters.

Signature
fn:translate(
$valueas xs:string?,
$replaceas xs:string,
$withas xs:string
) as xs:string
Properties

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

Rules

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

Otherwise, the function returns a result string constructed by processing each ·character· in $value, in order, according to the following rules:

  1. If the character does not appear in $replace then it is added to the result string unchanged.

  2. If the character first appears in $replace at some position M, where the value of $with is M or more characters in length, then the character at position M in $with is added to the result string.

  3. If the character first appears in $replace at some position M, where $with is less than M characters in length, then the character is omitted from the result string.

Notes

If $replace is the zero-length string then the function returns $value unchanged.

If a character occurs more than once in $replace, then the first occurrence determines the action taken.

If $with is longer than $replace, the excess characters are ignored.

If $replace is the zero-length string then the function returns $value unchanged.

If a character occurs more than once in $replace, then the first occurrence determines the action taken.

If $with is longer than $replace, the excess characters are ignored.

Examples
ExpressionResult
translate("bar", "abc", "ABC")
"BAr"
translate("--aaa--", "abc-", "ABC")
"AAA"
translate("abcdabc", "abc", "AB")
"ABdAB"

5.4.13 fn:hash

Changes in 4.0  

  1. New in 4.0  [Issues 779 1188 1422 1426 PRs 937 995 1190 23 January 2024]

Summary

Returns the results of a specified hash, checksum, or cyclic redundancy check function applied to the input.

Signature
fn:hash(
$valueas (xs:string | xs:hexBinary | xs:base64Binary)?,
$algorithmas xs:string?:= "MD5",
$optionsas map(*)?:= {}
) as xs:hexBinary?
Properties

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

Rules

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

If $value is an instance of xs:string, it is converted to a sequence of octets on the basis of UTF-8 encoding. If $value is an instance of xs:base64Binary or xs:hexBinary, it is converted to a sequence of octets.

The $algorithm argument, if present, determines the algorithm to be used to calculate a checksum, hash, or cyclic redundancy check. If empty or absent, MD5 will be used. The effective value of the algorithm is determined by passing the value through fn:upper-case(fn:normalize-space()).

Conforming implementations must support the following options and the functions referred to by them:

  • MD5: the MD5 Message-Digest algorithm, defined by [RFC 6151] (update to [RFC 1321]).

  • SHA-1: the SHA-1 algorithm, defined by [FIPS 180-4].

  • SHA-256: the SHA-256 algorithm, defined by [FIPS 180-4].

  • BLAKE3: the BLAKE3 algorithm defined by [BLAKE3 Hashing].

  • CRC-32: the CRC-32 algorithm, defined by [IEEE 802-3]. It delivers a 32 bit unsigned integer, which this function returns as a 4-octet xs:hexBinary value representing this integer in big-endian order (that is, most significant byte first).

    Note:

    Some libraries, notably System.IO.Hashing.Crc32 in .NET, return the result in little-endian order.

Conforming implementations may support other checksum and hash functions with implementation-defined semantics. The $options argument, if present, defines additional parameters controlling how the process is conducted.

The function returns as xs:hexBinary the octets returned by passing $value as an octet sequence through the selected algorithm. The process is followed even if the input octet sequence is empty.

Error Conditions

A dynamic error is raised [err:FOHA0001] if the effective value of the option algorithm is not one of the values supported by the implementation.

Notes

It is common for secure algorithms to be cryptographically broken, as has happened to the algorithms MD5, SHA-1, and SHA-256. And the CRC-32 algorithm is not intended for cryptographic purposes. Developers are responsible for ensuring that the algorithm chosen meets any expected security protocols, if relevant.

The BLAKE3 algorithm is included in the list of hashing algorithms because at the time of writing it appears to be a promising candidate as a secure and fast algorithm that shows signs of gaining widespread support. However, this is a fast moving field and the community group recognizes that this decision might eventually not stand the test of time. As the technology evolves in the future, implementations are free to drop support for this algorithm and substitute another that appears to better meet requirements.

Additional security practices, such as salting, may be applied as a preprocessing step, or fn:hash() can be incorporated into more complex functions.

In most cases, the xs:hexBinary output of the function will be sought in string form. Because of serialization rules, casting to a string renders the hash in uppercase, and rendering in lowercase (as adopted by [RFC 1321] and [FIPS 180-4]) requires further adjustment.

It is common for secure algorithms to be cryptographically broken, as has happened to the algorithms MD5, SHA-1, and SHA-256. And the CRC-32 algorithm is not intended for cryptographic purposes. Developers are responsible for ensuring that the algorithm chosen meets any expected security protocols, if relevant.

The BLAKE3 algorithm is included in the list of hashing algorithms because at the time of writing it appears to be a promising candidate as a secure and fast algorithm that shows signs of gaining widespread support. However, this is a fast moving field and the community group recognizes that this decision might eventually not stand the test of time. As the technology evolves in the future, implementations are free to drop support for this algorithm and substitute another that appears to better meet requirements.

Additional security practices, such as salting, may be applied as a preprocessing step, or fn:hash() can be incorporated into more complex functions.

In most cases, the xs:hexBinary output of the function will be sought in string form. Because of serialization rules, casting to a string renders the hash in uppercase, and rendering in lowercase (as adopted by [RFC 1321] and [FIPS 180-4]) requires further adjustment.

Examples
Variables
let $doc := <doc>abc</doc>
let $salt := "D;%yL9TS:5PalS/d"
Expression:
hash("abc")
Result:
xs:hexBinary("900150983CD24FB0D6963F7D28E17F72")
Expression:
hash("ABC")
Result:
xs:hexBinary("902FBDD2B1DF0C4F70B4A5D23525E932")
Expression:
hash("")
Result:
xs:hexBinary("D41D8CD98F00B204E9800998ECF8427E")
Expression:
hash("ABC", "SHA-1")
Result:
xs:hexBinary("3C01BDBB26F358BAB27F267924AA2C9A03FCFDB8")
Expression:
hash("ABC", "BLAKE3") 
=> string() => lower-case()
Result:
"d1717274597cf0289694f75d96d444b992a096f1afd8e7bbfa6ebb1d360fedfc"
Expression:
hash("ABC", "BLAKE3") 
=> xs:base64Binary() => string()
Result:
"0XFydFl88CiWlPddltREuZKglvGv2Oe7+m67HTYP7fw="
Expression:
hash("ABC", "sha-256")
=> string()
Result:
"B5D4045C3F466FA91FE2CC6ABE79232A1A57CDF104F7A26E716E0A1E2789DF78"
Expression:
hash("ABC", "sha-256")
Result:
xs:hexBinary("B5D4045C3F466FA91FE2CC6ABE79232A1A57CDF104F7A26E716E0A1E2789DF78")
Expression:
hash($doc)
Result:
xs:hexBinary("900150983CD24FB0D6963F7D28E17F72")
Expression:
hash(serialize($doc), "sha-1") 
=> xs:base64Binary()   
=> string()
Result:
"8PzN28NtxQv5RlxQ5/w6DcnrpEU="
Expression:
hash("password123" || $salt, "SHA-256")
Result:
xs:hexBinary("9C9B913EB1B6254F4737CE947EFD16F16E916F9D6EE5C1102A2002E48D4C88BD")
Expression:
hash("", "CRC-32")
Result:
xs:hexBinary("00000000")
Expression:
hash("input", "CRC-32")
Result:
xs:hexBinary("D82832D7")
Expression:

hash("password123", "sha-unknown")

Result:

Raises error FOHA0001.

5.6 String functions that use regular expressions

The four functions described in this section make use of a regular expression syntax for pattern matching, described below.

FunctionMeaning
fn:matchesReturns true if the supplied string matches a given regular expression.
fn:replaceReturns a string produced from the input string by replacing any substrings that match a given regular expression with a supplied replacement string, provided either literally, or by invoking a supplied function.
fn:tokenizeReturns a sequence of strings constructed by splitting the input wherever a separator is found; the separator is any substring that matches a given regular expression.
fn:analyze-stringAnalyzes a string using a regular expression, returning an XML structure that identifies which parts of the input string matched or failed to match the regular expression, and in the case of matched substrings, which substrings matched each capturing group in the regular expression.

5.6.3 fn:matches

Summary

Returns true if the supplied string matches a given regular expression.

Signature
fn:matches(
$valueas xs:string?,
$patternas xs:string,
$flagsas xs:string?:= ""
) as xs:boolean
Properties

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

Rules

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

If the $flags argument is omitted or if it is an empty sequence, the effect is the same as setting $flags to a zero-length string. Flags are defined in 5.6.2 Flags.

The function returns true if $value or some substring of $value matches the regular expression supplied as $pattern, and the associated $flags. Otherwise, the function returns false.

Error Conditions

A dynamic error is raised [err:FORX0002] if $pattern is invalid according to the rules described in 5.6.1 Regular expression syntax.

A dynamic error is raised [err:FORX0001] if $flags is invalid according to the rules described in 5.6.2 Flags.

Notes

Unless the metacharacters ^ and $ are used as anchors, the string is considered to match the pattern if any substring matches the pattern. But if anchors are used, the anchors must match the start/end of the string (in string mode), or the start/end of a line (in multi-line mode).

This is different from the behavior of patterns in [XML Schema Part 2: Datatypes Second Edition], where regular expressions are implicitly anchored.

Regular expression matching is defined on the basis of Unicode codepoints; it takes no account of collations.

Unless the metacharacters ^ and $ are used as anchors, the string is considered to match the pattern if any substring matches the pattern. But if anchors are used, the anchors must match the start/end of the string (in string mode), or the start/end of a line (in multi-line mode).

This is different from the behavior of patterns in [XML Schema Part 2: Datatypes Second Edition], where regular expressions are implicitly anchored.

Regular expression matching is defined on the basis of Unicode codepoints; it takes no account of collations.

Examples
Variables
let $poem := <poem author="Wilhelm Busch">
Kaum hat dies der Hahn gesehen,
Fängt er auch schon an zu krähen:
Kikeriki! Kikikerikih!!
Tak, tak, tak! - da kommen sie.
</poem>
ExpressionResult
matches("abracadabra", "bra")
true()
matches("abracadabra", "^a.*a$")
true()
matches("abracadabra", "^bra")
false()

Given the source document:

the following function calls produce the following results, with the poem element as the context node:

matches($poem, "Kaum.*krähen")
false()
matches($poem, "Kaum.*krähen", "s")
true()
matches($poem, "^Kaum.*gesehen,$", "m")
true()
matches($poem, "^Kaum.*gesehen,$")
false()
matches($poem, "kiki", "i")
true()

5.6.4 fn:replace

Changes in 4.0  

  1. The $action argument is new in 4.0.  [  18 July 2023]

Summary

Returns a string produced from the input string by replacing any substrings that match a given regular expression with a supplied replacement string, provided either literally, or by invoking a supplied function.

Signature
fn:replace(
$valueas xs:string?,
$patternas xs:string,
$replacementas xs:string?:= (),
$flagsas xs:string?:= '',
$actionas (fn(xs:untypedAtomic, xs:untypedAtomic*) as item()?)?:= ()
) as xs:string
Properties

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

Rules

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

The replacement string is determined by the values of the $replacement and/or $action arguments:

  • If the $action argument is present and is not an empty sequence, the string is obtained by calling the $action function.

    The first argument to the $action function is the string to be replaced, provided as xs:untypedAtomic.

    The second argument to the $action function provides the captured substrings as an xs:untypedAtomic sequence. The Nth item in this sequence is the substring captured by the Nth parenthesized sub-expression. If the Nth parenthesized sub-expression was not matched, the Nth item will be the zero-length string.

    Note that the rules for function coercion mean that the function actually supplied for the $action parameter may be an arity-1 function: the second argument does not need to be declared if it is not used.

    The replacement string is obtained by invoking fn:string for the result of the function call.

  • Otherwise, if the $replacement argument is present and is not an empty sequence, the replacement string is the value of $replacement.

  • Otherwise, the replacement string is the zero-length string.

If the $flags argument is omitted or if it is an empty sequence, the effect is the same as setting $flags to a zero-length string. Flags are defined in 5.6.2 Flags.

The function returns the xs:string that is obtained by replacing each non-overlapping substring of $value that matches the given $pattern with a replacement string.

If two overlapping substrings of $value both match the $pattern, then only the first one (that is, the one whose first ·character· comes first in the $value string) is replaced.

If the q flag is present, or if the replacement string was obtained by calling the $action function, then the replacement string is used as is.

Otherwise, within the replacement string, a variable $N may be used to refer to the substring captured by the Nth parenthesized sub-expression in the regular expression. For each match of the pattern, these variables are assigned the value of the content matched by the relevant sub-expression, and the modified replacement string is then substituted for the ·characters· in $value that matched the pattern. $0 refers to the substring captured by the regular expression as a whole.

More specifically, the rules are as follows, where S is the number of parenthesized sub-expressions in the regular expression, and N is the decimal number formed by taking all the digits that consecutively follow the $ character:

  1. If N=0, then the variable is replaced by the substring matched by the regular expression as a whole.

  2. If 1<=N<=S, then the variable is replaced by the substring captured by the Nth parenthesized sub-expression. If the Nth parenthesized sub-expression was not matched, then the variable is replaced by the zero-length string.

  3. If S<N<=9, then the variable is replaced by the zero-length string.

  4. Otherwise (if N>S and N>9), the last digit of N is taken to be a literal character to be included “as is” in the replacement string, and the rules are reapplied using the number N formed by stripping off this last digit.

For example, if the replacement string is "$23" and there are 5 substrings, the result contains the value of the substring that matches the second sub-expression, followed by the digit 3.

Unless the q flag is used, a literal $ character within the replacement string must be written as \$, and a literal \ character must be written as \\.

If two alternatives within the pattern both match at the same position in the $input, then the match that is chosen is the one matched by the first alternative. For example:

 replace("abcd", "(ab)|(a)", "[1=$1][2=$2]") returns "[1=ab][2=]cd"
Error Conditions

A dynamic error is raised [err:FORX0002] if the value of $pattern is invalid according to the rules described in section 5.6.1 Regular expression syntax.

A dynamic error is raised [err:FORX0001] if the value of $flags is invalid according to the rules described in section 5.6.2 Flags.

A dynamic error is raised [err:FORX0003] if the pattern matches a zero-length string, that is, if the expression fn:matches("", $pattern, $flags) returns true. It is not an error, however, if a captured substring is zero-length.

In the absence of the q flag, a dynamic error is raised [err:FORX0004] if the value of $replacement contains a dollar sign ($) character that is not immediately followed by a digit 0-9 and not immediately preceded by a backslash (\).

In the absence of the q flag, a dynamic error is raised [err:FORX0004] if the value of $replacement contains a backslash (\) character that is not part of a \\ pair, unless it is immediately followed by a dollar sign ($) character.

A dynamic error is raised [err:FORX0005] if both the $replacement and $action arguments are supplied, and neither is an empty sequence.

Notes

If the input string contains no substring that matches the regular expression, the result of the function is a single string identical to the input string.

If the input string contains no substring that matches the regular expression, the result of the function is a single string identical to the input string.

Examples
Expression:

replace("abracadabra", "bra", "*")

Result:
"a*cada*"
Expression:

replace("abracadabra", "a.*a", "*")

Result:
"*"
Expression:

replace("abracadabra", "a.*?a", "*")

Result:
"*c*bra"
Expression:

replace("abracadabra", "a", "")

Result:
"brcdbr"
Expression:

replace("abracadabra", "a(.)", "a$1$1")

Result:
"abbraccaddabbra"
Expression:

replace("AAAA", "A+", "b")

Result:
"b"
Expression:

replace("AAAA", "A+?", "b")

Result:
"bbbb"
Expression:

replace("darted", "^(.*?)d(.*)$", "$1c$2")

Result:
"carted"

(The first d is replaced.)

Expression:
replace("abracadabra", "bra", action := fn { "*" })
Result:
"a*cada*"
Expression:
replace(
  "abracadabra",
  "bra",
  action := upper-case#1
)
Result:
"aBRAcadaBRA"
Expression:
replace("Chapter 9", "[0-9]+", action := fn { . + 1 })
Result:
"Chapter 10"
Expression:
replace(
  "LHR to LAX",
  "[A-Z]{3}",
  action := { 'LAX': 'Los Angeles', 'LHR': 'London' }
)
Result:
"London to Los Angeles"
Expression:
replace(
  "57°43′30″",
  "([0-9]+)°([0-9]+)′([0-9]+)″",
  action := fn($s, $groups) {
    string($groups[1] + $groups[2] ÷ 60 + $groups[3] ÷ 3600) || '°'
  }
)
Result:
"57.725°"

The expression fn:replace("abracadabra", ".*?", "$1") raises an error, because the pattern matches the zero-length string

5.6.5 fn:tokenize

Changes in 4.0  

  1. The second argument can now be an empty sequence.  [Issue 895 PR 901 16 December 2023]

Summary

Returns a sequence of strings constructed by splitting the input wherever a separator is found; the separator is any substring that matches a given regular expression.

Signature
fn:tokenize(
$valueas xs:string?,
$patternas xs:string?:= (),
$flagsas xs:string?:= ""
) as xs:string*
Properties

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

Rules

The following rules apply when the $pattern argument is omitted, or is set to an empty sequence:

  • The function splits the supplied string at whitespace boundaries.

  • More specifically, calling fn:tokenize($value)or fn:tokenize($value, ()) is equivalent to calling fn:tokenize(fn:normalize-space($value), ' ')) where the second argument is a single space character (x20).

  • The $flags argument is ignored.

The following rules apply when the $pattern argument is supplied as a single string:

  • If the $flags argument is omitted or if it is an empty sequence, the effect is the same as setting $flags to a zero-length string. Flags are defined in 5.6.2 Flags.

  • If $value is the empty sequence, or if $value is the zero-length string, the function returns the empty sequence.

  • The function returns a sequence of strings formed by breaking the $value string into a sequence of strings, treating any substring that matches $pattern as a separator. The separators themselves are not returned.

  • If a separator occurs at the start of the $value string, the result sequence will start with a zero-length string. Similarly, zero-length strings will also occur in the result sequence if a separator occurs at the end of the $value string, or if two adjacent substrings match the supplied $pattern.

  • If two alternatives within the supplied $pattern both match at the same position in the $value string, then the match that is chosen is the first. For example:

     tokenize("abracadabra", "(ab)|(a)") returns ("", "r", "c", "d", "r", "")
Error Conditions

A dynamic error is raised [err:FORX0002] if the value of $pattern is invalid according to the rules described in section 5.6.1 Regular expression syntax.

A dynamic error is raised [err:FORX0001] if the value of $flags is invalid according to the rules described in section 5.6.2 Flags.

A dynamic error is raised [err:FORX0003] if the supplied $pattern matches a zero-length string, that is, if fn:matches("", $pattern, $flags) returns true.

Notes

If the input string is not zero length, and no separators are found in the input string, the result of the function is a single string identical to the input string.

The one-argument form of the function has a similar effect to the two-argument form with \s+ as the separator pattern, except that the one-argument form strips leading and trailing whitespace, whereas the two-argument form delivers an extra zero-length token if leading or trailing whitespace is present.

The function returns no information about the separators that were found in the string. If this information is required, the fn:analyze-string function can be used instead.

The separator used by the one-argument form of the function is any sequence of tab (U+0009 (TAB) ), newline (U+000A (NEWLINE) ), carriage return (U+000D (CARRIAGE RETURN) ) or space (U+0020 (SPACE) ) characters. This is the same as the separator recognized by list-valued attributes as defined in XSD. It is not the same as the separator recognized by list-valued attributes in HTML5, which also treats form-feed (U+000C (FORM FEED) ) as whitespace. If it is necessary to treat form-feed as a separator, an explicit separator pattern should be used.

If the input string is not zero length, and no separators are found in the input string, the result of the function is a single string identical to the input string.

The one-argument form of the function has a similar effect to the two-argument form with \s+ as the separator pattern, except that the one-argument form strips leading and trailing whitespace, whereas the two-argument form delivers an extra zero-length token if leading or trailing whitespace is present.

The function returns no information about the separators that were found in the string. If this information is required, the fn:analyze-string function can be used instead.

The separator used by the one-argument form of the function is any sequence of tab (U+0009 (TAB) ), newline (U+000A (NEWLINE) ), carriage return (U+000D (CARRIAGE RETURN) ) or space (U+0020 (SPACE) ) characters. This is the same as the separator recognized by list-valued attributes as defined in XSD. It is not the same as the separator recognized by list-valued attributes in HTML5, which also treats form-feed (U+000C (FORM FEED) ) as whitespace. If it is necessary to treat form-feed as a separator, an explicit separator pattern should be used.

Examples
Expression:

tokenize(" red green blue ")

Result:
"red", "green", "blue"
Expression:

tokenize("The cat sat on the mat", "\s+")

Result:
"The", "cat", "sat", "on", "the", "mat"
Expression:

tokenize(" red green blue ", "\s+")

Result:
"", "red", "green", "blue", ""
Expression:

tokenize("1, 15, 24, 50", ",\s*")

Result:
"1", "15", "24", "50"
Expression:

tokenize("1,15,,24,50,", ",")

Result:
"1", "15", "", "24", "50", ""

fn:tokenize("abba", ".?") raises the dynamic error [err:FORX0003].

Expression:
tokenize(
  "Some unparsed <br> HTML <BR> text",
  "\s*<br>\s*", "i"
)
Result:
"Some unparsed", "HTML", "text"

5.6.6 fn:analyze-string

Summary

Analyzes a string using a regular expression, returning an XML structure that identifies which parts of the input string matched or failed to match the regular expression, and in the case of matched substrings, which substrings matched each capturing group in the regular expression.

Signature
fn:analyze-string(
$valueas xs:string?,
$patternas xs:string,
$flagsas xs:string?:= ""
) as element(fn:analyze-string-result)
Properties

This function is ·nondeterministic·, ·context-independent·, and ·focus-independent·.

Rules

If the $flags argument is omitted or if it is an empty sequence, the effect is the same as setting $flags to a zero-length string. Flags are defined in 5.6.2 Flags.

If $value is the empty sequence the function behaves as if $value were the zero-length string. In this situation the result will be an element node with no children.

The function returns an element node whose local name is analyze-string-result. This element and all its descendant elements have the namespace URI http://www.w3.org/2005/xpath-functions. The namespace prefix is ·implementation-dependent·. The children of this element are a sequence of fn:match and fn:non-match elements. This sequence is formed by breaking the $value string into a sequence of strings, returning any substring that matches $pattern as the content of an fn:match element, and any intervening substring as the content of an fn:non-match element.

More specifically, the function starts at the beginning of the input string and attempts to find the first substring that matches the regular expression. If there are several matches, the first match is defined to be the one whose starting position comes first in the string. If several alternatives within the regular expression both match at the same position in the input string, then the match that is chosen is the first alternative that matches. For example, if the input string is The quick brown fox jumps and the regular expression is jump|jumps, then the match that is chosen is jump.

Having found the first match, the instruction proceeds to find the second and subsequent matches by repeating the search, starting at the first ·character· that was not included in the previous match.

The input string is thus partitioned into a sequence of substrings, some of which match the regular expression, others which do not match it. Each substring will contain at least one character. This sequence is represented in the result by the sequence of fn:match and fn:non-match children of the returned element node; the string value of the fn:match or fn:non-match element will be the corresponding substring of $input, and the string value of the returned element node will therefore be the same as $input.

The content of an fn:non-match element is always a single text node.

The content of a fn:match element, however, is in general a sequence of text nodes and fn:group element children. An fn:group element with a nr attribute having the integer value N identifies the substring captured by the Nth parenthesized sub-expression in the regular expression. For each capturing subexpression there will be at most one corresponding fn:group element in each fn:match element in the result.

If the function is called twice with the same arguments, it is ·implementation-dependent· whether the two calls return the same element node or distinct (but deep equal) element nodes. In this respect it is ·nondeterministic with respect to node identity·.

The base URI of the element nodes in the result is ·implementation-dependent·.

A schema is defined for the structure of the returned element: see C.1 Schema for the result of fn:analyze-string.

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.

Error Conditions

A dynamic error is raised [err:FORX0002] if the value of $pattern is invalid according to the rules described in section 5.6.1 Regular expression syntax.

A dynamic error is raised [err:FORX0001] if the value of $flags is invalid according to the rules described in section 5.6.2 Flags.

A dynamic error is raised [err:FORX0003] if the supplied $pattern matches a zero-length string, that is, if fn:matches("", $pattern, $flags) returns true.

Notes

It is recommended that a processor that implements schema awareness should return typed nodes. The concept of “schema awareness”, however, is a matter for host languages to define and is outside the scope of the function library specification.

The declarations and definitions in the schema are not automatically available in the static context of the fn:analyze-string call (or of any other expression). The contents of the static context are host-language defined, and in some host languages are implementation-defined.

The schema defines the outermost element, analyze-string-result, in such a way that mixed content is permitted. In fact the element will only have element nodes (match and non-match) as its children, never text nodes. Although this might have originally been an oversight, defining the analyze-string-result element with mixed="true" allows it to be atomized, which is potentially useful (the atomized value will be the original input string), and the capability has therefore been retained for compatibility with the 3.0 version of this specification.

It is recommended that a processor that implements schema awareness should return typed nodes. The concept of “schema awareness”, however, is a matter for host languages to define and is outside the scope of the function library specification.

The declarations and definitions in the schema are not automatically available in the static context of the fn:analyze-string call (or of any other expression). The contents of the static context are host-language defined, and in some host languages are implementation-defined.

The schema defines the outermost element, analyze-string-result, in such a way that mixed content is permitted. In fact the element will only have element nodes (match and non-match) as its children, never text nodes. Although this might have originally been an oversight, defining the analyze-string-result element with mixed="true" allows it to be atomized, which is potentially useful (the atomized value will be the original input string), and the capability has therefore been retained for compatibility with the 3.0 version of this specification.

Examples

In the following examples, the result document is shown in serialized form, with whitespace between the element nodes. This whitespace is not actually present in the result.

Expression:

analyze-string("The cat sat on the mat.", "\w+")

Result:
<analyze-string-result xmlns="http://www.w3.org/2005/xpath-functions">
  <match>The</match>
  <non-match> </non-match>
  <match>cat</match>
  <non-match> </non-match>
  <match>sat</match>
  <non-match> </non-match>
  <match>on</match>
  <non-match> </non-match>
  <match>the</match>
  <non-match> </non-match>
  <match>mat</match>
  <non-match>.</non-match>
</analyze-string-result>

(with whitespace added for legibility)

Expression:
analyze-string("08-12-03", "^(\d+)\-(\d+)\-(\d+)$")
Result:
<analyze-string-result xmlns="http://www.w3.org/2005/xpath-functions">
  <match>
    <group nr="1">08</group>-<group nr="2">12</group>-<group nr="3">03</group>
  </match>
</analyze-string-result>

(with whitespace added for legibility)

Expression:
analyze-string("A1,C15,,D24, X50,", "([A-Z])([0-9]+)")
Result:
<analyze-string-result xmlns="http://www.w3.org/2005/xpath-functions">
  <match>
    <group nr="1">A</group>
    <group nr="2">1</group>
  </match>
  <non-match>,</non-match>
  <match>
    <group nr="1">C</group>
    <group nr="2">15</group>
  </match>
  <non-match>,,</non-match>
  <match>
    <group nr="1">D</group>
    <group nr="2">24</group>
  </match>
  <non-match>, </non-match>
  <match>
    <group nr="1">X</group>
    <group nr="2">50</group>
  </match>
  <non-match>,</non-match>
</analyze-string-result>

(with whitespace added for legibility)

6 Functions that manipulate URIs

This section specifies functions that manipulate URI values, either as instances of xs:anyURI or as strings.

FunctionMeaning
fn:resolve-uriResolves a relative IRI reference against an absolute IRI.
fn:encode-for-uriEncodes reserved characters in a string that is intended to be used in the path segment of a URI.
fn:decode-from-uriDecodes URI-escaped characters in a string.
fn:iri-to-uriConverts a string containing an IRI into a URI according to the rules of [RFC 3987].
fn:escape-html-uriEscapes a URI in the same way that HTML user agents handle attribute values expected to contain URIs.

6.1 fn:resolve-uri

Changes in 4.0  

  1. The optional second argument can now be supplied as an empty sequence.  [Issue 895 PR 901 16 December 2023]

Summary

Resolves a relative IRI reference against an absolute IRI.

Signature
fn:resolve-uri(
$hrefas xs:string?,
$baseas xs:string?:= ()
) as xs:anyURI?
Properties

This function is ·deterministic·, ·context-dependent·, and ·focus-independent·. It depends on static base URI.

Rules

The function is defined to operate on IRI references as defined in [RFC 3987], and the implementation must permit all arguments that are valid according to that specification. In addition, the implementation may accept some or all strings that conform to the rules for (absolute or relative) Legacy Extended IRI references as defined in [Legacy extended IRIs for XML resource identification]. For the purposes of this section, the terms IRI and IRI reference include these extensions, insofar as the implementation chooses to support them.

The following rules apply in order:

  1. If $href is the empty sequence, the function returns the empty sequence.

  2. If $href is an absolute IRI (as defined above), then it is returned unchanged.

  3. If the $base argument is not supplied, or is supplied as an empty sequence then:

    1. If the static base URI in the static context is not absent, it is used as the effective value of $base.

    2. Otherwise, a dynamic error is raised: [err:FONS0005].

  4. The function resolves the relative IRI reference $href against the base IRI $base using the algorithm defined in [RFC 3986], adapted by treating any ·character· that would not be valid in an RFC3986 URI or relative reference in the same way that RFC3986 treats unreserved characters. No percent-encoding takes place.

Error Conditions

The first form of this function resolves $href against the value of the base-uri property from the static context. A dynamic error is raised [err:FONS0005] if the base-uri property is not initialized in the static context.

A dynamic error is raised [err:FORG0002] if $href is not a valid IRI according to the rules of RFC3987, extended with an implementation-defined subset of the extensions permitted in LEIRI, or if it is not a suitable relative reference to use as input to the RFC3986 resolution algorithm extended to handle additional unreserved characters.

A dynamic error is raised [err:FORG0002] if $base is not a valid IRI according to the rules of RFC3987, extended with an implementation-defined subset of the extensions permitted in LEIRI, or if it is not a suitable IRI to use as input to the chosen resolution algorithm (for example, if it is a relative IRI reference or if it is a non-hierarchic URI). In XPath 4.0, attempting to resolve against an absolute URI that includes a fragment identifier is no longer an error, the fragment identifier is simply ignored. A narrow reading of RFC 3986 might seem to forbid this, but in practice the interpretation is non-controversial and the practice is widely supported.

A dynamic error is raised [err:FORG0009] if the chosen resolution algorithm fails for any other reason.

Notes

Resolving a URI does not dereference it. This is merely a syntactic operation on two ·strings·.

The algorithms in the cited RFCs include some variations that are optional or recommended rather than mandatory; they also describe some common practices that are not recommended, but which are permitted for backwards compatibility. Where the cited RFCs permit variations in behavior, so does this specification.

Throughout this family of specifications, the phrase "resolving a relative URI (or IRI) reference" should be understood as using the rules of this function, unless otherwise stated.

RFC3986 defines an algorithm for resolving relative references in the context of the URI syntax defined in that RFC. RFC3987 describes a modification to that algorithm to make it applicable to IRIs (specifically: additional characters permitted in an IRI are handled the same way that RFC3986 handles unreserved characters). The LEIRI specification does not explicitly define a resolution algorithm, but suggests that it should not be done by converting the LEIRI to a URI, and should not involve percent-encoding. This specification fills this gap by defining resolution for LEIRIs in the same way that RFC3987 defines resolution for IRIs, that is by specifying that additional characters are handled as unreserved characters.

Resolving a URI does not dereference it. This is merely a syntactic operation on two ·strings·.

The algorithms in the cited RFCs include some variations that are optional or recommended rather than mandatory; they also describe some common practices that are not recommended, but which are permitted for backwards compatibility. Where the cited RFCs permit variations in behavior, so does this specification.

Throughout this family of specifications, the phrase "resolving a relative URI (or IRI) reference" should be understood as using the rules of this function, unless otherwise stated.

RFC3986 defines an algorithm for resolving relative references in the context of the URI syntax defined in that RFC. RFC3987 describes a modification to that algorithm to make it applicable to IRIs (specifically: additional characters permitted in an IRI are handled the same way that RFC3986 handles unreserved characters). The LEIRI specification does not explicitly define a resolution algorithm, but suggests that it should not be done by converting the LEIRI to a URI, and should not involve percent-encoding. This specification fills this gap by defining resolution for LEIRIs in the same way that RFC3987 defines resolution for IRIs, that is by specifying that additional characters are handled as unreserved characters.

6.2 fn:encode-for-uri

Summary

Encodes reserved characters in a string that is intended to be used in the path segment of a URI.

Signature
fn:encode-for-uri(
$valueas xs:string?
) as xs:string
Properties

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

Rules

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

This function applies the URI escaping rules defined in section 2 of [RFC 3986] to the xs:string supplied as $value. The effect of the function is to escape reserved characters. Each such character in the string is replaced with its percent-encoded form as described in [RFC 3986].

Since [RFC 3986] recommends that, for consistency, URI producers and normalizers should use uppercase hexadecimal digits for all percent-encodings, this function must always generate hexadecimal values using the upper-case letters A-F.

Notes

All characters are escaped except those identified as “unreserved” by [RFC 3986], that is the upper- and lower-case letters A to Z, the digits 0 to 9, HYPHEN-MINUS (-), LOW LINE (_), FULL STOP (.), and TILDE (~).

This function escapes URI delimiters and therefore cannot be used indiscriminately to encode “invalid” characters in a path segment.

This function is invertible but not idempotent. This is because a string containing a percent character will be modified by applying the function: for example 100% becomes 100%25, while 100%25 becomes 100%2525.

All characters are escaped except those identified as “unreserved” by [RFC 3986], that is the upper- and lower-case letters A to Z, the digits 0 to 9, HYPHEN-MINUS (-), LOW LINE (_), FULL STOP (.), and TILDE (~).

This function escapes URI delimiters and therefore cannot be used indiscriminately to encode “invalid” characters in a path segment.

This function is invertible but not idempotent. This is because a string containing a percent character will be modified by applying the function: for example 100% becomes 100%25, while 100%25 becomes 100%2525.

Examples
Expression:
encode-for-uri(
  "http://example.com/00/Weather/CA/Los%20Angeles#ocean"
)
Result:
"http%3A%2F%2Fexample.com%2F00%2FWeather%2FCA%2FLos%2520Angeles%23ocean"

(This is probably not what the user intended because all of the delimiters have been encoded.)

Expression:
concat(
  "http://example.com/",
  encode-for-uri("~bébé")
)
Result:
"http://example.com/~b%C3%A9b%C3%A9"
Expression:
concat(
  "http://example.com/",
  encode-for-uri("100% organic")
)
Result:
"http://example.com/100%25%20organic"

6.4 fn:iri-to-uri

Summary

Converts a string containing an IRI into a URI according to the rules of [RFC 3987].

Signature
fn:iri-to-uri(
$valueas xs:string?
) as xs:string
Properties

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

Rules

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

Otherwise, the function converts $value into a URI according to the rules given in Section 3.1 of [RFC 3987] by percent-encoding characters that are allowed in an IRI but not in a URI. If $value contains a character that is invalid in an IRI, such as the space character (see note below), the invalid character is replaced by its percent-encoded form as described in [RFC 3986] before the conversion is performed.

Since [RFC 3986] recommends that, for consistency, URI producers and normalizers should use uppercase hexadecimal digits for all percent-encodings, this function must always generate hexadecimal values using the upper-case letters A-F.

Notes

The function is idempotent but not invertible. Both the inputs My Documents and My%20Documents will be converted to the output My%20Documents.

This function does not check whether $iri is a valid IRI. It treats it as an ·string· and operates on the ·characters· in the string.

The following printable ASCII characters are invalid in an IRI: <, >, ", , {, }, |, \, ^, and `. Since these characters should not appear in an IRI, if they do appear in $iri they will be percent-encoded. In addition, characters outside the range U+0020 (SPACE) to U+007E (TILDE, ~) will be percent-encoded because they are invalid in a URI.

Since this function does not escape the character U+0025 (PERCENT SIGN, %) and this character is not allowed in data within a URI, users wishing to convert character strings (such as file names) that include % to a URI should manually escape % by replacing it with %25.

The function is idempotent but not invertible. Both the inputs My Documents and My%20Documents will be converted to the output My%20Documents.

This function does not check whether $iri is a valid IRI. It treats it as an ·string· and operates on the ·characters· in the string.

The following printable ASCII characters are invalid in an IRI: <, >, ", , {, }, |, \, ^, and `. Since these characters should not appear in an IRI, if they do appear in $iri they will be percent-encoded. In addition, characters outside the range U+0020 (SPACE) to U+007E (TILDE, ~) will be percent-encoded because they are invalid in a URI.

Since this function does not escape the character U+0025 (PERCENT SIGN, %) and this character is not allowed in data within a URI, users wishing to convert character strings (such as file names) that include % to a URI should manually escape % by replacing it with %25.

Examples
Expression:
iri-to-uri(
  "http://www.example.com/00/Weather/CA/Los%20Angeles#ocean"
)
Result:
"http://www.example.com/00/Weather/CA/Los%20Angeles#ocean"
Expression:

iri-to-uri("http://www.example.com/~bébé")

Result:
"http://www.example.com/~b%C3%A9b%C3%A9"

6.5 fn:escape-html-uri

Summary

Escapes a URI in the same way that HTML user agents handle attribute values expected to contain URIs.

Signature
fn:escape-html-uri(
$valueas xs:string?
) as xs:string
Properties

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

Rules

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

Otherwise, the function escapes all ·characters· except printable characters of the US-ASCII coded character set, specifically the ·codepoints· between 32 and 126 (decimal) inclusive. Each character in $value to be escaped is replaced by an escape sequence, which is formed by encoding the character as a sequence of octets in UTF-8, and then representing each of these octets in the form %HH, where HH is the hexadecimal representation of the octet. This function must always generate hexadecimal values using the upper-case letters A-F.

Notes

The behavior of this function corresponds to the recommended handling of non-ASCII characters in URI attribute values as described in [HTML 4.0] Appendix B.2.1.

The behavior of this function corresponds to the recommended handling of non-ASCII characters in URI attribute values as described in [HTML 4.0] Appendix B.2.1.

Examples
Expression:
escape-html-uri(
  "http://www.example.com/00/Weather/CA/Los Angeles#ocean"
)
Result:
"http://www.example.com/00/Weather/CA/Los Angeles#ocean"
Expression:
escape-html-uri(
  "javascript:if (navigator.browserLanguage == 'fr') window.open('http://www.example.com/~bébé');"
)
Result:
"javascript:if (navigator.browserLanguage == 'fr') window.open('http://www.example.com/~b%C3%A9b%C3%A9');"

6.6 Parsing and building URIs

This section specifies functions that parse strings as URIs, to identify their structure, and construct URI strings from their structured representation.

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.

FunctionMeaning
fn:parse-uriParses the URI provided and returns a map of its parts.
fn:build-uriConstructs a URI from the parts provided.

Both functions use a structured representation of a URI as defined in the next section.

6.6.2 fn:parse-uri

Changes in 4.0  

  1. New in 4.0  [Issues 72 389 390  17 October 2022]

Summary

Parses the URI provided and returns a map of its parts.

Signature
fn:parse-uri(
$valueas xs:string?,
$optionsas map(*)?:= {}
) as uri-structure-record?
Properties

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

Rules

If $value is an empty sequence, the result is an empty sequence.

The function parses the $value provided, returning a map containing its constituent parts: scheme, authority components, path, etc. In addition to parsing URIs as defined by [RFC 3986] (and [RFC 3987]), this function also attempts to account for strings that are not valid URIs but that often appear in URI-adjacent spaces, such as file names. Not all such strings can be successfully parsed as URIs.

The following options are available:

record(
allow-deprecated-features?as xs:boolean,
omit-default-ports?as xs:boolean,
unc-path?as xs:boolean
)
KeyMeaning

allow-deprecated-features?

Indicates that deprecated URI features should be returned
  • Type: xs:boolean

  • Default: false()

omit-default-ports?

Indicates that a port number that is the same as the default port for a given scheme should be omitted.
  • Type: xs:boolean

  • Default: false()

unc-path?

Indicates that an input URI that begins with two or more leading slashes should be interprted as a Windows Universal Naming Convention Path. (Specifically: that it has the file: scheme.)
  • Type: xs:boolean

  • Default: false()

This function is described as a series of transformations over the input string to identify the parts of a URI that are present. Some portions of the URI are identified by matching with a regular expression. This approach is designed to make the description clear and unambiguous; it is not implementation advice. Comparison of scheme and authority components is case insensitive.

Processing begins with a string that is equal to the $value. If the string contains any backslashes (\), replace them with forward slashes (/).

Strip off the fragment identifier and any query:

  • If the string matches ^(.*?)#(.*)$, the string is the first match group and the fragment is the second match group. Otherwise, the string is unchanged and the fragment is the empty sequence. If a fragment is present, it is URI decoded. If the fragment is the empty string, it is discarded and the fragment is the empty sequence.

  • If the string matches ^(.*?)\?(.*)$, the string is the first match group and the query is the second match group. Otherwise, the string is unchanged and the query is the empty sequence. If the query is the empty string, it is discarded and the query is the empty sequence.

Attempt to identify the scheme:

  • If the string matches ^([a-zA-Z][A-Za-z0-9\+\-\.]+):(.*)$:

    • the scheme is the first match group and

    • the string is the second match group.

  • Otherwise, the scheme is the empty sequence and the string is unchanged.

If the scheme is not empty and the fragment is empty, absolute is true. Otherwise, absolute is the empty sequence. (But see the discussion of hierarchical URIs, below.)

If scheme is the empty sequence or file:

  • If the string matches ^/*([a-zA-Z][:|].*)$:

    • the scheme is file and

    • the string is a single slash / followed by the first match group with the second character changed to :, if necessary.

  • Otherwise, if unc-path is true:

    • the scheme is file and

    • the string is unchanged.

  • Finally, if neither of the preceding cases apply:

    • the scheme remains the empty sequence and

    • the string is unchanged.

Now that the scheme, if there is one, has been identified, determine if the URI is hierarchical:

  • If the scheme is known to be hierarchical, or known not to be hierarchical, then hierarchical is set accordingly. If the implementation does not know if a scheme is or is not hierarchical, the hierarchical setting depends on the string: if the string is the empty string, hierarchical is the empty sequence (i.e. not known), otherwise hierarchical is true if string begins with / and false otherwise.

If the URI is not hierarchical, absolute is the empty sequence.

Identify the remaining components according to the scheme and whether or not the URI is hierarchical.

  • If the scheme is file:

    • The authority is the empty sequence.

    • If unc-path is true and the string matches ^/*(//[^/].*)$: then filepath, and string are both the first match group.

    • If the string begins ^//*[A-Za-z]:/ then all but one leading slash is removed from string and the filepath is the string with all leading slashes removed.

    • Otherwise, the filepath and string are the string with any sequence of leading slashes replaced by a single slash.

  • If the scheme is hierarchical:

    • If the string matches ^//([^/]+)$, the authority is the first match group and the string is empty.

    • If the string matches ^//([^/]*)(/.*)$, the authority is the first match group and the string is the second match group.

    • Otherwise, the authority is the empty sequence and the string is unchanged.

  • If the scheme is not hierarchical:

    • The authority is the empty sequence and the string is unchanged.

If the authority matches ^(([^@]*)@)(.*)(:([^:]*))?$, then the userinfo is match group 2, otherwise userinfo is the empty sequence. If userinfo is present and contains a non-empty password, then userinfo is discarded and set to the empty sequence unless the allow-deprecated-features option is true.

When parsing the authority to find the host, there are four possibilities: the host can be a registered name (e.g., example.com), an IPv4 address (e.g., 127.0.0.1), an IPv6 (or IPvFuture) address (e.g., [::1]), or an error if there is an open square bracket ([) not matched by a close square bracket (]). In a properly constructed RFC 3986 URI, the only place where square brackets may occur is around the IPv6/IPvFuture IP address.

  1. If the authority matches ^(([^@]*)@)?(\[[^\]]*\])(:([^:]*))?$, then the host is match group 3, otherwise

  2. If the authority matches ^(([^@]*)@)?\[.*$ then [err:FOUR0001] is raised, otherwise

  3. If the authority matches ^(([^@]*)@)?([^:]+)(:([^:]*))?$, then the host is match group 3, otherwise

  4. the host is the empty sequence.

This function does not attempt to decode the components of the host.

Similar care must be taken to match the port because an IPv6/IPvFuture address may contain a colon.

  • If the authority matches ^(([^@]*)@)?(\[[^\]]*\])(:([^:]*))?$, then the port is match group 5.

  • Otherwise, if the authority matches ^(([^@]*)@)?([^:]+)(:([^:]*))?$, then the port is match group 5.

  • Otherwise, the port is the empty sequence.

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

If the string is the empty string, then path is the empty sequence, otherwise path is the whole string. If the scheme is the empty sequence, filepath is also the whole string.

A path-segments sequence is constructed by tokenizing the string on / (solidus) and applying uri decoding on each token.

Note:

The path and path-segments properties both contain the path portion of the URI. The different formats only become important when the path contains encoded delimiters.

Consider /path%2Fsegment. An application may want to decode that, using /path/segment in a database query, for example. At the same time, an application may wish to modify the URI and then reconstruct it.

In the string form, decoding %2F to / is not reversible. In the path-segments form, the path is broken into discrete segments where the syntactic delimiters occur. This means the encoded delimiters can be decoded without introducing ambiguity: ("", "path/segment"). In this format, the decoding is reversible: escape the non-syntactic delimiters before reconstructing the path with the syntactic ones.

A consequence of constructing the path-segments this way is that an empty string appears before the first /, if the path begins with a /, after the last /, if the path ends with a /, and between consecutive / characters. (If the path consists of a single /, that / counts as both the first and last /, producing a segment list containing two empty strings.)

The empty strings may seem unnecessary at first glance, but they assure that the path can be reconstructed by joining the segments together again without having to handle the presence or absence of a leading or trailing / as special cases.

Applying uri decoding is equivalent to calling fn:decode-from-uri on the string.

The query-parameters value is constructed as follows. Start with an empty map. Tokenize the query on the & (ampersand). For each token, identify the key and the value. If the token contains an equal sign (=), the key is the string that precedes the first equal sign, uri decoded, and the value is the remainder of the token, after the first equal sign, uri decoded. If the token does not contain an equal sign, key is the empty string and the value is equal to the token, uri decoded. Add the key/value pair to the map. If the key already exists in the map, add the value to a list of values associated with that key. The resulting map, when all tokens have been processed, is the query-parameters map.

If the filepath is not the empty sequence, it is uri decoded. On a Windows system, any forward slashes in the path may be replaced with backslashes.

A uri-structure-record is returned. The record should be populated with only those keys that have a non-empty value (keys whose value is the empty sequence should be omitted).

Implementations may implement additional or different rules for URIs that have a scheme or pattern that they recognize. An implementation might choose to parse jar: URIs with special rules, for example, since they extend the syntax in ways not defined by [RFC 3986]. Implementations may add additional keys to the map. The meaning of those keys is implementation-defined.

Error Conditions

A dynamic error is raised [err:FOUR0001] if the URI contains an open square bracket in the authority component that is not followed by a close square bracket.

Notes

Like fn:resolve-uri, this function handles the additional characters allowed in [RFC 3987] IRIs in the same way that other unreserved characters are handled.

Unlike fn:resolve-uri, this function is not attempting to resolve one URI against another and consequently, the errors that can arise under those circumstances do not apply here. The fn:parse-uri function will accept strings that would raise errors if resolution was attempted; see fn:build-uri.

Like fn:resolve-uri, this function handles the additional characters allowed in [RFC 3987] IRIs in the same way that other unreserved characters are handled.

Unlike fn:resolve-uri, this function is not attempting to resolve one URI against another and consequently, the errors that can arise under those circumstances do not apply here. The fn:parse-uri function will accept strings that would raise errors if resolution was attempted; see fn:build-uri.

Examples

In the examples that follow, keys with values that are null or an empty sequence are elided for editorial clarity. String literals that include an ampersand character are written as string templates (for example `Barnes&Noble`) to ensure that the examples work in both XPath and XQuery.

Expression:
parse-uri("http://qt4cg.org/specifications/xpath-functions-40/Overview.html#parse-uri")
Result:
{
  "authority": "qt4cg.org",
  "fragment": "parse-uri",
  "hierarchical": true(),
  "host": "qt4cg.org",
  "path": "/specifications/xpath-functions-40/Overview.html",
  "path-segments": ("", "specifications", "xpath-functions-40", "Overview.html"),
  "scheme": "http",
  "uri": "http://qt4cg.org/specifications/xpath-functions-40/Overview.html#parse-uri"
}
Expression:
parse-uri("http://www.ietf.org/rfc/rfc2396.txt")
Result:
{
  "authority": "www.ietf.org",
  "hierarchical": true(),
  "absolute": true(),
  "host": "www.ietf.org",
  "path": "/rfc/rfc2396.txt",
  "path-segments": ("", "rfc", "rfc2396.txt"),
  "scheme": "http",
  "uri": "http://www.ietf.org/rfc/rfc2396.txt"
}
Expression:
parse-uri("https://example.com/path/to/file")
Result:
{
  "authority": "example.com",
  "path": "/path/to/file",
  "scheme": "https",
  "path-segments": ("", "path", "to", "file"),
  "host": "example.com",
  "hierarchical": true(),
  "absolute": true(),
  "uri": "https://example.com/path/to/file"
}
Expression:
parse-uri(
  `https://example.com:8080/path?s=%22hello world%22&sort=relevance`
)
Result:
{
  "authority": "example.com:8080",
  "hierarchical": true(),
  "absolute": true(),
  "host": "example.com",
  "path": "/path",
  "path-segments": ("", "path"),
  "port": "8080",
  "query": `s=%22hello world%22&sort=relevance`,
  "query-parameters": {
    "s": """hello world""",
    "sort": "relevance"
  },
  "scheme": "https",
  "uri": `https://example.com:8080/path?s=%22hello world%22&sort=relevance`
}
Expression:
parse-uri("https://user@example.com/path/to/file")
Result:
{
  "authority": "user@example.com",
  "hierarchical": true(),
  "absolute": true(),
  "host": "example.com",
  "path": "/path/to/file",
  "path-segments": ("", "path", "to", "file"),
  "scheme": "https",
  "uri": "https://user@example.com/path/to/file",
  "userinfo": "user"
}
Expression:
parse-uri("ftp://ftp.is.co.za/rfc/rfc1808.txt")
Result:
{
  "authority": "ftp.is.co.za",
  "hierarchical": true(),
  "absolute": true(),
  "host": "ftp.is.co.za",
  "path": "/rfc/rfc1808.txt",
  "path-segments": ("", "rfc", "rfc1808.txt"),
  "scheme": "ftp",
  "uri": "ftp://ftp.is.co.za/rfc/rfc1808.txt"
}
Expression:
parse-uri("file:////uncname/path/to/file")
Result:
{
  "filepath": "/uncname/path/to/file",
  "hierarchical": true(),
  "absolute": true(),
  "path": "/uncname/path/to/file",
  "path-segments": ("", "uncname", "path", "to", "file"),
  "scheme": "file",
  "uri": "file:////uncname/path/to/file"
}
Expression:
parse-uri("file:///c:/path/to/file")
Result:
{
  "filepath": "c:/path/to/file",
  "hierarchical": true(),
  "absolute": true(),
  "path": "/c:/path/to/file",
  "path-segments": ("", "c:", "path", "to", "file"),
  "scheme": "file",
  "uri": "file:///c:/path/to/file"
}
Expression:
parse-uri("file:/C:/Program%20Files/test.jar")
Result:
{
  "filepath": "C:/Program Files/test.jar",
  "hierarchical": true(),
  "absolute": true(),
  "path": "/C:/Program%20Files/test.jar",
  "path-segments": ("", "C:", "Program Files", "test.jar"),
  "scheme": "file",
  "uri": "file:/C:/Program%20Files/test.jar"
}
Expression:
parse-uri("file:\\c:\path\to\file")
Result:
{
  "filepath": "c:/path/to/file",
  "hierarchical": true(),
  "absolute": true(),
  "path": "/c:/path/to/file",
  "path-segments": ("", "c:", "path", "to", "file"),
  "scheme": "file",
  "uri": "file:\\c:\path\to\file"
}
Expression:
parse-uri("file:\c:\path\to\file")
Result:
{
  "filepath": "c:/path/to/file",
  "hierarchical": true(),
  "absolute": true(),
  "path": "/c:/path/to/file",
  "path-segments": ("", "c:", "path", "to", "file"),
  "scheme": "file",
  "uri": "file:\c:\path\to\file"
}
Expression:
parse-uri("c:\path\to\file")
Result:
{
  "filepath": "c:/path/to/file",
  "hierarchical": true(),
  "path": "/c:/path/to/file",
  "path-segments": ("", "c:", "path", "to", "file"),
  "scheme": "file",
  "uri": "c:\path\to\file"
}
Expression:
parse-uri("/path/to/file")
Result:
{
  "filepath": "/path/to/file",
  "hierarchical": true(),
  "path": "/path/to/file",
  "path-segments": ("", "path", "to", "file"),
  "uri": "/path/to/file"
}
Expression:
parse-uri("#testing")
Result:
{
  "fragment": "testing",
  "uri": "#testing"
}
Expression:
parse-uri("?q=1")
Result:
{
  "query": "q=1",
  "query-parameters":{
    "q": "1"
  },
  "uri": "?q=1"
}
Expression:
parse-uri("ldap://[2001:db8::7]/c=GB?objectClass?one")
Result:
{
  "authority": "[2001:db8::7]",
  "hierarchical": true(),
  "absolute": true(),
  "host": "[2001:db8::7]",
  "path": "/c=GB",
  "path-segments": ("", "c=GB"),
  "query": "objectClass?one",
  "query-parameters":{
    "": "objectClass?one"
  },
  "scheme": "ldap",
  "uri": "ldap://[2001:db8::7]/c=GB?objectClass?one"
}
Expression:
parse-uri("mailto:John.Doe@example.com")
Result:
{
  "hierarchical": false(),
  "path": "John.Doe@example.com",
  "path-segments": "John.Doe@example.com",
  "scheme": "mailto",
  "uri": "mailto:John.Doe@example.com"
}
Expression:
parse-uri("news:comp.infosystems.www.servers.unix")
Result:
{
  "hierarchical": false(),
  "path": "comp.infosystems.www.servers.unix",
  "path-segments": "comp.infosystems.www.servers.unix",
  "scheme": "news",
  "uri": "news:comp.infosystems.www.servers.unix"
}
Expression:
parse-uri("tel:+1-816-555-1212")
Result:
{
  "hierarchical": false(),
  "path": "+1-816-555-1212",
  "path-segments": " 1-816-555-1212",
  "scheme": "tel",
  "uri": "tel:+1-816-555-1212"
}
Expression:
parse-uri("telnet://192.0.2.16:80/")
Result:
{
  "authority": "192.0.2.16:80",
  "hierarchical": true(),
  "absolute": true(),
  "host": "192.0.2.16",
  "path": "/",
  "path-segments": ("", ""),
  "port": "80",
  "scheme": "telnet",
  "uri": "telnet://192.0.2.16:80/"
}
Expression:
parse-uri("urn:oasis:names:specification:docbook:dtd:xml:4.1.2")
Result:
{
  "hierarchical": false(),
  "path": "oasis:names:specification:docbook:dtd:xml:4.1.2",
  "path-segments": "oasis:names:specification:docbook:dtd:xml:4.1.2",
  "scheme": "urn",
  "uri": "urn:oasis:names:specification:docbook:dtd:xml:4.1.2"
}
Expression:
parse-uri("tag:textalign.net,2015:ns")
Result:
{
  "hierarchical": false(),
  "path": "textalign.net,2015:ns",
  "path-segments": "textalign.net,2015:ns",
  "scheme": "tag",
  "uri": "tag:textalign.net,2015:ns"
}
Expression:
parse-uri("tag:jan@example.com,1999-01-31:my-uri")
Result:
{
  "hierarchical": false(),
  "path": "jan@example.com,1999-01-31:my-uri",
  "path-segments": "jan@example.com,1999-01-31:my-uri",
  "scheme": "tag",
  "uri": "tag:jan@example.com,1999-01-31:my-uri"
}

This example uses the algorithm described above, not an algorithm that is specifically aware of the jar: scheme.

Expression:
parse-uri("jar:file:/C:/Program%20Files/test.jar!/foo/bar")
Result:
{
  "hierarchical": false(),
  "path": "file:/C:/Program%20Files/test.jar!/foo/bar",
  "path-segments": ("file:", "C:", "Program Files", "test.jar!", "foo", "bar"),
  "scheme": "jar",
  "uri": "jar:file:/C:/Program%20Files/test.jar!/foo/bar"
}

This example demonstrates that parsing the URI treats non-URI characters in lexical IRIs as “unreserved characters”. The rationale for this is given in the description of fn:resolve-uri.

Expression:
parse-uri("http://www.example.org/Dürst")
Result:
{
  "authority": "www.example.org",
  "hierarchical": true(),
  "absolute": true(),
  "host": "www.example.org",
  "path": "/Dürst",
  "path-segments": ("", "Dürst"),
  "scheme": "http",
  "uri": "http://www.example.org/Dürst"
}

This example demonstrates the use of | instead of : in a Windows path.

Expression:
parse-uri("c|/path/to/file")
Result:
{
  "filepath": "c:/path/to/file",
  "hierarchical": true(),
  "path": "/c:/path/to/file",
  "path-segments": ("", "c:", "path", "to", "file"),
  "scheme": "file",
  "uri": "c|/path/to/file"
}

This example demonstrates the use of | instead of : in a Windows path with an explicit file: scheme.

Expression:
parse-uri("file://c|/path/to/file")
Result:
{
  "filepath": "c:/path/to/file",
  "hierarchical": true(),
  "absolute": true(),
  "path": "/c:/path/to/file",
  "path-segments": ("", "c:", "path", "to", "file"),
  "scheme": "file",
  "uri": "file://c|/path/to/file"
}

7 Functions and operators on Boolean values

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

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

7.3.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 Section 2.4.3 Effective Boolean Value XP31.

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

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

  • If $input is a singleton value of type xs:boolean or a 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.

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) raises a type error [err:FORG0006].

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

8 Functions and operators on durations

Operators are defined on the following type:

and on the two defined subtypes (see 8.1.1 Subtypes of duration):

No ordering relation is defined on xs:duration values. Two xs:duration values may however be compared for equality.

8.2 Comparison operators on durations

FunctionMeaning
op:yearMonthDuration-less-thanReturns true if $arg1 is a shorter duration than $arg2.
op:dayTimeDuration-less-thanReturns true if $arg1 is a shorter duration than $arg2.
op:duration-equalReturns true if $arg1 and $arg2 are durations of the same length.

The following comparison operators are defined on the [XML Schema Part 2: Datatypes Second Edition] duration datatypes. Each operator takes two operands of the same type and returns an xs:boolean result. As discussed in [XML Schema Part 2: Datatypes Second Edition], the order relation on xs:duration is a partial order rather than a total order. For this reason, only equality is defined on xs:duration. A full complement of comparison and arithmetic functions are defined on the two subtypes of duration described in 8.1.1 Subtypes of duration which do have a total order.

8.2.1 op:yearMonthDuration-less-than

Summary

Returns true if $arg1 is a shorter duration than $arg2.

Operator Mapping

Defines the semantics of the lt operator when applied to two xs:yearMonthDuration values. Also used in the definition of the ge operator.

Signature
op:yearMonthDuration-less-than(
$arg1as xs:yearMonthDuration,
$arg2as xs:yearMonthDuration
) as xs:boolean
Rules

If the number of months in $arg1 is numerically less than the number of months in $arg2, the function returns true.

Otherwise, the function returns false.

Notes

Either or both durations may be negative.

Either or both durations may be negative.

8.2.2 op:dayTimeDuration-less-than

Summary

Returns true if $arg1 is a shorter duration than $arg2.

Operator Mapping

Defines the semantics of the lt operator when applied to two xs:dayTimeDuration values. Also used in the definition of the ge operator.

Signature
op:dayTimeDuration-less-than(
$arg1as xs:dayTimeDuration,
$arg2as xs:dayTimeDuration
) as xs:boolean
Rules

If the number of seconds in $arg1 is numerically less than the number of seconds in $arg2, the function returns true.

Otherwise, the function returns false.

Notes

Either or both durations may be negative

Either or both durations may be negative

8.2.3 op:duration-equal

Summary

Returns true if $arg1 and $arg2 are durations of the same length.

Operator Mapping

Defines the semantics of the eq operators when applied to two xs:duration values. Also used in the definition of the ne operator.

Signature
op:duration-equal(
$arg1as xs:duration,
$arg2as xs:duration
) as xs:boolean
Rules

If the xs:yearMonthDuration components of $arg1 and $arg2 are equal and the xs:dayTimeDuration components of $arg1 and $arg2 are equal, the function returns true.

Otherwise, the function returns false.

The semantics of this function are:

xs:yearMonthDuration($arg1) div xs:yearMonthDuration('P1M')  eq
xs:yearMonthDuration($arg2) div xs:yearMonthDuration('P1M')
    and
xs:dayTimeDuration($arg1) div xs:dayTimeDuration('PT1S')  eq
xs:dayTimeDuration($arg2) div xs:dayTimeDuration('PT1S')

that is, the function returns true if the months and seconds values of the two durations are equal.

Notes

Note that this function, like any other, may be applied to arguments that are derived from the types given in the function signature, including the two subtypes xs:dayTimeDuration and xs:yearMonthDuration. With the exception of the zero-length duration, no instance of xs:dayTimeDuration can ever be equal to an instance of xs:yearMonthDuration.

Note that this function, like any other, may be applied to arguments that are derived from the types given in the function signature, including the two subtypes xs:dayTimeDuration and xs:yearMonthDuration. With the exception of the zero-length duration, no instance of xs:dayTimeDuration can ever be equal to an instance of xs:yearMonthDuration.

Examples
Expression:
op:duration-equal(
  xs:duration("P1Y"),
  xs:duration("P12M")
)
Result:
true()
Expression:
op:duration-equal(
  xs:duration("PT24H"),
  xs:duration("P1D")
)
Result:
true()
Expression:
op:duration-equal(
  xs:duration("P1Y"),
  xs:duration("P365D")
)
Result:
false()
Expression:
op:duration-equal(
  xs:yearMonthDuration("P0Y"),
  xs:dayTimeDuration("P0D")
)
Result:
true()
Expression:
op:duration-equal(
  xs:yearMonthDuration("P1Y"),
  xs:dayTimeDuration("P365D")
)
Result:
false()
Expression:
op:duration-equal(
  xs:yearMonthDuration("P2Y"),
  xs:yearMonthDuration("P24M")
)
Result:
true()
Expression:
op:duration-equal(
  xs:dayTimeDuration("P10D"),
  xs:dayTimeDuration("PT240H")
)
Result:
true()
Expression:
op:duration-equal(
  xs:duration("P2Y0M0DT0H0M0S"),
  xs:yearMonthDuration("P24M")
)
Result:
true()
Expression:
op:duration-equal(
  xs:duration("P0Y0M10D"),
  xs:dayTimeDuration("PT240H")
)
Result:
true()

8.4 Constructing durations

This section decribes the fn:seconds function, which constructs an xs:dayTimeDuration value representing a decimal number of seconds.

FunctionMeaning
fn:secondsReturns an xs:dayTimeDuration whose length is a given number of seconds.

8.4.1 fn:seconds

Changes in 4.0  

  1. New in 4.0  [Issue 959 PR 984 6 February 2024]

Summary

Returns an xs:dayTimeDuration whose length is a given number of seconds.

Signature
fn:seconds(
$valueas xs:decimal?
) as xs:dayTimeDuration?
Properties

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

Rules

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

Otherwise, the function returns an xs:dayTimeDuration value whose length in seconds is equal to $value.

If $value is negative then the result will be a negative duration.

For handling of overflow and underflow, see 9.7.1 Limits and precision.

Notes

The result of seconds($n) is approximately equal to the result of the expression xs:dayTimeDuration('PT1S') * $n. The equivalence is only approximate, because seconds($n) uses the exact xs:decimal value supplied, whereas multiplying a duration by a number first promotes the number to an xs:double value, which may lose precision.

The result of seconds($n) is approximately equal to the result of the expression xs:dayTimeDuration('PT1S') * $n. The equivalence is only approximate, because seconds($n) uses the exact xs:decimal value supplied, whereas multiplying a duration by a number first promotes the number to an xs:double value, which may lose precision.

Examples
Expression:
seconds(1)
Result:
xs:dayTimeDuration('PT1S')
Expression:
seconds(0.001)
Result:
xs:dayTimeDuration('PT0.001S')
Expression:
seconds(60)
Result:
xs:dayTimeDuration('PT1M')
Expression:
seconds(86400)
Result:
xs:dayTimeDuration('P1D')
Expression:
seconds(-5400)
Result:
xs:dayTimeDuration('-PT1H30M')
Expression:
xs:dateTime('1970-01-01T00:00:00Z') + 1706702400 * seconds(1)
Result:
xs:dateTime('2024-01-31T12:00:00Z')

(The expression converts a Unix timestamp to an xs:dateTime value).

Expression:
(
  xs:dateTime('2024-01-31T12:00:00Z') -
  xs:dateTime('1970-01-01T00:00:00Z')
) div seconds(1)
Result:
1706702400

(The expression converts an xs:dateTime value to a Unix timestamp).

8.5 Arithmetic operators on durations

FunctionMeaning
op:add-yearMonthDurationsReturns the result of adding two xs:yearMonthDuration values.
op:subtract-yearMonthDurationsReturns the result of subtracting one xs:yearMonthDuration value from another.
op:multiply-yearMonthDurationReturns the result of multiplying $arg1 by $arg2. The result is rounded to the nearest month.
op:divide-yearMonthDurationReturns the result of dividing $arg1 by $arg2. The result is rounded to the nearest month.
op:divide-yearMonthDuration-by-yearMonthDurationReturns the ratio of two xs:yearMonthDuration values.
op:add-dayTimeDurationsReturns the sum of two xs:dayTimeDuration values.
op:subtract-dayTimeDurationsReturns the result of subtracting one xs:dayTimeDuration from another.
op:multiply-dayTimeDurationReturns the result of multiplying a xs:dayTimeDuration by a number.
op:divide-dayTimeDurationReturns the result of multiplying a xs:dayTimeDuration by a number.
op:divide-dayTimeDuration-by-dayTimeDurationReturns the ratio of two xs:dayTimeDuration values, as a decimal number.

For operators that combine a duration and a date/time value, see 9.7 Arithmetic operators on durations, dates and times.

8.5.1 op:add-yearMonthDurations

Summary

Returns the result of adding two xs:yearMonthDuration values.

Operator Mapping

Defines the semantics of the + operator when applied to two xs:yearMonthDuration values.

Signature
op:add-yearMonthDurations(
$arg1as xs:yearMonthDuration,
$arg2as xs:yearMonthDuration
) as xs:yearMonthDuration
Rules

The function returns the result of adding $arg1 to $arg2. The result will be an xs:yearMonthDuration whose length in months is equal to the length in months of $arg1 plus the length in months of $arg2.

For handling of overflow, see 8.1.2 Limits and precision.

Notes

Either duration (and therefore the result) may be negative.

Either duration (and therefore the result) may be negative.

Examples
Expression:
op:add-yearMonthDurations(
  xs:yearMonthDuration("P2Y11M"),
  xs:yearMonthDuration("P3Y3M")
)
Result:
xs:yearMonthDuration("P6Y2M")

8.5.2 op:subtract-yearMonthDurations

Summary

Returns the result of subtracting one xs:yearMonthDuration value from another.

Operator Mapping

Defines the semantics of the - operator when applied to two xs:yearMonthDuration values.

Signature
op:subtract-yearMonthDurations(
$arg1as xs:yearMonthDuration,
$arg2as xs:yearMonthDuration
) as xs:yearMonthDuration
Rules

The function returns the result of subtracting $arg2 from $arg1. The result will be an xs:yearMonthDuration whose length in months is equal to the length in months of $arg1 minus the length in months of $arg2.

For handling of overflow, see 8.1.2 Limits and precision.

Notes

Either duration (and therefore the result) may be negative.

Either duration (and therefore the result) may be negative.

Examples
Expression:
op:subtract-yearMonthDurations(
  xs:yearMonthDuration("P2Y11M"),
  xs:yearMonthDuration("P3Y3M")
)
Result:
xs:yearMonthDuration("-P4M")

8.5.3 op:multiply-yearMonthDuration

Summary

Returns the result of multiplying $arg1 by $arg2. The result is rounded to the nearest month.

Operator Mapping

Defines the semantics of the * operator when applied to an xs:yearMonthDuration and a numeric value.

Signature
op:multiply-yearMonthDuration(
$arg1as xs:yearMonthDuration,
$arg2as xs:double
) as xs:yearMonthDuration
Rules

The result is the xs:yearMonthDuration whose length in months is equal to the result of applying the fn:round function to the value obtained by multiplying the length in months of $arg1 by the value of $arg2.

If $arg2 is positive or negative zero, the result is a zero-length duration. If $arg2 is positive or negative infinity, the result overflows and is handled as described in 9.7.1 Limits and precision.

For handling of overflow, underflow, and rounding, see 8.1.2 Limits and precision.

Error Conditions

A dynamic error is raised [err:FOCA0005] if $arg2 is NaN.

Notes

Either duration (and therefore the result) may be negative.

Either duration (and therefore the result) may be negative.

Examples
Expression:
op:multiply-yearMonthDuration(
  xs:yearMonthDuration("P2Y11M"),
  2.3
)
Result:
xs:yearMonthDuration("P6Y9M")

8.5.4 op:divide-yearMonthDuration

Summary

Returns the result of dividing $arg1 by $arg2. The result is rounded to the nearest month.

Operator Mapping

Defines the semantics of the div operator when applied to an xs:yearMonthDuration and a numeric value.

Signature
op:divide-yearMonthDuration(
$arg1as xs:yearMonthDuration,
$arg2as xs:double
) as xs:yearMonthDuration
Rules

The result is the xs:yearMonthDuration whose length in months is equal to the result of applying the fn:round function to the value obtained by dividing the length in months of $arg1 by the value of $arg2.

If $arg2 is positive or negative infinity, the result is a zero-length duration. If $arg2 is positive or negative zero, the result overflows and is handled as described in 9.7.1 Limits and precision.

For handling of overflow, underflow, and rounding, see 8.1.2 Limits and precision.

Error Conditions

A dynamic error is raised [err:FOCA0005] if $arg2 is NaN.

Notes

Either operand (and therefore the result) may be negative.

Either operand (and therefore the result) may be negative.

Examples
Expression:
op:divide-yearMonthDuration(
  xs:yearMonthDuration("P2Y11M"),
  1.5
)
Result:
xs:yearMonthDuration("P1Y11M")

8.5.5 op:divide-yearMonthDuration-by-yearMonthDuration

Summary

Returns the ratio of two xs:yearMonthDuration values.

Operator Mapping

Defines the semantics of the div operator when applied to two xs:yearMonthDuration values.

Signature
op:divide-yearMonthDuration-by-yearMonthDuration(
$arg1as xs:yearMonthDuration,
$arg2as xs:yearMonthDuration
) as xs:decimal
Rules

The function returns the result of dividing the length in months of $arg1 by the length in months of $arg2, according to the rules of the op:numeric-divide function for integer operands.

For handling of overflow, underflow, and rounding, see 8.1.2 Limits and precision.

Notes

Either duration (and therefore the result) may be negative.

Either duration (and therefore the result) may be negative.

Examples
Expression:
op:divide-yearMonthDuration-by-yearMonthDuration(
  xs:yearMonthDuration("P3Y4M"),
  xs:yearMonthDuration("-P1Y4M")
)
Result:
-2.5

The following example demonstrates how to calculate the length of an xs:yearMonthDuration value in months:

Expression:
op:divide-yearMonthDuration-by-yearMonthDuration(
  xs:yearMonthDuration("P3Y4M"),
  xs:yearMonthDuration("P1M")
)
Result:
40

8.5.6 op:add-dayTimeDurations

Summary

Returns the sum of two xs:dayTimeDuration values.

Operator Mapping

Defines the semantics of the + operator when applied to two xs:dayTimeDuration values.

Signature
op:add-dayTimeDurations(
$arg1as xs:dayTimeDuration,
$arg2as xs:dayTimeDuration
) as xs:dayTimeDuration
Rules

The function returns the result of adding $arg1 to $arg2. The result is the xs:dayTimeDuration whose length in seconds is equal to the sum of the length in seconds of the two input durations.

For handling of overflow, see 8.1.2 Limits and precision.

Notes

Either duration (and therefore the result) may be negative.

Either duration (and therefore the result) may be negative.

Examples
Expression:
op:add-dayTimeDurations(
  xs:dayTimeDuration("P2DT12H5M"),
  xs:dayTimeDuration("P5DT12H")
)
Result:
xs:dayTimeDuration('P8DT5M')

8.5.7 op:subtract-dayTimeDurations

Summary

Returns the result of subtracting one xs:dayTimeDuration from another.

Operator Mapping

Defines the semantics of the - operator when applied to two xs:dayTimeDuration values.

Signature
op:subtract-dayTimeDurations(
$arg1as xs:dayTimeDuration,
$arg2as xs:dayTimeDuration
) as xs:dayTimeDuration
Rules

The function returns the result of subtracting $arg2 from $arg1. The result is the xs:dayTimeDuration whose length in seconds is equal to the length in seconds of $arg1 minus the length in seconds of $arg2.

For handling of overflow, see 8.1.2 Limits and precision.

Notes

Either duration (and therefore the result) may be negative.

Either duration (and therefore the result) may be negative.

Examples
Expression:
op:subtract-dayTimeDurations(
  xs:dayTimeDuration("P2DT12H"),
  xs:dayTimeDuration("P1DT10H30M")
)
Result:
xs:dayTimeDuration('P1DT1H30M')

8.5.8 op:multiply-dayTimeDuration

Summary

Returns the result of multiplying a xs:dayTimeDuration by a number.

Operator Mapping

Defines the semantics of the * operator when applied to an xs:dayTimeDuration and a numeric value.

Signature
op:multiply-dayTimeDuration(
$arg1as xs:dayTimeDuration,
$arg2as xs:double
) as xs:dayTimeDuration
Rules

The function returns the result of multiplying $arg1 by $arg2. The result is the xs:dayTimeDuration whose length in seconds is equal to the length in seconds of $arg1 multiplied by the numeric value $arg2.

If $arg2 is positive or negative zero, the result is a zero-length duration. If $arg2 is positive or negative infinity, the result overflows and is handled as described in 8.1.2 Limits and precision.

For handling of overflow, underflow, and rounding, see 8.1.2 Limits and precision.

Error Conditions

A dynamic error is raised [err:FOCA0005] if $arg2 is NaN.

Notes

Either operand (and therefore the result) may be negative.

Either operand (and therefore the result) may be negative.

Examples
Expression:
op:multiply-dayTimeDuration(
  xs:dayTimeDuration("PT2H10M"),
  2.1
)
Result:
xs:dayTimeDuration('PT4H33M')

8.5.9 op:divide-dayTimeDuration

Summary

Returns the result of multiplying a xs:dayTimeDuration by a number.

Operator Mapping

Defines the semantics of the div operator when applied to two xs:dayTimeDuration values.

Signature
op:divide-dayTimeDuration(
$arg1as xs:dayTimeDuration,
$arg2as xs:double
) as xs:dayTimeDuration
Rules

The function returns the result of dividing $arg1 by $arg2. The result is the xs:dayTimeDuration whose length in seconds is equal to the length in seconds of $arg1 divided by the numeric value $arg2.

If $arg2 is positive or negative infinity, the result is a zero-length duration. If $arg2 is positive or negative zero, the result overflows and is handled as described in 8.1.2 Limits and precision.

For handling of overflow, underflow, and rounding, see 8.1.2 Limits and precision.

Error Conditions

A dynamic error is raised [err:FOCA0005] if $arg2 is NaN.

Notes

Either operand (and therefore the result) may be negative.

Either operand (and therefore the result) may be negative.

Examples
Expression:
op:divide-dayTimeDuration(
  xs:dayTimeDuration("P1DT2H30M10.5S"),
  1.5
)
Result:
xs:duration("PT17H40M7S")

8.5.10 op:divide-dayTimeDuration-by-dayTimeDuration

Summary

Returns the ratio of two xs:dayTimeDuration values, as a decimal number.

Operator Mapping

Defines the semantics of the div operator when applied to two xs:dayTimeDuration values.

Signature
op:divide-dayTimeDuration-by-dayTimeDuration(
$arg1as xs:dayTimeDuration,
$arg2as xs:dayTimeDuration
) as xs:decimal
Rules

The function returns the result of dividing $arg1 by $arg2. The result is the xs:dayTimeDuration whose length in seconds is equal to the length in seconds of $arg1 divided by the length in seconds of $arg2. The calculation is performed by applying op:numeric-divide to the two xs:decimal operands.

For handling of overflow, underflow, and rounding, see 8.1.2 Limits and precision.

Notes

Either operand (and therefore the result) may be negative.

Either operand (and therefore the result) may be negative.

Examples
Expression:
round-half-to-even(
  op:divide-dayTimeDuration-by-dayTimeDuration(
    xs:dayTimeDuration("P2DT53M11S"), xs:dayTimeDuration("P1DT10H")
  ),
  4
)
Result:
1.4378

This examples shows how to determine the number of seconds in a duration.

Expression:
op:divide-dayTimeDuration-by-dayTimeDuration(
  xs:dayTimeDuration("P2DT53M11S"),
  xs:dayTimeDuration("PT1S")
)
Result:
175991.0

9 Functions and operators on 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.3 Constructing a dateTime

FunctionMeaning
fn:dateTimeReturns an xs:dateTime value created by combining an xs:date and an xs:time.
fn:unix-dateTimeReturns a dateTime value for a Unix time.

9.3.2 fn:unix-dateTime

Changes in 4.0  

  1. New in 4.0  [Issue 959 PR 1358 1 August 2024]

Summary

Returns a dateTime value for a Unix time.

Signature
fn:unix-dateTime(
$valueas xs:nonNegativeInteger?:= 0
) as xs:dateTimeStamp
Properties

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

Rules

The function returns a dateTime value in UTC timezone for the Unix time specified by $value in milliseconds. If the value is absent or an empty sequence, 0 is used. The Unix time is defined in [IEEE 1003.1-2024].

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.

Formal Equivalent

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

xs:dateTime('1970-01-01T00:00:00Z') + ($value otherwise 0) * seconds(0.001)
Notes

By calling this convenience function, it can be ensured that the correct timezone is used for computing the Unix time.

Note that Unix time does not account for leap seconds. It assumes that every day has 86,400 seconds.

By calling this convenience function, it can be ensured that the correct timezone is used for computing the Unix time.

Note that Unix time does not account for leap seconds. It assumes that every day has 86,400 seconds.

Examples
Expression:
unix-dateTime()
Result:
xs:dateTime('1970-01-01T00:00:00Z')
Expression:
unix-dateTime(1)
Result:
xs:dateTime('1970-01-01T00:00:00.001Z')
Expression:
unix-dateTime(86400000)
Result:
xs:dateTime('1970-01-02T00:00:00Z')

Calculate the Unix time associated with a xs:dateTime value:

let $value := current-dateTime()
return ($value - unix-dateTime()) div seconds(0.001)

9.5 Component extraction functions on dates and times

The date and time datatypes may be considered to be composite datatypes in that they contain distinct properties or components. The extraction functions specified below extract a single component from a date or time value. In all cases the local value (that is, the original value as written, without any timezone adjustment) is used.

Note:

A time written as 24:00:00 is treated as 00:00:00 on the following day.

FunctionMeaning
fn:year-from-dateTimeReturns the year component of a ·Gregorian· value.
fn:month-from-dateTimeReturns the month component of a ·Gregorian· value.
fn:day-from-dateTimeReturns the day component of a ·Gregorian· value.
fn:hours-from-dateTimeReturns the hours component of a ·Gregorian· value.
fn:minutes-from-dateTimeReturns the minute component of a ·Gregorian· value.
fn:seconds-from-dateTimeReturns the seconds component of a ·Gregorian· value.
fn:timezone-from-dateTimeReturns the timezone component of a ·Gregorian· value.
fn:year-from-dateReturns the year component of an xs:date.
fn:month-from-dateReturns the month component of an xs:date.
fn:day-from-dateReturns the day component of an xs:date.
fn:timezone-from-dateReturns the timezone component of an xs:date.
fn:hours-from-timeReturns the hours component of an xs:time.
fn:minutes-from-timeReturns the minutes component of an xs:time.
fn:seconds-from-timeReturns the seconds component of an xs:time.
fn:timezone-from-timeReturns the timezone component of an xs:time.

9.5.1 fn:year-from-dateTime

Changes in 4.0  

  1. The function has been extended to handle other Gregorian types such as xs:gYearMonth.  [Issue 1448 PR 1481 8 October 2024]

Summary

Returns the year component of a ·Gregorian· value.

Signature
fn:year-from-dateTime(
$valueas (xs:dateTime | xs:date | xs:time | xs:gYear | xs:gYearMonth | xs:gMonth | xs:gMonthDay | xs:gDay)?
) as xs:integer?
Properties

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

Rules

If $value is the empty sequence, or if the year component is absent, the function returns the empty sequence.

Otherwise, the function returns an xs:integer representing the year component in $value. The result may be negative.

Notes

Ignoring complications that arise with midnight on the last day of the year, the year returned is the same numeric value that appears in the lexical representation, which for negative years means the meaning may vary depending on whether XSD 1.0 or XSD 1.1 conventions are in use.

Ignoring complications that arise with midnight on the last day of the year, the year returned is the same numeric value that appears in the lexical representation, which for negative years means the meaning may vary depending on whether XSD 1.0 or XSD 1.1 conventions are in use.

Examples
Expression:
year-from-dateTime(
  xs:dateTime("1999-05-31T13:20:00-05:00")
)
Result:
1999
Expression:
year-from-dateTime(
  xs:dateTime("1999-05-31T21:30:00-05:00")
)
Result:
1999
Expression:
year-from-dateTime(
  xs:dateTime("1999-12-31T19:20:00")
)
Result:
1999
Expression:
year-from-dateTime(
  xs:dateTime("1999-12-31T24:00:00")
)
Result:
2000
Expression:
year-from-dateTime(
  xs:dateTime("-0002-06-06T00:00:00")
)
Result:
-2

(The result is the same whether XSD 1.0 or 1.1 is in use, despite the absence of a year 0 in the XSD 1.0 value space.)

Expression:
year-from-dateTime(
  xs:gYearMonth("2007-05Z")
)
Result:
2007
Expression:
year-from-dateTime(
  xs:time("12:30:00")
)
Result:
()

9.5.8 fn:year-from-date

Summary

Returns the year component of an xs:date.

Signature
fn:year-from-date(
$valueas xs:date?
) as xs:integer?
Properties

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

Rules

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

Otherwise, the function returns an xs:integer representing the year in the local value of $value. The value may be negative.

Notes

The year returned is the same numeric value that appears in the lexical representation, which for negative years means the meaning may vary depending on whether XSD 1.0 or XSD 1.1 conventions are in use.

The year returned is the same numeric value that appears in the lexical representation, which for negative years means the meaning may vary depending on whether XSD 1.0 or XSD 1.1 conventions are in use.

Examples
ExpressionResult
year-from-date(
  xs:date("1999-05-31")
)
1999
year-from-date(
  xs:date("2000-01-01+05:00")
)
2000
year-from-date(
  xs:date("-0002-06-01")
)
-2

(The result is the same whether XSD 1.0 or 1.1 is in use, despite the absence of a year 0 in the XSD 1.0 value space.)

9.7 Arithmetic operators on durations, dates and times

These functions support adding or subtracting a duration value to or from an xs:dateTime, an xs:date or an xs:time value. Appendix E of [XML Schema Part 2: Datatypes Second Edition] describes an algorithm for performing such operations.

FunctionMeaning
op:subtract-dateTimesReturns an xs:dayTimeDuration representing the amount of elapsed time between the instants arg2 and arg1.
op:subtract-datesReturns the xs:dayTimeDuration that corresponds to the elapsed time between the starting instant of $arg2 and the starting instant of $arg2.
op:subtract-timesReturns the xs:dayTimeDuration that corresponds to the elapsed time between the values of $arg2 and $arg1 treated as times on the same date.
op:add-yearMonthDuration-to-dateTimeReturns the xs:dateTime that is a given duration after a specified xs:dateTime (or before, if the duration is negative).
op:add-dayTimeDuration-to-dateTimeReturns the xs:dateTime that is a given duration after a specified xs:dateTime (or before, if the duration is negative).
op:subtract-yearMonthDuration-from-dateTimeReturns the xs:dateTime that is a given duration before a specified xs:dateTime (or after, if the duration is negative).
op:subtract-dayTimeDuration-from-dateTimeReturns the xs:dateTime that is a given duration before a specified xs:dateTime (or after, if the duration is negative).
op:add-yearMonthDuration-to-dateReturns the xs:date that is a given duration after a specified xs:date (or before, if the duration is negative).
op:add-dayTimeDuration-to-dateReturns the xs:date that is a given duration after a specified xs:date (or before, if the duration is negative).
op:subtract-yearMonthDuration-from-dateReturns the xs:date that is a given duration before a specified xs:date (or after, if the duration is negative).
op:subtract-dayTimeDuration-from-dateReturns the xs:date that is a given duration before a specified xs:date (or after, if the duration is negative).
op:add-dayTimeDuration-to-timeReturns the xs:time value that is a given duration after a specified xs:time (or before, if the duration is negative or causes wrap-around past midnight)
op:subtract-dayTimeDuration-from-timeReturns the xs:time value that is a given duration before a specified xs:time (or after, if the duration is negative or causes wrap-around past midnight)

9.7.4 op:subtract-times

Summary

Returns the xs:dayTimeDuration that corresponds to the elapsed time between the values of $arg2 and $arg1 treated as times on the same date.

Operator Mapping

Defines the semantics of the - operator when applied to two xs:time values.

Signature
op:subtract-times(
$arg1as xs:time,
$arg2as xs:time
) as xs:dayTimeDuration
Properties

This function is ·deterministic·, ·context-dependent·, and ·focus-independent·. It depends on implicit timezone.

Rules

The function returns the result of the expression:

op-subtract-dateTimes(
        dateTime(xs:date('1972-12-31'), $arg1),
        dateTime(xs:date('1972-12-31'), $arg2))
Notes

Any other reference date would work equally well.

Any other reference date would work equally well.

Examples
ExpressionResult

Assume that the dynamic context provides an implicit timezone value of -05:00. Assume, also, that the date components of the reference xs:dateTime correspond to "1972-12-31".

op:subtract-times(
  xs:time("11:12:00Z"),
  xs:time("04:00:00")
)
xs:dayTimeDuration("PT2H12M")

(This is obtained by subtracting from the xs:dateTime value {1972, 12, 31, 11, 12, 0, xs:dayTimeDuration("PT0S")} the xs:dateTime value {1972, 12, 31, 9, 0, 0, xs:dayTimeDuration("PT0S")}.)

op:subtract-times(
  xs:time("11:00:00-05:00"),
  xs:time("21:30:00+05:30")
)
xs:dayTimeDuration("PT0S")

(The two xs:dateTime values are {1972, 12, 31, 11, 0, 0, xs:dayTimeDuration("-PT5H")} and {1972, 12, 31, 21, 30, 0, xs:dayTimeDuration("PT5H30M")}. These normalize to {1972, 12, 31, 16, 0, 0, xs:dayTimeDuration("PT0S")} and {1972, 12, 31, 16, 0, 0, xs:dayTimeDuration("PT0S")}. ).

op:subtract-times(
  xs:time("17:00:00-06:00"),
  xs:time("08:00:00+09:00")
)
xs:dayTimeDuration("P1D")

(The two normalized xs:dateTime values are {1972, 12, 31, 23, 0, 0, xs:dayTimeDuration("PT0S")} and {1972, 12, 30, 23, 0, 0, xs:dayTimeDuration("PT0S")}.)

op:subtract-times(
  xs:time("24:00:00"),
  xs:time("23:59:59")
)
xs:dayTimeDuration("-PT23H59M59S")

(The two normalized xs:dateTime values are {1972, 12, 31, 0, 0, 0, ()} and {1972, 12, 31, 23, 59, 59.0, ()}.)

9.9 Parsing dates and times

FunctionMeaning
fn:parse-ietf-dateParses a string containing the date and time in IETF format, returning the corresponding xs:dateTime value.

A function is provided to parse dates and times expressed using syntax that is commonly encountered in internet protocols.

9.9.1 fn:parse-ietf-date

Summary

Parses a string containing the date and time in IETF format, returning the corresponding xs:dateTime value.

Signature
fn:parse-ietf-date(
$valueas xs:string?
) as xs:dateTime?
Properties

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

Rules

The function accepts a string matching the production input in the following grammar:

input::=S? (dayname ","? S)? ((datespec S time) | asctime) S?
dayname::="Mon" | "Tue" | "Wed" | "Thu" | "Fri" | "Sat" | "Sun" | "Monday | "Tuesday" | "Wednesday" | "Thursday" | "Friday" | "Saturday" | "Sunday"
datespec::=daynum dsep monthname dsep year
asctime::=monthname dsep daynum S time S year
dsep::=S | (S? "-" S?)
daynum::=digit digit?
year::=digit digit (digit digit)?
digit::=[0-9]
monthname::="Jan" | "Feb" | "Mar" | "Apr" | "May" | "Jun" | "Jul" | "Aug" | "Sep" | "Oct" | "Nov" | "Dec"
time::=hours ":" minutes (":" seconds)? (S? timezone)?
hours::=digit digit?
minutes::=digit digit
seconds::=digit digit ("." digit+)?
timezone::=tzname | tzoffset (S? "(" S? tzname S? ")")?
tzname::="UT" | "UTC" | "GMT" | "EST" | "EDT" | "CST" | "CDT" | "MST" | "MDT" | "PST" | "PDT"
tzoffset::=("+"|"-") hours ":"? minutes?
S::=(x09 | x0A | x0D | x20)+

The input is case-insensitive: upper-case and lower-case distinctions in the above grammar show the conventional usage, but otherwise have no significance.

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

The dayname, if present, is ignored.

The daynum, monthname, and year supply the day, month, and year of the resulting xs:dateTime value. A two-digit year must have 1900 added to it. A year such as 0070 is to be treated as given; negative years are not permitted.

The hours, minutes, and seconds (including fractional seconds) values supply the corresponding components of the resulting xs:dateTime value; if the seconds value or the fractional seconds value is absent then zero is assumed.

If both a tzoffset and a tzname are supplied then the tzname is ignored.

If a tzoffset is supplied then this defines the hours and minutes parts of the timezone offset:

  • If it contains a colon, this separates the hours part from the minutes part.

  • Otherwise, the grammar allows a sequence of from one to four digits. These are interpreted as H, HH, HMM, or HHMM respectively, where H or HH is the hours part, and MM (if present) is the minutes part.

  • If the minutes part is absent it defaults to 00.

If a tzname is supplied with no tzoffset then it is translated to a timezone offset as follows:

tznameOffset
UT, UTC, GMT00:00
EST-05:00
EDT-04:00
CST-06:00
CDT-05:00
MST-07:00
MDT-06:00
PST-08:00
PDT-07:00

If neither a tzoffset nor tzname is supplied, a timezone offset of 00:00 is assumed.

Error Conditions

A dynamic error is raised [err:FORG0010] if the input does not match the grammar, or if the resulting date/time value is invalid (for example, "31 February").

Notes

The parse-ietf-date function attempts to interpret its input as a date in any of the three formats specified by HTTP [RFC 2616].

These formats are used widely on the Internet to represent timestamps, and were specified in:

[RFC 2616] (HTTP) officially uses a subset of those three formats restricted to GMT.

The grammar for this function is slightly more liberal than the RFCs (reflecting the internet tradition of being liberal in what is accepted). For example the function:

The parse-ietf-date function attempts to interpret its input as a date in any of the three formats specified by HTTP [RFC 2616].

These formats are used widely on the Internet to represent timestamps, and were specified in:

[RFC 2616] (HTTP) officially uses a subset of those three formats restricted to GMT.

The grammar for this function is slightly more liberal than the RFCs (reflecting the internet tradition of being liberal in what is accepted). For example the function:

  1. Accepts a single-digit value where appropriate in place of a two-digit value with a leading zero (so "Wed 1 Jun" is acceptable in place of "Wed 01 Jun", and the timezone offset "-5:00" is equivalent to "-05:00")

  2. Accepts one or more whitespace characters (x20, x09, x0A, x0D) wherever a single space is required, and allows whitespace to be omitted where it is not required for parsing

  3. Accepts and ignores whitespace characters (x20, x09, x0A, x0D) at the start or end of the string.

In new protocols IETF recommends the format of [RFC 3339], which is based on a profile of ISO 8601 similar to that already used in XPath and XSD, but the “approximate” [RFC 822] format described here is very widely used.

An [RFC 1123] date can be generated approximately using fn:format-dateTime with a picture string of "[FNn3], [D01] [MNn3] [Y04] [H01]:[m01]:[s01] [Z0000]".

In new protocols IETF recommends the format of [RFC 3339], which is based on a profile of ISO 8601 similar to that already used in XPath and XSD, but the “approximate” [RFC 822] format described here is very widely used.

An [RFC 1123] date can be generated approximately using fn:format-dateTime with a picture string of "[FNn3], [D01] [MNn3] [Y04] [H01]:[m01]:[s01] [Z0000]".

Examples
ExpressionResult
parse-ietf-date("Wed, 06 Jun 1994 07:29:35 GMT")
xs:dateTime("1994-06-06T07:29:35Z")
parse-ietf-date("Wed, 6 Jun 94 07:29:35 GMT")
xs:dateTime("1994-06-06T07:29:35Z")
parse-ietf-date("Wed Jun 06 11:54:45 EST 2013")
xs:dateTime("2013-06-06T11:54:45-05:00")
parse-ietf-date("Sunday, 06-Nov-94 08:49:37 GMT")
xs:dateTime("1994-11-06T08:49:37Z")
parse-ietf-date("Wed, 6 Jun 94 07:29:35 +0500")
xs:dateTime("1994-06-06T07:29:35+05:00")

10 Functions related to QNames

10.1 Functions to create a QName

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.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 Section 2.1 TerminologyDM.

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)

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.

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

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

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

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

10.2 Functions and operators on QNames

This section specifies functions and an operator on QNames as defined in [XML Schema Part 2: Datatypes Second Edition].

FunctionMeaning
op:QName-equalReturns true if two supplied QNames have the same namespace URI and the same local part.
fn:prefix-from-QNameReturns the prefix component of the supplied QName.
fn:local-name-from-QNameReturns the local part of the supplied QName.
fn:namespace-uri-from-QNameReturns the namespace URI part of the supplied QName.
fn:expanded-QNameReturns a string representation of an xs:QName in the format Q{uri}local.
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:namespace-uri-for-prefixReturns the namespace URI of one of the in-scope namespaces for $element, identified by its namespace prefix.

10.2.1 op:QName-equal

Summary

Returns true if two supplied QNames have the same namespace URI and the same local part.

Operator Mapping

Defines the semantics of the eq and ne operators when applied to two values of type xs:QName.

Signature
op:QName-equal(
$arg1as xs:QName,
$arg2as xs:QName
) as xs:boolean
Properties

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

Rules

The function returns true if the namespace URIs of $arg1 and $arg2 are equal and the local names of $arg1 and $arg2 are equal.

Otherwise, the function returns false.

The namespace URI parts are considered equal if they are both absentDM, or if they are both present and equal under the rules of the fn:codepoint-equal function.

The local parts are also compared under the rules of the fn:codepoint-equal function.

Notes

The prefix parts of $arg1 and $arg2, if any, are ignored.

The prefix parts of $arg1 and $arg2, if any, are ignored.

10.2.6 fn:in-scope-namespaces

Changes in 4.0  

  1. New in 4.0  [  20 September 2022]

Summary

Returns the in-scope namespaces of an element node, as a map.

Signature
fn:in-scope-namespaces(
$elementas element()
) as map((xs:NCName | enum('')), xs:anyURI)
Properties

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

Rules

The function returns a map representing the prefixes of the in-scope namespaces for $element. The map contains one entry for each in-scope namespace: the key of the entry is the namespace prefix or a zero-length string, and the corresponding value is the namespace URI.

For namespace bindings that have a prefix, the key represents the prefix as an instance of xs:NCName. For the default namespace, which has no prefix, the key is the zero-length string as an instance of xs:string.

The order of entries in the returned map is ·implementation-dependent·.

Notes

The XML namespace is in scope for every element, so the result will always include an entry with key "xml" and corresponding value http://www.w3.org/XML/1998/namespace.

The XML namespace is in scope for every element, so the result will always include an entry with key "xml" and corresponding value http://www.w3.org/XML/1998/namespace.

Examples
Variables
let $e := 
<z:a xmlns="http://example.org/one" xmlns:z="http://example.org/two">
  <b xmlns=""/>
</z:a>
Expression:

in-scope-namespaces($e)

Result:
{
  "": "http://example.org/one",
  "z": "http://example.org/two",
  "xml": "http://www.w3.org/XML/1998/namespace"
}

10.2.7 fn:in-scope-prefixes

Changes in 4.0  

  1. Reformulated in 4.0 in terms of the new fn:in-scope-namespaces function; the semantics are unchanged.

Summary

Returns the prefixes of the in-scope namespaces for an element node.

Signature
fn:in-scope-prefixes(
$elementas element()
) as xs:string*
Properties

This function is ·nondeterministic-wrt-ordering·, ·context-independent·, and ·focus-independent·.

Rules

The function returns the result of the expression map:keys(fn:in-scope-namespaces($element)) (but in no defined order).

Notes

The XML namespace is in scope for every element, so the result will always include the string "xml".

The XML namespace is in scope for every element, so the result will always include the string "xml".

12 Operators on NOTATION

This section specifies operators that take xs:NOTATION values as arguments.

FunctionMeaning
op:NOTATION-equalReturns true if the two xs:NOTATION values have the same namespace URI and the same local part.

12.1 op:NOTATION-equal

Summary

Returns true if the two xs:NOTATION values have the same namespace URI and the same local part.

Operator Mapping

Defines the semantics of the eq and ne operators when applied to two values of type xs:NOTATION.

Signature
op:NOTATION-equal(
$arg1as xs:NOTATION,
$arg2as xs:NOTATION
) as xs:boolean
Rules

The function returns true if the namespace URIs of $arg1 and $arg2 are equal and the local names of $arg1 and $arg2 are equal.

Otherwise, the function returns false.

The namespace URI parts are considered equal if they are both absentDM, or if they are both present and equal under the rules of the fn:codepoint-equal function.

The local parts are also compared under the rules of the fn:codepoint-equal function.

Notes

The prefix parts of $arg1 and $arg2, if any, are ignored.

The prefix parts of $arg1 and $arg2, if any, are ignored.

13 Functions and operators on 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].

13.1 General functions and operators on sequences

The following functions are defined on sequences. These functions work on any sequence, without performing any operations that are sensitive to the individual items in the sequence.

FunctionMeaning
fn:emptyReturns true if the argument is the empty sequence.
fn:existsReturns true if the argument is a non-empty sequence.
fn:footReturns the last item in a sequence.
fn:headReturns the first item in a sequence.
fn:identityReturns its argument value.
fn:insert-beforeReturns a sequence constructed by inserting an item or a sequence of items at a given position within an existing sequence.
fn:items-atReturns a sequence containing the items from $input at positions defined by $at, in the order specified.
fn:removeReturns a new sequence containing all the items of $inputexcept those at specified positions.
fn:replicateProduces multiple copies of a sequence.
fn:reverseReverses the order of items in a sequence.
fn:sequence-joinInserts a separator between adjacent items in a sequence.
fn:sliceReturns a sequence containing selected items from a supplied input sequence based on their position.
fn:subsequenceReturns the contiguous sequence of items in $input beginning at the position indicated by $start and continuing for the number of items indicated by $length.
fn:tailReturns all but the first item in a sequence.
fn:trunkReturns all but the last item in a sequence.
fn:unorderedReturns the items of $input in an ·implementation-dependent· order.
fn:voidAbsorbs the argument.

As in the previous section, for the illustrative examples below, assume an XQuery or transformation operating on a non-empty Purchase Order document containing a number of line-item elements. The variable $seq is bound to the sequence of line-item nodes in document order. The variables $item1, $item2, etc. are bound to separate, individual line-item nodes in the sequence.

13.1.3 fn:foot

Changes in 4.0  

  1. New in 4.0  [Issue 97 PR 250]

Summary

Returns the last item in a sequence.

Signature
fn:foot(
$inputas item()*
) as item()?
Properties

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

Rules

The function returns the value of the expression $input[last()]

Formal Equivalent

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

filter($input, fn($item, $pos) { $pos eq count($input) })
Notes

If $input is the empty sequence the empty sequence is returned.

If $input is the empty sequence the empty sequence is returned.

Examples
ExpressionResult
foot(1 to 5)
5
foot(())
()

13.1.5 fn:identity

Changes in 4.0  

  1. New in 4.0  [Issue 858  20 September 2022]

Summary

Returns its argument value.

Signature
fn:identity(
$inputas item()*
) as item()*
Properties

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

Rules

The function returns $input.

Formal Equivalent

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

$input
Notes

The function is useful in contexts where a function must be supplied, but no processing is required.

The function is useful in contexts where a function must be supplied, but no processing is required.

Examples
ExpressionResult
identity(0)
0
identity(1 to 10)
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
parse-xml('<a/>') ! (identity(/) is /)
true()

(If the argument is a node, the function returns the identical node, not a copy).

identity(())
()

13.1.6 fn:insert-before

Summary

Returns a sequence constructed by inserting an item or a sequence of items at a given position within an existing sequence.

Signature
fn:insert-before(
$inputas item()*,
$positionas xs:integer,
$insertas item()*
) as item()*
Properties

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

Rules

The value returned by the function consists of all items of $input whose 1-based position is less than $position, followed by all items of $insert, followed by the remaining elements of $input, in that order.

Formal Equivalent

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

filter($input, fn($item, $pos) { $pos lt $position }),
$insert,
filter($input, fn($item, $pos) { $pos ge $position })
Notes

If $input is the empty sequence, $insert is returned. If $insert is the empty sequence, $input is returned.

If $position is less than one (1), the first position, the effective value of $position is one (1). If $position is greater than the number of items in $input, then the effective value of $position is equal to the number of items in $input plus 1.

The value of $input is not affected by the sequence construction.

If $input is the empty sequence, $insert is returned. If $insert is the empty sequence, $input is returned.

If $position is less than one (1), the first position, the effective value of $position is one (1). If $position is greater than the number of items in $input, then the effective value of $position is equal to the number of items in $input plus 1.

The value of $input is not affected by the sequence construction.

Examples
Variables
let $abc := ("a", "b", "c")
ExpressionResult
insert-before($abc, 0, "z")
"z", "a", "b", "c"
insert-before($abc, 1, "z")
"z", "a", "b", "c"
insert-before($abc, 2, "z")
"a", "z", "b", "c"
insert-before($abc, 3, "z")
"a", "b", "z", "c"
insert-before($abc, 4, "z")
"a", "b", "c", "z"

13.1.7 fn:items-at

Changes in 4.0  

  1. New in 4.0  [Issue 213 PR 419 22 November 2022]

Summary

Returns a sequence containing the items from $input at positions defined by $at, in the order specified.

Signature
fn:items-at(
$inputas item()*,
$atas xs:integer*
) as item()*
Properties

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

Rules

Returns the items in $input at the positions listed in $at, in order of the integers in the $at argument.

Formal Equivalent

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

for-each($at, fn($index) { subsequence($input, $index, 1) })
Notes

In the simplest case where $at is a single integer, fn:items-at($input, 3) returns the same result as $input[3].

Compared with a simple positional filter expression, the function is useful because:

In the simplest case where $at is a single integer, fn:items-at($input, 3) returns the same result as $input[3].

Compared with a simple positional filter expression, the function is useful because:

  1. It can select items at multiple positions, and unlike fn:subsequence, these do not need to be contiguous.

  2. The $at expression can depend on the focus.

  3. The order of the returned items can differ from their order in the $input sequence.

If any integer in $at is outside the range 1 to count($input), that integer is effectively ignored: no error occurs.

If either of the arguments is an empty sequence, the result is an empty sequence.

If $at contains duplicate integers, the result also contains duplicates. No de-duplication occurs. If the input sequence contains nodes, these are not copied: instead, the result sequence contains multiple references to the same node.

If any integer in $at is outside the range 1 to count($input), that integer is effectively ignored: no error occurs.

If either of the arguments is an empty sequence, the result is an empty sequence.

If $at contains duplicate integers, the result also contains duplicates. No de-duplication occurs. If the input sequence contains nodes, these are not copied: instead, the result sequence contains multiple references to the same node.

Examples
ExpressionResult
items-at(11 to 20, 4)
14
items-at(11 to 20, 4 to 6)
14, 15, 16
items-at(11 to 20, (7, 3))
17, 13
items-at(11 to 20, index-of(("a", "b", "c"), "b"))
12
items-at(characters("quintessential"), (4, 8, 3))
"n", "s", "i"
items-at(characters("quintessential"), (4, 8, 1, 1))
"n", "s", "q", "q"
items-at((), 832)
()
items-at((), ())
()

13.1.8 fn:remove

Changes in 4.0  

  1. The second argument can now be a sequence of integers.  [Issue 294 PR 313 24 January 2023]

Summary

Returns a new sequence containing all the items of $inputexcept those at specified positions.

Signature
fn:remove(
$inputas item()*,
$positionsas xs:integer*
) as item()*
Properties

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

Rules

The function returns a sequence consisting of all items of $inputwhose 1-based position is not equal to any of the integers in $positions.

Formal Equivalent

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

filter($input, fn($item, $pos) { not($pos eq $positions) })
Notes

Any integer in $positions that is less than 1 or greater than the number of items in $input is effectively ignored.

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

If $positions is an empty sequence, the input sequence $input is returned unchanged.

Any integer in $positions that is less than 1 or greater than the number of items in $input is effectively ignored.

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

If $positions is an empty sequence, the input sequence $input is returned unchanged.

Examples
Variables
let $abc := ("a", "b", "c")
ExpressionResult
remove($abc, 0)
"a", "b", "c"
remove($abc, 1)
"b", "c"
remove($abc, 6)
"a", "b", "c"
remove((), 3)
()
remove($abc, 2 to 3)
"a"
remove($abc, ())
"a", "b", "c"

13.1.9 fn:replicate

Changes in 4.0  

  1. New in 4.0  [  4 October 2022]

Summary

Produces multiple copies of a sequence.

Signature
fn:replicate(
$inputas item()*,
$countas xs:nonNegativeInteger
) as item()*
Properties

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

Rules

The function returns the value of (1 to $count) ! $input.

Formal Equivalent

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

fold-left(1 to $count, (), fn($result, $next) { $result, $input })
Notes

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

The $count argument is declared as xs:nonNegativeInteger, which means that a type error occurs if it is called with a negative value.

If the input sequence contains nodes, these are not copied: instead, the result sequence contains multiple references to the same node. So, for example, fn:count(fn:replicate(/, 6)|()) returns 1, because the fn:replicate call creates duplicates, and the union operation eliminates them.

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

The $count argument is declared as xs:nonNegativeInteger, which means that a type error occurs if it is called with a negative value.

If the input sequence contains nodes, these are not copied: instead, the result sequence contains multiple references to the same node. So, for example, fn:count(fn:replicate(/, 6)|()) returns 1, because the fn:replicate call creates duplicates, and the union operation eliminates them.

Examples
ExpressionResult
replicate(0, 6)
0, 0, 0, 0, 0, 0
replicate(("A", "B", "C"), 3)
"A", "B", "C", "A", "B", "C", "A", "B", "C"
replicate((), 5)
()
replicate(("A", "B", "C"), 1)
"A", "B", "C"
replicate(("A", "B", "C"), 0)
()

13.1.10 fn:reverse

Summary

Reverses the order of items in a sequence.

Signature
fn:reverse(
$inputas item()*
) as item()*
Properties

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

Rules

The function returns a sequence containing the items in $input in reverse order.

Formal Equivalent

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

fold-left($input, (), fn($result, $item) { $item, $result })
Notes

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

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

Examples
Variables
let $abc := ("a", "b", "c")
ExpressionResult
reverse($abc)
"c", "b", "a"
reverse(("hello"))
"hello"
reverse(())
()
reverse([ 1, 2, 3 ])
[ 1, 2, 3 ]

(The input is a sequence containing a single item (the array)).

reverse(([ 1, 2, 3 ], [ 4, 5, 6 ]))
[ 4, 5, 6 ], [ 1, 2, 3 ]

13.1.12 fn:slice

Changes in 4.0  

  1. New in 4.0

Summary

Returns a sequence containing selected items from a supplied input sequence based on their position.

Signature
fn:slice(
$inputas item()*,
$startas xs:integer?:= (),
$endas xs:integer?:= (),
$stepas xs:integer?:= ()
) as item()*
Properties

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

Rules

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

Let $S be the first of the following that applies:

  • If $start is absent, empty, or zero, then 1.

  • If $start is negative, then fn:count($input) + $start + 1.

  • Otherwise, $start.

Let $E be the first of the following that applies:

  • If $end is absent, empty, or zero, then fn:count($input).

  • If $end is negative, then fn:count($input) + $end + 1.

  • Otherwise, $end.

Let $STEP be the first of the following that applies:

  • If $step is absent, empty, or zero, then:

    • If $E ge $S, then +1

    • Otherwise -1

  • Otherwise, $step.

If $STEP is negative, the function returns $input => fn:reverse() => fn:slice(-$S, -$E, -$STEP).

Otherwise the function returns the result of the expression:

$input[position() ge $S and position() le $E and (position() - $S) mod $STEP eq 0]
Editorial note 
TBA: define formal equivalent.
Notes

The function is inspired by the slice operators in Javascript and Python, but it differs in detail to accommodate the tradition of 1-based addressing in XPath. The end position is inclusive rather than exclusive, so that in the simple case where $start and $end are positive and $end > $start, fn:slice($in, $start, $end) returns the same result as $in[position() = $start to $end].

This function can be used to enhance the RangeExpression, defined in Section 4.7.2 Range ExpressionsXP, to construct a sequence of integers based on steps other than 1.

The function is inspired by the slice operators in Javascript and Python, but it differs in detail to accommodate the tradition of 1-based addressing in XPath. The end position is inclusive rather than exclusive, so that in the simple case where $start and $end are positive and $end > $start, fn:slice($in, $start, $end) returns the same result as $in[position() = $start to $end].

This function can be used to enhance the RangeExpression, defined in Section 4.7.2 Range ExpressionsXP, to construct a sequence of integers based on steps other than 1.

Examples
Variables
let $in := ('a', 'b', 'c', 'd', 'e')
ExpressionResult
slice($in, start := 2, end := 4)
"b", "c", "d"
slice($in, start := 2)
"b", "c", "d", "e"
slice($in, end := 2)
"a", "b"
slice($in, start := 3, end := 3)
"c"
slice($in, start := 4, end := 3)
"d", "c"
slice($in, start := 2, end := 5, step := 2)
"b", "d"
slice($in, start := 5, end := 2, step := -2)
"e", "c"
slice($in, start := 2, end := 5, step := -2)
()
slice($in, start := 5, end := 2, step := 2)
()
slice($in)
"a", "b", "c", "d", "e"
slice($in, start := -1)
"e"
slice($in, start := -3)
"c", "d", "e"
slice($in, end := -2)
"a", "b", "c", "d"
slice($in, start := 2, end := -2)
"b", "c", "d"
slice($in, start := -2, end := 2)
"d", "c", "b"
slice($in, start := -4, end := -2)
"b", "c", "d"
slice($in, start := -2, end := -4)
"d", "c", "b"
slice($in, start := -4, end := -2, step := 2)
"b", "d"
slice($in, start := -2, end := -4, step := -2)
"d", "b"
slice(("a", "b", "c", "d"), 0)
"a", "b", "c", "d"
slice((1 to 5), step := 2)
1, 3, 5

13.1.13 fn:subsequence

Changes in 4.0  

  1. The optional third argument can now be supplied as an empty sequence.  [Issue 895 PR 901 16 December 2023]

Summary

Returns the contiguous sequence of items in $input beginning at the position indicated by $start and continuing for the number of items indicated by $length.

Signature
fn:subsequence(
$inputas item()*,
$startas xs:double,
$lengthas xs:double?:= ()
) as item()*
Properties

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

Rules

In the two-argument case (or where the third argument is an empty sequence), the function returns:

$input[round($start) le position()]

In the three-argument case, the function returns:

$input[round($start) le position() 
         and position() lt round($start) + round($length)]
Formal Equivalent

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

filter(
  $input,
  if (empty($length)) then (
    fn($item, $pos) { round($start) le $pos }
  ) else (
    fn($item, $pos) { round($start) le $pos and $pos lt round($start) + round($length) }
  )
)
Notes

The first item of a sequence is located at position 1, not position 0.

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

In the two-argument case, the function returns a sequence comprising those items of $input whose 1-based position is greater than or equal to $start (rounded to an integer). No error occurs if $start is zero or negative.

In the three-argument case, The function returns a sequence comprising those items of $input whose 1-based position is greater than or equal to $start (rounded to an integer), and less than the sum of $start and $length (both rounded to integers). No error occurs if $start is zero or negative, or if $start plus $length exceeds the number of items in the sequence, or if $length is negative.

As a consequence of the general rules, if $start is -INF and $length is +INF, then fn:round($start) + fn:round($length) is NaN; since position() lt NaN always returns false, the result is an empty sequence.

The reason the function accepts arguments of type xs:double is that many computations on untyped data return an xs:double result; and the reason for the rounding rules is to compensate for any imprecision in these floating-point computations.

The first item of a sequence is located at position 1, not position 0.

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

In the two-argument case, the function returns a sequence comprising those items of $input whose 1-based position is greater than or equal to $start (rounded to an integer). No error occurs if $start is zero or negative.

In the three-argument case, The function returns a sequence comprising those items of $input whose 1-based position is greater than or equal to $start (rounded to an integer), and less than the sum of $start and $length (both rounded to integers). No error occurs if $start is zero or negative, or if $start plus $length exceeds the number of items in the sequence, or if $length is negative.

As a consequence of the general rules, if $start is -INF and $length is +INF, then fn:round($start) + fn:round($length) is NaN; since position() lt NaN always returns false, the result is an empty sequence.

The reason the function accepts arguments of type xs:double is that many computations on untyped data return an xs:double result; and the reason for the rounding rules is to compensate for any imprecision in these floating-point computations.

Examples
Variables
let $seq := ("item1", "item2", "item3", "item4", "item5")
ExpressionResult
subsequence($seq, 4)
"item4", "item5"
subsequence($seq, 3, 2)
"item3", "item4"

13.1.14 fn:tail

Summary

Returns all but the first item in a sequence.

Signature
fn:tail(
$inputas item()*
) as item()*
Properties

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

Rules

The function all items in $input except the first, retaining order.

Formal Equivalent

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

filter($input, fn($item, $pos) { $pos gt 1 })
Notes

If $input is the empty sequence, or a sequence containing a single item, then the empty sequence is returned.

If $input is the empty sequence, or a sequence containing a single item, then the empty sequence is returned.

Examples
ExpressionResult
tail(1 to 5)
2, 3, 4, 5
tail(("a", "b", "c"))
"b", "c"
tail("a")
()
tail(())
()
tail([ 1, 2, 3 ])
()

13.1.15 fn:trunk

Changes in 4.0  

  1. New in 4.0  [Issue 97 PR 250]

Summary

Returns all but the last item in a sequence.

Signature
fn:trunk(
$inputas item()*
) as item()*
Properties

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

Rules

The function returns all items in $input except the last, retaining order.

Formal Equivalent

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

filter($input, fn($item, $pos) { $pos ne count($input) })
Notes

If $input is the empty sequence, or a sequence containing a single item, then the empty sequence is returned.

If $input is the empty sequence, or a sequence containing a single item, then the empty sequence is returned.

Examples
ExpressionResult
trunk(1 to 5)
1, 2, 3, 4
trunk(("a", "b", "c"))
"a", "b"
trunk("a")
()
trunk(())
()
trunk([ 1, 2, 3 ])
()

13.1.16 fn:unordered

Summary

Returns the items of $input in an ·implementation-dependent· order.

Signature
fn:unordered(
$inputas item()*
) as item()*
Properties

This function is ·nondeterministic-wrt-ordering·, ·context-independent·, and ·focus-independent·.

Rules

The function returns the items of $input in an ·implementation-dependent· order.

Notes

Query optimizers may be able to do a better job if the order of the output sequence is not specified. For example, when retrieving prices from a purchase order, if an index exists on prices, it may be more efficient to return the prices in index order rather than in document order.

This function does not guarantee that the resulting sequence will be in an order different from the input sequence. Many times the two sequences will be identical.

Query optimizers may be able to do a better job if the order of the output sequence is not specified. For example, when retrieving prices from a purchase order, if an index exists on prices, it may be more efficient to return the prices in index order rather than in document order.

This function does not guarantee that the resulting sequence will be in an order different from the input sequence. Many times the two sequences will be identical.

Examples
ExpressionResult
unordered((1, 2, 3, 4, 5))
(1, 2, 3, 4, 5)

(or some permutation thereof)

13.1.17 fn:void

Changes in 4.0  

  1. New in 4.0  [Issue 1029 PR 1032 25 February 2025]

Summary

Absorbs the argument.

Signature
fn:void(
$inputas item()*:= ()
) as empty-sequence()
Properties

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

Rules

The function absorbs the supplied $input argument and returns an empty sequence.

Notes

The function can be used to discard unneeded output of expressions (functions, third-party libraries, etc.).

It can also be used to discard results during development.

The function is utilized by built-in functions such as map:get to return an empty sequence for arbitrary input.

It is ·implementation-dependent· whether the supplied argument is evaluated or ignored. An implementation may decide to evaluate ·nondeterministic· expressions and ignore deterministic ones.

The function can be used to discard unneeded output of expressions (functions, third-party libraries, etc.).

It can also be used to discard results during development.

The function is utilized by built-in functions such as map:get to return an empty sequence for arbitrary input.

It is ·implementation-dependent· whether the supplied argument is evaluated or ignored. An implementation may decide to evaluate ·nondeterministic· expressions and ignore deterministic ones.

Examples
Expression:

void(1 to 1000000)

Result:
()
Expression:

array:get(array { 1, 2, 3 }, 4, void#1)

Result:
()

(Without the third argument, an error would be raised.)

Expression:

for $f in (identity#1, void#1) return $f(123)

Result:
123
Expression:
let $mapping := () 
return for-each(1 to 10, $mapping otherwise void#0)
Result:
()

(Indicates that if no mapping is supplied, all items are dropped.)

13.2 Comparison functions

The functions in this section perform comparisons between the items in one or more sequences.

FunctionMeaning
fn:atomic-equalDetermines whether two atomic items are equal, under the rules used for comparing keys in a map.
fn:deep-equal This function assesses whether two sequences are deep-equal to each other. To be deep-equal, they must contain items that are pairwise deep-equal; and for two items to be deep-equal, they must either be atomic items that compare equal, or nodes of the same kind, with the same name, whose children are deep-equal, or maps with matching entries, or arrays with matching members.
fn:compareReturns -1, 0, or 1, depending on whether the first value is less than, equal to, or greater than the second value.
fn:distinct-valuesReturns the values that appear in a sequence, with duplicates eliminated.
fn:duplicate-valuesReturns the values that appear in a sequence more than once.
fn:index-ofReturns a sequence of positive integers giving the positions within the sequence $input of items that are equal to $target.
fn:starts-with-subsequenceDetermines whether one sequence starts with another, using a supplied callback function to compare items.
fn:ends-with-subsequenceDetermines whether one sequence ends with another, using a supplied callback function to compare items.
fn:contains-subsequenceDetermines whether one sequence contains another as a contiguous subsequence, using a supplied callback function to compare items.

13.2.1 fn:atomic-equal

Changes in 4.0  

  1. New in 4.0. The function is identical to the internal op:same-key function in 3.1

Summary

Determines whether two atomic items are equal, under the rules used for comparing keys in a map.

Signature
fn:atomic-equal(
$value1as xs:anyAtomicType,
$value2as xs:anyAtomicType
) as xs:boolean
Properties

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

Rules

The function fn:atomic-equal is used to compare two atomic items for equality. This function has the following properties (which do not all apply to the eq operator):

  • Any two atomic items can be compared, regardless of their type.

  • No dynamic error is ever raised (the result is either true or false).

  • The result of the comparison never depends on the static or dynamic context.

  • Every value (including NaN) is equal to itself.

  • The comparison is symmetric: if A equals B, then B equals A.

  • The comparison is transitive: if A equals B and B equals C, then A equals C.

The function returns true if and only if one of the following conditions is true:

  1. All of the following conditions are true:

    1. $value1 is an instance of xs:string, xs:anyURI, or xs:untypedAtomic

    2. $value2 is an instance of xs:string, xs:anyURI, or xs:untypedAtomic

    3. fn:codepoint-equal($value1, $value2)

    Note:

    Strings are compared without any dependency on collations.

  2. All of the following conditions are true:

    1. $value1 is an instance of xs:decimal, xs:double, or xs:float

    2. $value2 is an instance of xs:decimal, xs:double, or xs:float

    3. One of the following conditions is true:

      1. Both $value1 and $value2 are NaN

        Note:

        xs:double('NaN') is the same key as xs:float('NaN')

      2. Both $value1 and $value2 are positive infinity

        Note:

        xs:double('INF') is the same key as xs:float('INF')

      3. Both $value1 and $value2 are negative infinity

        Note:

        xs:double('-INF') is the same key as xs:float('-INF')

      4. $value1 and $value2 when converted to decimal numbers with no rounding or loss of precision are mathematically equal.

        Note:

        Every instance of xs:double, xs:float, and xs:decimal can be represented exactly as a decimal number provided enough digits are available both before and after the decimal point. Unlike the eq relation, which converts both operands to xs:double values, possibly losing precision in the process, this comparison is transitive.

        Note:

        Positive and negative zero compare equal.

  3. All of the following conditions are true:

    1. One of the following conditions is true:

      1. $value1 and $value2 are both instances of xs:date.

      2. $value1 and $value2 are both instances of xs:time.

      3. $value1 and $value2 are both instances of xs:dateTime.

      4. $value1 and $value2 are both instances of xs:gYear.

      5. $value1 and $value2 are both instances of xs:gYearMonth.

      6. $value1 and $value2 are both instances of xs:gMonth.

      7. $value1 and $value2 are both instances of xs:gMonthDay.

      8. $value1 and $value2 are both instances of xs:gDay.

    2. One of the following conditions is true:

      1. Both $value1 and $value2 have a timezone

      2. Neither $value1 nor $value2 has a timezone

    3. $value1 eq $value2

    Note:

    Values having a timezone are never equal to values without one. The implicit timezone is not used.

  4. All of the following conditions are true:

    1. One of the following conditions is true:

      1. $value1 and $value2 are both instances of xs:boolean.

      2. $value1 and $value2 are both instances of xs:QName.

      3. $value1 and $value2 are both instances of xs:NOTATION.

      4. $value1 and $value2 are both instances of xs:duration.

      5. $value1 and $value2 are both instances of xs:hexBinary.

      6. $value1 and $value2 are both instances of xs:base64Binary.

    2. $value1 eq $value2

Notes

The internal function op:same-key was introduced in an earlier version of this specification for comparing keys within a map. In this version of the specification, the functionality is unchanged, but the function is exposed so that it is available directly to applications.

The function is used to assess whether two atomic items are considered to be duplicates when used as keys in a map. A map cannot contain two separate entries whose keys are the same as defined by this function. The function is also used when matching keys in functions such as map:get and map:remove.

The rules for comparing keys in a map are chosen to ensure that the comparison is:

The internal function op:same-key was introduced in an earlier version of this specification for comparing keys within a map. In this version of the specification, the functionality is unchanged, but the function is exposed so that it is available directly to applications.

The function is used to assess whether two atomic items are considered to be duplicates when used as keys in a map. A map cannot contain two separate entries whose keys are the same as defined by this function. The function is also used when matching keys in functions such as map:get and map:remove.

The rules for comparing keys in a map are chosen to ensure that the comparison is:

  • Context-free: there is no dependency on the static or dynamic context

  • Error-free: any two atomic items can be compared, and the result is either true or false, never an error

  • Transitive: if A is the same key as B, and B is the same key as C, then A is the same key as C.

Two atomic items may be distinguishable even though they are equal under this comparison. For example: they may have different type annotations; dates and times may have different timezones; xs:QName values may have different prefixes.

Unlike the eq operator and the fn:deep-equal function, xs:hexBinary and xs:base64Binary values are considered distinct. This decision was made in order to preserve backwards compatibility: if the values were treated as interchangeable, it would become impossible to construct certain maps that could be validly constructed using earlier versions of the specification, and it would be difficult to make maps fully interoperable between processors supporting different language versions, for example when calling fn:transform.

As always, any algorithm that delivers the right result is acceptable. For example, when testing whether an xs:double value D is the same key as an xs:decimal value that has N significant digits, it is not necessary to know all the digits in the decimal expansion of D to establish the result: computing the first N+1 significant digits (or indeed, simply knowing that there are more than N significant digits) is sufficient.

Two atomic items may be distinguishable even though they are equal under this comparison. For example: they may have different type annotations; dates and times may have different timezones; xs:QName values may have different prefixes.

Unlike the eq operator and the fn:deep-equal function, xs:hexBinary and xs:base64Binary values are considered distinct. This decision was made in order to preserve backwards compatibility: if the values were treated as interchangeable, it would become impossible to construct certain maps that could be validly constructed using earlier versions of the specification, and it would be difficult to make maps fully interoperable between processors supporting different language versions, for example when calling fn:transform.

As always, any algorithm that delivers the right result is acceptable. For example, when testing whether an xs:double value D is the same key as an xs:decimal value that has N significant digits, it is not necessary to know all the digits in the decimal expansion of D to establish the result: computing the first N+1 significant digits (or indeed, simply knowing that there are more than N significant digits) is sufficient.

Examples
Expression:

atomic-equal(3, 3)

Result:
true()
Expression:

atomic-equal(3, 3e0)

Result:
true()
Expression:

atomic-equal(3.1, 3.1e0)

Result:
false()
Expression:

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

Result:
true()
Expression:

atomic-equal("a", "a")

Result:
true()
Expression:

atomic-equal("a", "A")

Result:
false()
Expression:

atomic-equal("a", xs:untypedAtomic("a"))

Result:
true()
Expression:
atomic-equal(
  "https://www.w3.org/",
  xs:anyURI("https://www.w3.org/")
)
Result:
true()
Expression:

atomic-equal(12, "12")

Result:
false()

13.2.2 fn:deep-equal

Changes in 4.0  

  1. When comments and processing instructions are ignored, any text nodes either side of the comment or processing instruction are now merged prior to comparison.  [Issue 930 PR 933 16 January 2024]

  2. The $options parameter has been added, absorbing the $collation parameter.  [Issues 934 1167 PR 1191 21 May 2024]

  3. A callback function can be supplied for comparing individual items.  [Issues 99 1142 PRs 1120 1150 9 April 2024]

Summary

This function assesses whether two sequences are deep-equal to each other. To be deep-equal, they must contain items that are pairwise deep-equal; and for two items to be deep-equal, they must either be atomic items that compare equal, or nodes of the same kind, with the same name, whose children are deep-equal, or maps with matching entries, or arrays with matching members.

Signature
fn:deep-equal(
$input1as item()*,
$input2as item()*,
$optionsas (xs:string | map(*))?:= {}
) as xs:boolean
Properties

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

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

Rules

The $options argument, if present, defines additional parameters controlling how the comparison is done. If it is supplied as a map, then the ·option parameter conventions· apply.

For backwards compatibility reasons, the $options argument can also be set to a string containing a collation name. Supplying a string $S for this argument is equivalent to supplying the map { 'collation': $S }. Omitting the argument, or supplying the empty sequence, is equivalent to supplying an empty map.

If the two sequences ($input1 and $input2) are both empty, the function returns true.

If the two sequences are of different lengths, the function returns false.

If the two sequences are of the same length, the comparison is controlled by the ordered option:

  • By default, the option is true: The function returns true if and only if every item in the sequence $input1 is deep-equal to the item at the same position in the sequence $input2.

  • If the option is set to false, the function returns false if and only if every item in the sequence $input1 is deep-equal to an item at some position in the sequence $input2, and vice versa.

The rules for deciding whether two items are deep-equal appear below.

The entries that may appear in the $options map are as follows. The detailed rules for the interpretation of each option appear later.

record(
base-uri?as xs:boolean,
collation?as xs:string,
comments?as xs:boolean,
debug?as xs:boolean,
id-property?as xs:boolean,
idrefs-property?as xs:boolean,
in-scope-namespaces?as xs:boolean,
items-equal?as fn(item(), item()) as xs:boolean?,
namespace-prefixes?as xs:boolean,
nilled-property?as xs:boolean,
normalization-form?as xs:string?,
ordered?as xs:boolean,
processing-instructions?as xs:boolean,
timezones?as xs:boolean,
type-annotations?as xs:boolean,
type-variety?as xs:boolean,
typed-values?as xs:boolean,
unordered-elements?as xs:QName*,
whitespace?as enum("preserve", "strip", "normalize")
)
KeyMeaning

base-uri?

Determines whether the base-uri of a node is significant.
  • Type: xs:boolean

  • Default: false

collation?

Identifies a collation which is used at all levels of recursion when strings are compared (but not when names are compared), according to the rules in 5.3.6 Choosing a collation. If the argument is not supplied, or if it is empty, then the default collation from the dynamic context of the caller is used.
  • Type: xs:string

  • Default: fn:default-collation()

comments?

Determines whether comments are significant.
  • Type: xs:boolean

  • Default: false

debug?

Requests diagnostics in the case where the function returns false. When this option is set and the two inputs are found to be not equal, the implementation should output messages (in an implementation-dependent format and to an implementation-dependent destination) indicating the nature of the differences that were found.
  • Type: xs:boolean

  • Default: false

id-property?

Determines whether the id property of elements and attributes is significant.
  • Type: xs:boolean

  • Default: false

idrefs-property?

Determines whether the idrefs property of elements and attributes is significant.
  • Type: xs:boolean

  • Default: false

in-scope-namespaces?

Determines whether the in-scope namespaces of elements are significant.
  • Type: xs:boolean

  • Default: false

items-equal?

A user-supplied function to test whether two items are considered equal. The function can return true or false to indicate that two items are or are not equal, overriding the normal rules that would apply to those items; or it can return an empty sequence, to indicate that the normal rules should be followed. Note that returning () is not equivalent to returning false.
  • Type: fn(item(), item()) as xs:boolean?

  • Default: fn:void#0

namespace-prefixes?

Determines whether namespace prefixes in xs:QName values (particularly the names of elements and attributes) are significant.
  • Type: xs:boolean

  • Default: false

nilled-property?

Determines whether the nilled property of elements and attributes is significant.
  • Type: xs:boolean

  • Default: false

normalization-form?

If present, indicates that text and attributes are converted to the specified Unicode normalization form prior to comparison. The value is as for the corresponding argument of fn:normalize-unicode.
  • Type: xs:string?

  • Default: ()

ordered?

Controls whether the top-level order of the items of the input sequences is considered.
  • Type: xs:boolean

  • Default: true

processing-instructions?

Determines whether processing instructions are significant.
  • Type: xs:boolean

  • Default: false

timezones?

Determines whether timezones in date/time values are significant.
  • Type: xs:boolean

  • Default: false

type-annotations?

Determines whether type annotations are significant.
  • Type: xs:boolean

  • Default: false

type-variety?

Determines whether the variety of the type annotation of an element (whether it has complex content or simple content) is significant.
  • Type: xs:boolean

  • Default: true

typed-values?

Determines whether nodes are compared using their typed values rather than their string values.
  • Type: xs:boolean

  • Default: true

unordered-elements?

A list of QNames of elements considered to be unordered: that is, their child elements may appear in any order.
  • Type: xs:QName*

  • Default: ()

whitespace?

Determines the extent to which whitespace is treated as significant. The value preserve retains all whitespace. The value strip ignores text nodes consisting entirely of whitespace. The value normalize ignores whitespace text nodes in the same way as the strip option, and additionally compares text and attribute nodes after normalizing whitespace in accordance with the rules of the fn:normalize-space function. The detailed rules, given below, also take into account type annotations and xml:space attributes.
  • Type: enum("preserve", "strip", "normalize")

  • Default: preserve

Note:

As a general rule for boolean options (but not invariably), the value true indicates that the comparison is more strict.

In the following rules, where a recursive call on fn:deep-equal is made, this is assumed to use the same values of $options as the original call.

The rules reference a function equal-strings which compares two xs:string or xs:anyURI values as follows:

  1. If the whitespace option is set to normalize, then each string is processed by calling the fn:normalize-space function.

  2. If the normalization-form option is present, each string is then normalized by calling the fn:normalize-unicode function, supplying the specified normalization form.

  3. The two strings are then compared for equality under the requested collation.

More formally, the equal-strings function is equivalent to the following implementation in XQuery:

declare function equal-strings(
  $string1   as xs:string,
  $string2   as xs:string, 
  $options   as map(*)
) as xs:boolean {
  let $n1 := if ($options?normalization-form)
             then normalize-unicode(?, $options?normalization-form) 
             else identity#1
  let $n2 := if ($options?whitespace = "normalize")
             then normalize-space#1 
             else identity#1               
  return compare($n1($n2($string1)), $n1($n2($string2)), $options?collation) eq 0    
}

The rules for deciding whether two items $i1 and $i2 are deep-equal are as follows.

The two items are first compared using the function supplied in the items-equal option. If this returns true then the items are deep-equal. If it returns false then the items are not deep-equal. If it returns an empty sequence (which is always the case if the option is not explicitly specified) then the two items are deep-equal if one or more of the following conditions are true:

  1. All of the following conditions are true:

    1. $i1 is an atomic item.

    2. $i2 is an atomic item.

    3. Either the type-annotations option is false, or both atomic items have the same type annotation.

    4. One of the following conditions is true:

      1. If both $i1 and $i2 are instances of xs:string, xs:untypedAtomic, or xs:anyURI, equal-strings($i1, $i2, $collation, $options) returns true.

      2. If both $i1 and $i2 are instances of xs:date, xs:time or xs:dateTime, $i1 eq $i2 returns true.

      3. If both $i1 and $i2 are instances of xs:hexBinary or xs:base64Binary, $i1 eq $i2 returns true.

      4. Otherwise, fn:atomic-equal($i1, $i2) returns true.

      Note:

      If $i1 and $i2 are not comparable, that is, if the expression ($i1 eq $i2) would raise an error, then the function returns false; it does not report an error.

    5. One of the following conditions is true:

      1. Option namespace-prefixes is false.

      2. Neither $i1 nor $i2 is of type xs:QName or xs:NOTATION.

      3. $i1 and $i2 are qualified names with the same namespace prefix.

    6. One of the following conditions is true:

      1. Option timezones is false.

      2. Neither $i1 nor $i2 is of type xs:date, xs:time, xs:dateTime, xs:gYear, xs:gYearMonth, xs:gMonth, xs:gMonthDay, or xs:gDay.

      3. Neither $i1 nor $i2 has a timezone component.

      4. Both $i1 and $i2 have a timezone component and the timezone components are equal.

  2. All of the following conditions are true:

    1. $i1 is a map.

    2. $i2 is a map.

    3. Both maps have the same number of entries.

    4. For every entry in the first map, there is an entry in the second map that:

      1. has the ·same key· (note that the collation is not used when comparing keys), and

      2. has the same associated value (compared using the fn:deep-equal function, recursively).

    Note:

    It is not required that the order of entries in the two maps should be the same.

  3. All the following conditions are true:

    1. $i1 is an array.

    2. $i2 is an array.

    3. Both arrays have the same number of members (array:size($i1) eq array:size($i2)).

    4. Members in the same position of both arrays are deep-equal to each other: that is, every $p in 1 to array:size($i1) satisfies deep-equal($i1($p), $i2($p), $collation, $options).

  4. All the following conditions are true:

    1. $i1 is a function item and is not a map or array.

    2. $i2 is a function item and is not a map or array.

    3. $i1 and $i2 have the same function identity. The concept of function identity is explained in Section 2.9.4 Function ItemsDM.

  5. All the following conditions are true:

    1. $i1 is a node.

    2. $i2 is a node.

    3. Both nodes have the same node kind.

    4. Either the base-uri option is false, or both nodes have the same value for their base URI property, or both nodes have an absent base URI.

    5. Let significant-children($parent) be the sequence of nodes obtained by applying the following steps to the children of $parent, in turn:

      1. Comment nodes are discarded if the option comments is false.

      2. Processing instruction nodes are discarded if the option processing-instructions is false.

      3. Adjacent text nodes are merged.

      4. Whitespace-only text nodes are discarded if both the following conditions are true:

        1. The option whitespace is set to strip or normalize; and

        2. The text node is not within the scope of an element that has the attribute xml:space="preserve".

        Note:

        Whitespace text nodes will already have been discarded if $parent is a schema-validated element node whose type annotation is a complex type with an element-only or empty content model.

    6. One of the following conditions is true.

      1. Both nodes are document nodes, and the sequence significant-children($i1) is deep-equal to the sequence significant-children($i2).

      2. Both nodes are element nodes, and all the following conditions are true:

        1. The two nodes have the same name, that is (node-name($i1) eq node-name($i2)).

        2. Either the option namespace-prefixes is false, or both element names have the same prefix.

        3. Either the option in-scope-namespaces is false, or both element nodes have the same in-scope namespace bindings.

        4. Either the option type-annotations is false, or both element nodes have the same type annotation.

        5. Either the option id-property is false, or both element nodes have the same value for their is-id property.

        6. Either the option idrefs-property is false, or both element nodes have the same value for their is-idrefs property.

        7. Either the option nilled-property is false, or both element nodes have the same value for their nilled property.

        8. One of the following conditions is true:

          1. The option type-variety is false.

          2. Both nodes are annotated as having simple content. For this purpose simple content means either a simple type or a complex type with simple content.

          3. Both nodes are annotated as having complex content. For this purpose complex content means a complex type whose variety is mixed, element-only, or empty.

          Note:

          It is a consequence of this rule that, by default, validating a document D against a schema will usually (but not necessarily) result in a document that is not deep-equal to D. The exception is when the schema allows all elements to have mixed content.

        9. The two nodes have the same number of attributes, and for every attribute $a1 in $i1/@* there exists an attribute $a2 in $i2/@* such that node-name($a1) eq node-name($a2) and $a1 and $a2 are deep-equal.

          Note:

          Attributes, like other items, may be compared using the supplied items-equal function. However, this function will not be called to compare two attribute nodes unless they have the same name.

        10. One of the following conditions holds:

          1. Both element nodes are annotated as having simple content (as defined above), the typed-values option is true, and the typed value of $i1 is deep-equal to the typed value of $i2.

            Note:

            The typed value of an element node is used only when the element has simple content, which means that no error can occur as a result of atomizing a node with no typed value.

          2. Both element nodes are annotated as having simple content (as defined above), the typed-values option is false, and the equal-strings function returns true when applied to the string value of $i1 and the string value of $i2.

          3. Both element nodes have a type annotation that is a complex type with element-only, mixed, or empty content, the (common) element name is not present in the unordered-elements option, and the sequence significant-children($i1) is deep-equal to the sequence significant-children($i2).

          4. Both element nodes have a type annotation that is a complex type with element-only, mixed, or empty content, the (common) element name is present in the unordered-elements option, and the sequence significant-children($i1) is deep-equal to some permutation of the sequence significant-children($i2).

            Note:

            Elements annotated as xs:untyped fall into this category.

            Including an element name in the unordered-elements list is unlikely to be useful except when the relevant elements have element-only content, but this is not a requirement: the rules apply equally to elements with mixed content, or even (trivially) to elements with empty content.

      3. Both nodes are attribute nodes, and all the following conditions are true:

        1. The two attribute nodes have the same name, that is (node-name($i1) eq node-name($i2)).

        2. Either the option namespace-prefixes is false, or both attribute names have the same prefix.

        3. Either the option type-annotations is false, or both attribute nodes have the same type annotation.

        4. Either the option id-property is false, or both attribute nodes have the same value for their is-id property.

        5. Either the option idrefs-property is false, or both attribute nodes have the same value for their is-idrefs property.

        6. Let T be true if the option typed-value is true and both attributes $i1 and $i2 have a type annotation other than xs:untypedAtomic.

          Then either T is true and the typed value of $i1 is deep-equal to the typed value of $i2, or T is false and the equal-strings function returns true when applied to the string value of $i1 and the string value of $i2.

      4. Both nodes are processing instruction nodes, and all the following conditions are true:

        1. The two nodes have the same name, that is (node-name($i1) eq node-name($i2)).

        2. The equal-strings function returns true when applied to the string value of $i1 and the string value of $i2.

      5. Both nodes are namespace nodes, and all the following conditions are true:

        1. The two nodes either have the same name or are both nameless, that is fn:deep-equal(node-name($i1), node-name($i2)).

        2. The string value of $i1 is equal to the string value of $i2 when compared using the Unicode codepoint collation.

        Note:

        Namespace nodes are not considered directly unless they appear in the top-level sequences passed explicitly to the fn:deep-equal function.

      6. Both nodes are comment nodes, and the equal-strings function returns true when applied to their string values.

      7. Both nodes are text nodes, and the equal-strings function returns true when applied to their string values.

In all other cases the result is false.

Error Conditions

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

A dynamic 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

By default, whitespace in text nodes and attributes is considered significant. There are various ways whitespace differences can be ignored:

By default, whitespace in text nodes and attributes is considered significant. There are various ways whitespace differences can be ignored:

  • If nodes have been schema-validated, setting the typed-values option to true causes the typed values rather than the string values to be compared. This will typically cause whitespace to be ignored except where the type of the value is xs:string.

  • Setting the whitespace option to normalize causes all text and attribute nodes to have leading and trailing whitespace removed, and intermediate whitespace reduced to a single character.

By default, two nodes are not required to have the same type annotation, and they are not required to have the same in-scope namespaces. They may also differ in their parent, their base URI, and the values returned by the is-id and is-idrefs accessors (see Section 4.5 is-id AccessorDM and Section 4.6 is-idrefs AccessorDM). The order of children is significant, but the order of attributes is insignificant.

By default, the contents of comments and processing instructions are significant only if these nodes appear directly as items in the two sequences being compared. The content of a comment or processing instruction that appears as a descendant of an item in one of the sequences being compared does not affect the result. In previous versions of this specification, the presence of a comment or processing instruction, if it caused text to be split across two text nodes, might affect the result; this has been changed in 4.0 so that adjacent text nodes are merged after comments and processing instructions have been stripped.

Comparing items of different kind (for example, comparing an atomic item to a node, or a map to an array, or an integer to an xs:date) returns false, it does not return an error. So the result of fn:deep-equal(1, current-dateTime()) is false.

The items-equal callback function may be used to override the default rules for comparing individual items. For example, it might return true unconditionally when comparing two @timestamp attributes, if there is no expectation that the two trees will have identical timestamps. Given two nodes $n1 and $n2, it might compare them using the is operator, so that instead of comparing the descendants of the two nodes, the function simply checks whether they are the same node. Given two function items $f1 and $f2 it might return true unconditionally, knowing that there is no effective way to test if the functions are equivalent. Given two numeric values, it might return true if they are equal to six decimal places.

It is good practice for the items-equal callback function to be reflexive, symmetric, and transitive; if it is not, then the fn:deep-equal function itself will lack these qualities. Reflexive means that every item (including NaN) should be equal to itself; symmetric means that items-equal(A, B) should return the same result as items-equal(B, A), and transitive means that items-equal(A, B) and items-equal(B, C) should imply items-equal(A, C).

Setting the ordered option to false or supplying the unordered-elements option may result in poor performance when comparing long sequences, especially if the items-equal callback function is supplied.

By default, two nodes are not required to have the same type annotation, and they are not required to have the same in-scope namespaces. They may also differ in their parent, their base URI, and the values returned by the is-id and is-idrefs accessors (see Section 4.5 is-id AccessorDM and Section 4.6 is-idrefs AccessorDM). The order of children is significant, but the order of attributes is insignificant.

By default, the contents of comments and processing instructions are significant only if these nodes appear directly as items in the two sequences being compared. The content of a comment or processing instruction that appears as a descendant of an item in one of the sequences being compared does not affect the result. In previous versions of this specification, the presence of a comment or processing instruction, if it caused text to be split across two text nodes, might affect the result; this has been changed in 4.0 so that adjacent text nodes are merged after comments and processing instructions have been stripped.

Comparing items of different kind (for example, comparing an atomic item to a node, or a map to an array, or an integer to an xs:date) returns false, it does not return an error. So the result of fn:deep-equal(1, current-dateTime()) is false.

The items-equal callback function may be used to override the default rules for comparing individual items. For example, it might return true unconditionally when comparing two @timestamp attributes, if there is no expectation that the two trees will have identical timestamps. Given two nodes $n1 and $n2, it might compare them using the is operator, so that instead of comparing the descendants of the two nodes, the function simply checks whether they are the same node. Given two function items $f1 and $f2 it might return true unconditionally, knowing that there is no effective way to test if the functions are equivalent. Given two numeric values, it might return true if they are equal to six decimal places.

It is good practice for the items-equal callback function to be reflexive, symmetric, and transitive; if it is not, then the fn:deep-equal function itself will lack these qualities. Reflexive means that every item (including NaN) should be equal to itself; symmetric means that items-equal(A, B) should return the same result as items-equal(B, A), and transitive means that items-equal(A, B) and items-equal(B, C) should imply items-equal(A, C).

Setting the ordered option to false or supplying the unordered-elements option may result in poor performance when comparing long sequences, especially if the items-equal callback function is supplied.

Examples
Variables
let $at := <attendees>
  <name last="Parker" first="Peter"/>
  <name last="Barker" first="Bob"/>
  <name last="Parker" first="Peter"/>
</attendees>
Expression:

deep-equal($at, $at/*)

Result:
false()
Expression:

deep-equal($at/name[1], $at/name[2])

Result:
false()
Expression:

deep-equal($at/name[1], $at/name[3])

Result:
true()
Expression:

deep-equal($at/name[1], 'Peter Parker')

Result:
false()
Expression:
deep-equal(
  $at//name[@first="Bob"], 
  $at//name[@last="Barker"],
  options := { 'items-equal': op('is') } 
)
Result:
true()

(Tests whether the two input sequences contain exactly the same nodes.)

Expression:

deep-equal([ 1, 2, 3], [ 1, 2, 3 ])

Result:
true()
Expression:

deep-equal((1, 2, 3), [ 1, 2, 3 ])

Result:
false()
Expression:
deep-equal(
  { 1: 'a', 2: 'b' },
  { 2: 'b', 1: 'a' }
)
Result:
true()
Expression:
deep-equal(
  (1, 2, 3, 4),
  (1, 4, 3, 2),
  options := { 'ordered': false() }
)
Result:
true()
Expression:
deep-equal(
  (1, 1, 2, 3),
  (1, 2, 3, 3),
  options := { 'ordered': false() }
)
Result:
false()
Expression:
deep-equal(
  parse-xml("<a xmlns='AA'/>"),
  parse-xml("<p:a xmlns:p='AA'/>")
)
Result:
true()

(By default, namespace prefixes are ignored).

Expression:
deep-equal(
  parse-xml("<a xmlns='AA'/>"),
  parse-xml("<p:a xmlns:p='AA'/>"),
  options := { 'namespace-prefixes': true() }
)
Result:
false()

(False because the namespace prefixes differ).

Expression:
deep-equal(
  parse-xml("<a xmlns='AA'/>"),
  parse-xml("<p:a xmlns:p='AA'/>"),
  options := { 'in-scope-namespaces': true() }
)
Result:
false()

(False because the in-scope namespace bindings differ).

Expression:
deep-equal(
  parse-xml("<a><b/><c/></a>"),
  parse-xml("<a><c/><b/></a>")
)
Result:
false()

(By default, order of elements is significant).

Expression:
deep-equal(
  parse-xml("<a><b/><c/></a>"),
  parse-xml("<a><c/><b/></a>"),
  options := { 'unordered-elements': xs:QName('a') }
)
Result:
true()

(The unordered-elements option means that the ordering of the children of a is ignored.)

Expression:
deep-equal(
  parse-xml("<para style='bold'><span>x</span></para>"),
  parse-xml("<para style=' bold'> <span>x</span></para>")
)
Result:
false()

(By default, both the leading whitespace in the style attribute and the whitespace text node preceding the span element are significant.)

Expression:
deep-equal(
  parse-xml("<para style='bold'><span>x</span></para>"),
  parse-xml("<para style=' bold'> <span>x</span></para>"),
  options := { 'whitespace': 'normalize' }
)
Result:
true()

(The whitespace option causes both the leading space in the attribute value and the whitespace preceding the span element to be ignored.)

Expression:
deep-equal(
  (1, 2, 3), 
  (1.0007, 1.9998, 3.0005),
  options := { 'items-equal': fn($x, $y) {
    if (($x, $y) instance of xs:numeric+) {
      abs($x - $y) lt 0.001
    }
  } }
)
Result:
true()

(For numeric values, the callback function tests whether they are approximately equal. For any other items, it returns an empty sequence, so the normal comparison rules apply.)

Expression:
deep-equal(
  (1, 2, 3, 4, 5), 
  (1, 2, 3, 8, 5),
  options := { 'items-equal': fn($x, $y) {
    trace((), `comparing { $x } and { $y }`)
  } }
)
Result:
false()

(The callback function traces which items are being compared, without changing the result of the comparison.)

13.2.3 fn:compare

Changes in 4.0  

  1. The function has been expanded in scope to handle comparison of values other than strings.  [Issue 893 PR 909 10 January 2024]

  2. The spec has been corrected to note that the function depends on the implicit timezone.  [Issue 1608  26 November 2024]

Summary

Returns -1, 0, or 1, depending on whether the first value is less than, equal to, or greater than the second value.

Signature
fn:compare(
$value1as xs:anyAtomicType?,
$value2as xs:anyAtomicType?,
$collationas xs:string?:= fn:default-collation()
) as xs:integer?
Properties

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

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

Rules

Compares two atomic items $value1 and $value2 for order, and returns the integer value -1, 0, or 1, depending on whether $value1 is less than, equal to, or greater than $value2, respectively.

This function differs from the operators lt, eq, and gt in that decimal values are not converted to doubles. This means that the comparison is fully transitive, which makes it safe for use in sorting algorithms. It is used to underpin sorting in XQuery 4.0 and XSLT 4.0, and is also available as a free-standing function in its own right.

If either $value1 or $value2 is the empty sequence, the function returns the empty sequence.

Otherwise, the result is determined as follows:

  1. If $value1 is an instance of xs:string, xs:anyURI or xs:untypedAtomic, and if $value2 is an instance of xs:string, xs:anyURI or xs:untypedAtomic, the values are compared as strings, and the result reflects the order according to the rules of the collation that is used.

    The collation is determined according to the rules in 5.3.6 Choosing a collation.

    When used with the default collation, the function defines the semantics of the eq, ne, gt, lt, le and ge operators on xs:string values.

  2. If both $value1 and $value2 are instances of xs:numeric, the function relies on a total order, which is defined as follows:

    1. A value $f of type xs:float is in all cases equal to the value xs:double($f). The remaining rules therefore only consider instances of xs:double and xs:decimal.

    2. NaN is equal to itself and less than any other value.

    3. Negative infinity is equal to itself and less than any other value except NaN.

    4. Positive infinity is equal to itself and greater than any other value.

    5. Negative zero is equal to positive zero.

    6. Other xs:double and xs:decimal values (that is, values other than the infinities, NaN, and negative zero) are ordered according to their mathematical magnitude, the comparison being done without any rounding or loss of precision. This effect can be achieved by converting xs:double values to xs:decimal using an implementation of xs:decimal that imposes no limits on precision or scale, or an implementation whose limits are such that all xs:double values can be represented precisely.

  3. If both $value1 and $value2 are instances of xs:boolean, then:

    1. -1 is returned if op:boolean-less-than($value1, $value2) returns true.

    2. 0 is returned if op:boolean-equal($value1, $value2) returns true.

    3. 1 is returned otherwise.

  4. If $value1 is an instance of xs:hexBinary or xs:base64Binary, and if $value2 is an instance of xs:hexBinary or xs:base64Binary, then:

    1. -1 is returned if op:binary-less-than($value1, $value2) returns true.

    2. 0 is returned if op:binary-equal($value1, $value2) returns true.

    3. 1 is returned otherwise.

  5. If both $value1 and $value2 are instances of xs:date, then:

    1. -1 is returned if op:date-less-than($value1, $value2) returns true.

    2. 0 is returned if op:date-equal($value1, $value2) returns true.

    3. 1 is returned otherwise.

  6. If both $value1 and $value2 are instances of xs:time, then:

    1. -1 is returned if op:time-less-than($value1, $value2) returns true.

    2. 0 is returned if op:time-equal($value1, $value2) returns true.

    3. 1 is returned otherwise.

  7. If both $value1 and $value2 are instances of xs:dateTime, then:

    1. -1 is returned if op:dateTime-less-than($value1, $value2) returns true.

    2. 0 is returned if op:dateTime-equal($value1, $value2) returns true.

    3. 1 is returned otherwise.

  8. If both $value1 and $value2 are instances of xs:dayTimeDuration, then:

    1. -1 is returned if op:dayTimeDuration-less-than($value1, $value2) returns true.

    2. 0 is returned if op:duration-equal($value1, $value2) returns true.

    3. 1 is returned otherwise.

  9. If both $value1 and $value2 are instances of xs:yearMonthDuration, then:

    1. -1 is returned if op:yearMonthDuration-less-than($value1, $value2) returns true.

    2. 0 is returned if op:duration-equal($value1, $value2) returns true.

    3. 1 is returned otherwise.

  10. For any other combination of types, a type error [err:XPTY0004]XP is raised.

Notes

For numeric values, consider the xs:double value written as 0.1e0 and the xs:decimal value written as 0.1: The mathematical magnitude of this xs:double value is 0.1000000000000000055511151231257827021181583404541015625. Therefore, compare(0.1e0, 0.1) returns +1. By contrast, 0.1e0 lt 0.1 is false and 0.1e0 eq 0.1 is true, because those expressions convert the xs:decimal value 0.1 to the xs:double value 0.1e0 before the comparison.

Although operations such as sorting and the fn:min and fn:max functions invoke fn:compare to perform numeric comparison, these functions in some cases treat NaN differently.

For numeric values, consider the xs:double value written as 0.1e0 and the xs:decimal value written as 0.1: The mathematical magnitude of this xs:double value is 0.1000000000000000055511151231257827021181583404541015625. Therefore, compare(0.1e0, 0.1) returns +1. By contrast, 0.1e0 lt 0.1 is false and 0.1e0 eq 0.1 is true, because those expressions convert the xs:decimal value 0.1 to the xs:double value 0.1e0 before the comparison.

Although operations such as sorting and the fn:min and fn:max functions invoke fn:compare to perform numeric comparison, these functions in some cases treat NaN differently.

Examples
Expression:

compare('abc', 'abc')

Result:
0
Expression:

compare('Strasse', 'Straße')

Result:
-1
Expression:

compare('Strasse', 'Straße')

Result:
0

(Assuming the default collation equates “ss” and the German letter “ß”.)

Expression:
compare(
  'Strasse',
  'Straße',
  collation({ 'lang': 'de', 'strength': 'primary' })
)
Result:
0

(The specified collation equates “ss” and the German letter “ß”.)

Expression:

compare('text', parse-xml('<xml>text</xml>'))

Result:
0
Expression:

compare(9, 10)

Result:
-1
Expression:

compare(123, 123.0)

Result:
0
Expression:

compare(xs:double('NaN'), xs:float('NaN'))

Result:
0
Expression:

compare(xs:double('NaN'), xs:double('-INF'))

Result:
-1
Expression:

compare(xs:double('-INF'), -23)

Result:
-1
Expression:

compare(1, 1e0)

Result:
0
Expression:

compare(1.1, 1.1e0)

Result:
-1
Expression:

compare(1.2, 1.2e0)

Result:
+1
Expression:

compare(9999, xs:double('INF'))

Result:
-1
Expression:

compare(false(), true())

Result:
-1
Expression:

compare(xs:hexBinary(''), xs:base64Binary(''))

Result:
0
Expression:

compare(xs:time('23:59:59'), xs:time('00:00:00'))

Result:
1
Expression:

compare(xs:date('2001-01-01+01:00'), xs:date('2001-01-01+00:00'))

Result:
-1

13.2.4 fn:distinct-values

Changes in 4.0  

  1. Changed in 4.0 to use transitive equality comparisons for numeric values.

  2. The order of results is now prescribed; it was previously implementation-dependent.  [Issue 628 PR 987]

Summary

Returns the values that appear in a sequence, with duplicates eliminated.

Signature
fn:distinct-values(
$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

The function returns the sequence that results from removing from $values all but one of a set of values that are considered equal to one another. Two items $J and $K in the input sequence (after atomization, as required by the function signature) are considered equal if fn:deep-equal($J, $K, $coll) is true, where $coll is the collation selected according to the rules in 5.3.6 Choosing a collation. This collation is used when string comparison is required.

If ordering mode (in the static context) is ordered then:

  • For any set of values that compare equal, the one that is returned is the one that appears first in $values.

  • The items that are returned appear in the order in which they occur within $values.

By contrast, if ordering mode is unordered then:

Notes

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

Values of type xs:untypedAtomic are compared as if they were of type xs:string.

Values that cannot be compared, because the eq operator is not defined for their types, are considered to be distinct.

For xs:float and xs:double values, positive zero is equal to negative zero and, although NaN does not equal itself, if $values contains multiple NaN values a single NaN is returned.

If xs:dateTime, xs:date or xs:time values do not have a timezone, they are considered to have the implicit timezone provided by the dynamic context for the purpose of comparison. Note that xs:dateTime, xs:date or xs:time values can compare equal even if their timezones are different.

Editorial note 
Ordering mode has been dropped.

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

Values of type xs:untypedAtomic are compared as if they were of type xs:string.

Values that cannot be compared, because the eq operator is not defined for their types, are considered to be distinct.

For xs:float and xs:double values, positive zero is equal to negative zero and, although NaN does not equal itself, if $values contains multiple NaN values a single NaN is returned.

If xs:dateTime, xs:date or xs:time values do not have a timezone, they are considered to have the implicit timezone provided by the dynamic context for the purpose of comparison. Note that xs:dateTime, xs:date or xs:time values can compare equal even if their timezones are different.

Editorial note 
Ordering mode has been dropped.
Examples
ExpressionResult
distinct-values((1, 2.0, 3, 2))
1, 2.0, 3

(Assuming ordering mode is ordered.)

distinct-values((
  xs:untypedAtomic("cherry"),
  xs:untypedAtomic("plum"),
  xs:untypedAtomic("plum")
))
xs:untypedAtomic("cherry"), xs:untypedAtomic("plum")

(Assuming ordering mode is ordered.)

13.2.5 fn:duplicate-values

Changes in 4.0  

  1. New in 4.0  [Issue 123 PR 614]

  2. The order of results is now prescribed; it was previously implementation-dependent.  [Issue 628 PR 987]

Summary

Returns the values that appear in a sequence more than once.

Signature
fn:duplicate-values(
$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

The items of $values are compared against each other, according to the rules of fn:distinct-values and with $coll as the collation selected according to the rules in 5.3.6 Choosing a collation.

From each resulting set of values that are considered equal, one value will be returned if the set contains more than one value.

If ordering mode (in the static context) is ordered then:

  • For any set of values that compare equal, the one that is returned is the one that appears first in $values.

  • The items that are returned appear in the order in which they occur within $values.

By contrast, if ordering mode is unordered then:

Notes

The effect of the function is equivalent to the following XSLT expression:

<xsl:for-each-group select="$values" group-by="." collation="{ $collation }">
  <xsl:sequence select="current-group()[2]"/>
</xsl:for-each>

The effect of the function is equivalent to the following XSLT expression:

<xsl:for-each-group select="$values" group-by="." collation="{ $collation }">
  <xsl:sequence select="current-group()[2]"/>
</xsl:for-each>

The following XQuery expression is equivalent if no collation is specified (group by requires collation URIs to be static):

for $group in $values
group by $value := $group
where count($group) > 1
return $value

The following XQuery expression is equivalent if no collation is specified (group by requires collation URIs to be static):

for $group in $values
group by $value := $group
where count($group) > 1
return $value
Examples
Expression:

duplicate-values((1, 2, 3, 1.0, 1e0))

Result:
1

(If ordering mode is ordered the result will be the xs:integer value 1.)

Expression:

duplicate-values(1 to 100)

Result:
()
Expression:

duplicate-values(('1', <x>1</x>, '2', 2))

Result:
"1"

(The string "1" and the untyped value of the element node are considered equal, whereas the string "2" and the integer are considered unequal.)

Raise an error for duplicates in an ID sequence:

let $ids := duplicate-values(//@id)
where exists($ids)
return error((), 'Duplicate IDs found: ' || string-join($ids, ', '))

13.2.6 fn:index-of

Summary

Returns a sequence of positive integers giving the positions within the sequence $input of items that are equal to $target.

Signature
fn:index-of(
$inputas xs:anyAtomicType*,
$targetas xs:anyAtomicType,
$collationas xs:string?:= fn:default-collation()
) as xs:integer*
Properties

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

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

Rules

The function returns a sequence of positive integers giving the positions within the sequence $input of items that are equal to $target.

The collation used by this function is determined according to the rules in 5.3.6 Choosing a collation. This collation is used when string comparison is required.

The items in the sequence $input are compared with $target under the rules for the eq operator. Values of type xs:untypedAtomic are compared as if they were of type xs:string. Values that cannot be compared, because the eq operator is not defined for their types, are considered to be distinct. If an item compares equal, then the position of that item in the sequence $input is included in the result.

The first item in a sequence is at position 1, not position 0.

The result sequence is in ascending numeric order.

Notes

If $input is the empty sequence, or if no item in $input matches $target, then the function returns the empty sequence.

No error occurs if non-comparable values are encountered. So when comparing two atomic items, the effective boolean value of fn:index-of($a, $b) is true if $a and $b are equal, false if they are not equal or not comparable.

If $input is the empty sequence, or if no item in $input matches $target, then the function returns the empty sequence.

No error occurs if non-comparable values are encountered. So when comparing two atomic items, the effective boolean value of fn:index-of($a, $b) is true if $a and $b are equal, false if they are not equal or not comparable.

Examples
Expression:

index-of((10, 20, 30, 40), 35)

Result:
()
Expression:

index-of((10, 20, 30, 30, 20, 10), 20)

Result:
2, 5
Expression:
index-of(
  ("a", "sport", "and", "a", "pastime"),
  "a"
)
Result:
1, 4
Expression:
index-of(
  ("a", "b", "c"),
  "B",
  "http://www.w3.org/2005/xpath-functions/collation/html-ascii-case-insensitive"
)
Result:
2
Expression:

index-of(current-date(), 23)

Result:
()
Expression:

index-of([ 1, [ 5, 6 ], [ 6, 7 ] ], 6)

Result:
3, 4

(The array is atomized to a sequence of five integers).

If @a is an attribute of type xs:NMTOKENS whose string value is "red green blue", and whose typed value is therefore ("red", "green", "blue"), then fn:index-of(@a, "blue") returns 3. This is because the function calling mechanism atomizes the attribute node to produce a sequence of three xs:NMTOKEN values.

13.2.7 fn:starts-with-subsequence

Changes in 4.0  

  1. New in 4.0  [Issue 92 PR 222 1 November 2022]

Summary

Determines whether one sequence starts with another, using a supplied callback function to compare items.

Signature
fn:starts-with-subsequence(
$inputas item()*,
$subsequenceas item()*,
$compareas (fn(item(), item()) as xs:boolean?)?:= fn:deep-equal#2
) as xs:boolean
Properties

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

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

Rules

Informally, the function returns true if $input starts with $subsequence, when items are compared using the supplied (or default) $compare function.

Formal Equivalent

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

count($input) ge count($subsequence) and
every(for-each-pair($input, $subsequence, $compare))
Notes

There is no requirement that the $compare function should have the traditional qualities of equality comparison. The result is well-defined, for example, even if $compare is not transitive or not symmetric. A return value of () from the function is treated as false.

There is no requirement that the $compare function should have the traditional qualities of equality comparison. The result is well-defined, for example, even if $compare is not transitive or not symmetric. A return value of () from the function is treated as false.

Examples
Expression:

starts-with-subsequence((), ())

Result:
true()
Expression:

starts-with-subsequence(1 to 10, 1 to 5)

Result:
true()
Expression:

starts-with-subsequence(1 to 10, ())

Result:
true()
Expression:

starts-with-subsequence(1 to 10, 1 to 10)

Result:
true()
Expression:

starts-with-subsequence(1 to 10, 1)

Result:
true()
Expression:
starts-with-subsequence(
  1 to 10,
  101 to 105,
  fn($x, $y) { $x mod 100 = $y mod 100 }
)
Result:
true()
Expression:
starts-with-subsequence(
  ("A", "B", "C"),
  ("a", "b"),
  fn($x, $y) {
    compare(
      $x,
      $y,
      "http://www.w3.org/2005/xpath-functions/collation/html-ascii-case-insensitive"
    ) eq 0
  }
)
Result:
true()
Expression:
let $p := parse-xml("<doc><chap><p/><p/></chap></doc>")//p[2]
return starts-with-subsequence(
  $p/ancestor::*[1],
  $p/parent::*,
  op("is")
)
Result:
true()
Expression:

starts-with-subsequence(10 to 20, 1 to 5, op("gt"))

Result:
true()
Expression:
starts-with-subsequence(
  ("Alpha", "Beta", "Gamma"),
  ("A", "B"),
  starts-with#2
)
Result:
true()
Expression:
starts-with-subsequence(
  ("Alpha", "Beta", "Gamma", "Delta"),
  1 to 3,
  fn($x, $y) { ends-with($x, 'a' ) }
)
Result:
true()

(True because the first three items in the input sequence end with "a".)

13.2.8 fn:ends-with-subsequence

Changes in 4.0  

  1. New in 4.0  [Issue 92 PR 222 1 November 2022]

Summary

Determines whether one sequence ends with another, using a supplied callback function to compare items.

Signature
fn:ends-with-subsequence(
$inputas item()*,
$subsequenceas item()*,
$compareas (fn(item(), item()) as xs:boolean?)?:= fn:deep-equal#2
) as xs:boolean
Properties

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

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

Rules

Informally, the function returns true if $input ends with $subsequence, when items are compared using the supplied (or default) $compare function.

Formal Equivalent

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

starts-with-subsequence(reverse($input), reverse($subsequence), $compare)
Notes

There is no requirement that the $compare function should have the traditional qualities of equality comparison. The result is well-defined, for example, even if $compare is not transitive or not symmetric.

A return value of () from the function is treated as false.

There is no requirement that the $compare function should have the traditional qualities of equality comparison. The result is well-defined, for example, even if $compare is not transitive or not symmetric.

A return value of () from the function is treated as false.

Examples
Expression:

ends-with-subsequence((), ())

Result:
true()
Expression:

ends-with-subsequence(1 to 10, 5 to 10)

Result:
true()
Expression:

ends-with-subsequence(1 to 10, ())

Result:
true()
Expression:

ends-with-subsequence(1 to 10, 1 to 10)

Result:
true()
Expression:

ends-with-subsequence(1 to 10, 10)

Result:
true()
Expression:
ends-with-subsequence(
  1 to 10,
  108 to 110,
  fn($x, $y) { $x mod 100 = $y mod 100 }
)
Result:
true()
Expression:
ends-with-subsequence(
  ("A", "B", "C"),
  ("b", "c"),
  fn($x, $y) {
    compare(
      $x,
      $y,
      "http://www.w3.org/2005/xpath-functions/collation/html-ascii-case-insensitive"
    ) eq 0
  }
)
Result:
true()
Expression:
let $p := parse-xml("<doc><chap><p/><p/></chap></doc>")//p[2]
return ends-with-subsequence(
  $p/ancestor::node()[last()],
  $p/root(),
  op("is")
)
Result:
true()
Expression:

ends-with-subsequence(10 to 20, 1 to 5, op("gt"))

Result:
true()
Expression:
ends-with-subsequence(
  ("Alpha", "Beta", "Gamma"),
  ("B", "G"),
  starts-with#2
)
Result:
true()
Expression:
ends-with-subsequence(
  ("Alpha", "Beta", "Gamma", "Delta"),
  1 to 2,
  fn($x, $y) { string-length($x) eq 5 }
)
Result:
true()

(True because the last two items in the input sequence have a string length of 5.)

13.2.9 fn:contains-subsequence

Changes in 4.0  

  1. New in 4.0  [Issue 92 PR 222 1 November 2022]

Summary

Determines whether one sequence contains another as a contiguous subsequence, using a supplied callback function to compare items.

Signature
fn:contains-subsequence(
$inputas item()*,
$subsequenceas item()*,
$compareas (fn(item(), item()) as xs:boolean?)?:= fn:deep-equal#2
) as xs:boolean
Properties

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

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

Rules

Informally, the function returns true if $input contains a consecutive subsequence matching $subsequence, when items are compared using the supplied (or default) $compare function.

Formal Equivalent

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

some $i in 0 to count($input) - count($subsequence) satisfies
  every $j in 1 to count($subsequence) satisfies
    $compare($input[$i + $j], $subsequence[$j])
Notes

There is no requirement that the $compare function should have the traditional qualities of equality comparison. The result is well-defined, for example, even if $compare is not transitive or not symmetric.

A return value of () from the function is treated as false.

There is no requirement that the $compare function should have the traditional qualities of equality comparison. The result is well-defined, for example, even if $compare is not transitive or not symmetric.

A return value of () from the function is treated as false.

Examples
Expression:

contains-subsequence((), ())

Result:
true()
Expression:

contains-subsequence(1 to 10, 3 to 6)

Result:
true()
Expression:

contains-subsequence(1 to 10, (2, 4, 6))

Result:
false()
Expression:

contains-subsequence(1 to 10, ())

Result:
true()
Expression:

contains-subsequence(1 to 10, 1 to 10)

Result:
true()
Expression:

contains-subsequence(1 to 10, 5)

Result:
true()
Expression:
contains-subsequence(
  1 to 10,
  103 to 105,
  fn($x, $y) { $x mod 100 = $y mod 100 }
)
Result:
true()
Expression:
contains-subsequence(
  ("A", "B", "C", "D"),
  ("b", "c"),
  fn($x, $y) {
    compare(
      $x,
      $y,
      "http://www.w3.org/2005/xpath-functions/collation/html-ascii-case-insensitive"
    ) eq 0
  }
)
Result:
true()
Expression:
let $chap := parse-xml("<doc><chap><h1/><p/><p/><footnote/></chap></doc>")//chap
return contains-subsequence(
  $chap ! child::*,
  $chap ! child::p,
  op("is")
)
Result:
true()

(True because the p children of the chap element form a contiguous subsequence.)

Expression:

contains-subsequence(10 to 20, (5, 3, 1), op("gt"))

Result:
true()
Expression:
contains-subsequence(
  ("Alpha", "Beta", "Gamma", "Delta"), ("B", "G"),
  starts-with#2
)
Result:
true()
Expression:
contains-subsequence(
  ("Zero", "Alpha", "Beta", "Gamma", "Delta", "Epsilon"),
  1 to 4,
  fn($x, $y) { ends-with($x, 'a') }
)
Result:
true()

(True because there is a run of 4 consecutive items ending in "a".)

13.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: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 equal to the highest value appearing in the input sequence.
fn:minReturns a value that is equal to the lowest value appearing in the input sequence.
fn:sumReturns a value obtained by adding together the values in $values.
fn:all-equalReturns true if all items in a supplied sequence (after atomization) are equal.
fn:all-differentReturns true if no two items in a supplied sequence are equal.

13.4.1 fn:count

Summary

Returns the number of items in a sequence.

Signature
fn:count(
$inputas item()*
) as xs:integer
Properties

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

Rules

The function returns the number of items in $input.

Formal Equivalent

The function is defined as follows, making use of primitive constructors and accessors defined in [XQuery and XPath Data Model (XDM) 4.0].

dm:count($input)
Notes

The function returns 0 if $input is the empty sequence.

The function returns 0 if $input is the empty sequence.

Examples
Variables
let $tree := <doc><chap><p/><p/><p/></chap></doc>
let $seq2 := (98.5, 98.3, 98.9)
let $seq3 := ()
ExpressionResult
count($tree//chap/p)
3
count($seq3)
0
count($seq2)
3
count($seq2[. > 100])
0
count([])
1
count([ 1, 2, 3 ])
1

13.4.3 fn:max

Changes in 4.0  

  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:double  [Issue 866 PR 881 6 December 2023]

Summary

Returns a value that is equal to the highest 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 are mutually comparable if one or more of the following conditions applies:

  1. Both values are instances of xs:string or xs:anyURI.

  2. Both values are instances of xs:numeric.

  3. Both values are instances of xs:hexBinary or xs:base64Binary.

  4. Both values are instances of xs:date.

  5. Both values are instances of xs:dateTime.

  6. Both values are instances of xs:time.

  7. Both values are instances of xs:dayTimeDuration.

  8. Both values are instances of xs:yearMonthDuration.

  9. Both values are instances of xs:boolean.

If the converted sequence contains a single value then it must be comparable to itself under the above rules. (So the input cannot be, for example, a singleton xs:QName.)

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 $v1 and $v2 from the converted sequence are compared as follows:

  1. If both values are instances of xs:string or xs:anyURI, they are compared using fn:compare($v1, $v2, $collation), where $collation is determined by the rules in 5.3.6 Choosing a collation.

    Note:

    In other cases, $collation is ignored.

  2. If both values are instances of xs:numeric, they are compared using fn:compare($v1, $v2).

  3. In all other cases, the values are compared using the lt and eq operators appropriate to their type.

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:double.

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: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")) raises a type error [err:FORG0006].

13.4.4 fn:min

Changes in 4.0  

  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:double  [Issue 866 PR 881 6 December 2023]

Summary

Returns a value that is equal to the lowest 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 are mutually comparable if one or more of the following conditions applies:

  1. Both values are instances of xs:string or xs:anyURI.

  2. Both values are instances of xs:numeric.

  3. Both values are instances of xs:hexBinary or xs:base64Binary.

  4. Both values are instances of xs:date.

  5. Both values are instances of xs:dateTime.

  6. Both values are instances of xs:time.

  7. Both values are instances of xs:dayTimeDuration.

  8. Both values are instances of xs:yearMonthDuration.

  9. Both values are instances of xs:boolean.

If the converted sequence contains a single value then it must be comparable to itself under the above rules. (So the input cannot be, for example, a singleton xs:QName.)

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 $v1 and $v2 from the converted sequence are compared as follows:

  1. If both values are instances of xs:string or xs:anyURI, they are compared using fn:compare($v1, $v2, $collation), where $collation is determined by the rules in 5.3.6 Choosing a collation.

    Note:

    In other cases, $collation is ignored.

  2. If both values are instances of xs:numeric, they are compared using fn:compare($v1, $v2).

  3. In all other cases, the values are compared using the lt and eq operators appropriate to their type.

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:double.

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: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")) raises a type error [err:FORG0006].

13.4.5 fn:sum

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 values of type xs:untypedAtomic in $values are 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.

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

All items in $values must be numeric or derived from a single base type. In addition, the type must support addition. Duration values must either all be xs:yearMonthDuration values or must all be xs:dayTimeDuration values. For numeric values, the numeric promotion rules defined in 4.2 Arithmetic operators on numeric values are used to promote all values to a single common type. The sum of a sequence of integers will therefore be an integer, while the sum of a numeric sequence that includes at least one xs:double will be an xs:double.

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.

The result of the function when a single argument is supplied is the result of the expression: fn:sum($arg, 0).

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.

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

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.

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

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

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

13.5 Functions on node identifiers

This section defines a number of functions used to find elements by ID or IDREF value, or to generate identifiers.

FunctionMeaning
fn:idReturns the sequence of element nodes that have an ID value matching the value of one or more of the IDREF values supplied in $values.
fn:element-with-id Returns the sequence of element nodes that have an ID value matching the value of one or more of the IDREF values supplied in $values.
fn:idrefReturns the sequence of element or attribute nodes with an IDREF value matching the value of one or more of the ID values supplied in $values.
fn:generate-idThis function returns a string that uniquely identifies a given node.

13.5.1 fn:id

Summary

Returns the sequence of element nodes that have an ID value matching the value of one or more of the IDREF values supplied in $values.

Signature
fn:id(
$valuesas xs:string*,
$nodeas node():= .
) as element()*
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 function returns a sequence, in document order with duplicates eliminated, containing every element node E that satisfies all the following conditions:

  1. E is in the target document. The target document is the document containing $node, or the document containing the context value (.) if the second argument is omitted. The behavior of the function if $node is omitted is exactly the same as if the context value had been passed as $node.

  2. E has an ID value equal to one of the candidate IDREF values, where:

    • An element has an ID value equal to V if either or both of the following conditions are true:

      • The is-id property (See Section 4.5 is-id AccessorDM.) of the element node is true, and the typed value of the element node is equal to V under the rules of the eq operator using the Unicode codepoint collation (http://www.w3.org/2005/xpath-functions/collation/codepoint).

      • The element has an attribute node whose is-id property (See Section 4.5 is-id AccessorDM.) is true and whose typed value is equal to V under the rules of the eq operator using the Unicode code point collation (http://www.w3.org/2005/xpath-functions/collation/codepoint).

    • Each xs:string in $values is parsed as if it were of type IDREFS, that is, each xs:string in $values is treated as a whitespace-separated sequence of tokens, each acting as an IDREF. These tokens are then included in the list of candidate IDREFs. If any of the tokens is not a lexically valid IDREF (that is, if it is not lexically an xs:NCName), it is ignored. Formally, the candidate IDREF values are the strings in the sequence given by the expression:

      for $s in $values
      return tokenize(normalize-space($s), ' ')[. castable as xs:IDREF]
  3. If several elements have the same ID value, then E is the one that is first in document order.

Error Conditions

A dynamic error is raised [err:FODC0001] if $node, or the context value if the second argument is absent, is a node in a tree whose root is not a document node.

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

Notes

The effect of this function is anomalous in respect of element nodes with the is-id property. For legacy reasons, this function returns the element that has the is-id property, whereas it would be more appropriate to return its parent, that being the element that is uniquely identified by the ID. A new function fn:element-with-id has been introduced with the desired behavior.

If the data model is constructed from an Infoset, an attribute will have the is-id property if the corresponding attribute in the Infoset had an attribute type of ID: typically this means the attribute was declared as an ID in a DTD.

If the data model is constructed from a PSVI, an element or attribute will have the is-id property if its typed value is a single atomic item of type xs:ID or a type derived by restriction from xs:ID.

No error is raised in respect of a candidate IDREF value that does not match the ID of any element in the document. If no candidate IDREF value matches the ID value of any element, the function returns the empty sequence.

It is not necessary that the supplied argument should have type xs:IDREF or xs:IDREFS, or that it should be derived from a node with the is-idrefs property.

An element may have more than one ID value. This can occur with synthetic data models or with data models constructed from a PSVI where the element and one of its attributes are both typed as xs:ID.

If the source document is well-formed but not valid, it is possible for two or more elements to have the same ID value. In this situation, the function will select the first such element.

It is also possible in a well-formed but invalid document to have an element or attribute that has the is-id property but whose value does not conform to the lexical rules for the xs:ID type. Such a node will never be selected by this function.

The effect of this function is anomalous in respect of element nodes with the is-id property. For legacy reasons, this function returns the element that has the is-id property, whereas it would be more appropriate to return its parent, that being the element that is uniquely identified by the ID. A new function fn:element-with-id has been introduced with the desired behavior.

If the data model is constructed from an Infoset, an attribute will have the is-id property if the corresponding attribute in the Infoset had an attribute type of ID: typically this means the attribute was declared as an ID in a DTD.

If the data model is constructed from a PSVI, an element or attribute will have the is-id property if its typed value is a single atomic item of type xs:ID or a type derived by restriction from xs:ID.

No error is raised in respect of a candidate IDREF value that does not match the ID of any element in the document. If no candidate IDREF value matches the ID value of any element, the function returns the empty sequence.

It is not necessary that the supplied argument should have type xs:IDREF or xs:IDREFS, or that it should be derived from a node with the is-idrefs property.

An element may have more than one ID value. This can occur with synthetic data models or with data models constructed from a PSVI where the element and one of its attributes are both typed as xs:ID.

If the source document is well-formed but not valid, it is possible for two or more elements to have the same ID value. In this situation, the function will select the first such element.

It is also possible in a well-formed but invalid document to have an element or attribute that has the is-id property but whose value does not conform to the lexical rules for the xs:ID type. Such a node will never be selected by this function.

Examples
Variables
let $emp := validate lax {
  document {
    <employee xml:id="ID21256"
              xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
              xmlns:xs="http://www.w3.org/2001/XMLSchema">
      <empnr xsi:type="xs:ID">E21256</empnr>
      <first>John</first>
      <last>Brown</last>
    </employee>
  }
}
ExpressionResult
$emp/id('ID21256')/name()
"employee"

(The xml:id attribute has the is-id property, so the employee element is selected.)

$emp/id('E21256')/name()
"empnr"

(Assuming the empnr element is given the type xs:ID as a result of schema validation, the element will have the is-id property and is therefore selected. Note the difference from the behavior of fn:element-with-id.)

13.5.2 fn:element-with-id

Summary

Returns the sequence of element nodes that have an ID value matching the value of one or more of the IDREF values supplied in $values.

Signature
fn:element-with-id(
$valuesas xs:string*,
$nodeas node():= .
) as element()*
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

Note:

The effect of this function is identical to fn:id in respect of elements that have an attribute with the is-id property. However, it behaves differently in respect of element nodes with the is-id property. Whereas the fn:id function, for legacy reasons, returns the element that has the is-id property, this function returns the element identified by the ID, which is the parent of the element having the is-id property.

The function returns a sequence, in document order with duplicates eliminated, containing every element node E that satisfies all the following conditions:

  1. E is in the target document. The target document is the document containing $node, or the document containing the context value (.) if the second argument is omitted. The behavior of the function if $node is omitted is exactly the same as if the context value had been passed as $node.

  2. E has an ID value equal to one of the candidate IDREF values, where:

    • An element has an ID value equal to V if either or both of the following conditions are true:

      • The element has an child element node whose is-id property (See Section 4.5 is-id AccessorDM.) is true and whose typed value is equal to V under the rules of the eq operator using the Unicode code point collation (http://www.w3.org/2005/xpath-functions/collation/codepoint).

      • The element has an attribute node whose is-id property (See Section 4.5 is-id AccessorDM.) is true and whose typed value is equal to V under the rules of the eq operator using the Unicode code point collation (http://www.w3.org/2005/xpath-functions/collation/codepoint).

    • Each xs:string in $values is parsed as if it were of type IDREFS, that is, each xs:string in $values is treated as a whitespace-separated sequence of tokens, each acting as an IDREF. These tokens are then included in the list of candidate IDREFs. If any of the tokens is not a lexically valid IDREF (that is, if it is not lexically an xs:NCName), it is ignored. Formally, the candidate IDREF values are the strings in the sequence given by the expression:

      for $s in $arg
      return tokenize(normalize-space($s), ' ')[. castable as xs:IDREF]
  3. If several elements have the same ID value, then E is the one that is first in document order.

Error Conditions

A dynamic error is raised [err:FODC0001] if $node, or the context value if the second argument is omitted, is a node in a tree whose root is not a document node.

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

Notes

This function is equivalent to the fn:id function except when dealing with ID-valued element nodes. Whereas the fn:id function selects the element containing the identifier, this function selects its parent.

If the data model is constructed from an Infoset, an attribute will have the is-id property if the corresponding attribute in the Infoset had an attribute type of ID: typically this means the attribute was declared as an ID in a DTD.

If the data model is constructed from a PSVI, an element or attribute will have the is-id property if its typed value is a single atomic item of type xs:ID or a type derived by restriction from xs:ID.

No error is raised in respect of a candidate IDREF value that does not match the ID of any element in the document. If no candidate IDREF value matches the ID value of any element, the function returns the empty sequence.

It is not necessary that the supplied argument should have type xs:IDREF or xs:IDREFS, or that it should be derived from a node with the is-idrefs property.

An element may have more than one ID value. This can occur with synthetic data models or with data models constructed from a PSVI where the element and one of its attributes are both typed as xs:ID.

If the source document is well-formed but not valid, it is possible for two or more elements to have the same ID value. In this situation, the function will select the first such element.

It is also possible in a well-formed but invalid document to have an element or attribute that has the is-id property but whose value does not conform to the lexical rules for the xs:ID type. Such a node will never be selected by this function.

This function is equivalent to the fn:id function except when dealing with ID-valued element nodes. Whereas the fn:id function selects the element containing the identifier, this function selects its parent.

If the data model is constructed from an Infoset, an attribute will have the is-id property if the corresponding attribute in the Infoset had an attribute type of ID: typically this means the attribute was declared as an ID in a DTD.

If the data model is constructed from a PSVI, an element or attribute will have the is-id property if its typed value is a single atomic item of type xs:ID or a type derived by restriction from xs:ID.

No error is raised in respect of a candidate IDREF value that does not match the ID of any element in the document. If no candidate IDREF value matches the ID value of any element, the function returns the empty sequence.

It is not necessary that the supplied argument should have type xs:IDREF or xs:IDREFS, or that it should be derived from a node with the is-idrefs property.

An element may have more than one ID value. This can occur with synthetic data models or with data models constructed from a PSVI where the element and one of its attributes are both typed as xs:ID.

If the source document is well-formed but not valid, it is possible for two or more elements to have the same ID value. In this situation, the function will select the first such element.

It is also possible in a well-formed but invalid document to have an element or attribute that has the is-id property but whose value does not conform to the lexical rules for the xs:ID type. Such a node will never be selected by this function.

Examples
Variables
let $emp := validate lax {    
  document {
    <employee xml:id="ID21256"
              xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
              xmlns:xs="http://www.w3.org/2001/XMLSchema">
      <empnr xsi:type="xs:ID">E21256</empnr>
      <first>John</first>
      <last>Brown</last>
    </employee>
  }
}
Expression:
$emp/element-with-id('ID21256')/name()
Result:
"employee"

(The xml:id attribute has the is-id property, so the employee element is selected.)

Expression:

$emp/element-with-id('E21256')/name()

Result:
"employee"

(Assuming the empnr element is given the type xs:ID as a result of schema validation, the element will have the is-id property and is therefore its parent is selected. Note the difference from the behavior of fn:id.)

13.5.3 fn:idref

Summary

Returns the sequence of element or attribute nodes with an IDREF value matching the value of one or more of the ID values supplied in $values.

Signature
fn:idref(
$valuesas xs:string*,
$nodeas node():= .
) as node()*
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 function returns a sequence, in document order with duplicates eliminated, containing every element or attribute node $N that satisfies all the following conditions:

  1. $N is in the target document. The target document is the document containing $node, or the document containing the context value (.) if the second argument is omitted. The behavior of the function if $node is omitted is exactly the same as if the context value had been passed as $node.

  2. $N has an IDREF value equal to one of the candidate ID values, where:

    • A node $N has an IDREF value equal to V if both of the following conditions are true:

      • The is-idrefs property (see Section 4.6 is-idrefs AccessorDM) of $N is true.

      • The sequence

        tokenize(normalize-space(string($N)), ' ')

        contains a string that is equal to V under the rules of the eq operator using the Unicode code point collation (http://www.w3.org/2005/xpath-functions/collation/codepoint).

    • Each xs:string in $values is parsed as if it were of lexically of type xs:ID. These xs:strings are then included in the list of candidate xs:IDs. If any of the strings in $values is not a lexically valid xs:ID (that is, if it is not lexically an xs:NCName), it is ignored. More formally, the candidate ID values are the strings in the sequence:

      $values[. castable as xs:NCName]
Error Conditions

A dynamic error is raised [err:FODC0001] if $node, or the context value if the second argument is omitted, is a node in a tree whose root is not a document node.

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

Notes

An element or attribute typically acquires the is-idrefs property by being validated against the schema type xs:IDREF or xs:IDREFS, or (for attributes only) by being described as of type IDREF or IDREFS in a DTD.

Because the function is sensitive to the way in which the data model is constructed, calls on this function are not always interoperable.

No error is raised in respect of a candidate ID value that does not match the IDREF value of any element or attribute in the document. If no candidate ID value matches the IDREF value of any element or attribute, the function returns the empty sequence.

It is possible for two or more nodes to have an IDREF value that matches a given candidate ID value. In this situation, the function will return all such nodes. However, each matching node will be returned at most once, regardless how many candidate ID values it matches.

It is possible in a well-formed but invalid document to have a node whose is-idrefs property is true but that does not conform to the lexical rules for the xs:IDREF type. The effect of the above rules is that ill-formed candidate ID values and ill-formed IDREF values are ignored.

If the data model is constructed from a PSVI, the typed value of a node that has the is-idrefs property will contain at least one atomic item of type xs:IDREF (or a type derived by restriction from xs:IDREF). It may also contain atomic items of other types. These atomic items are treated as candidate ID values if two conditions are met: their lexical form must be valid as an xs:NCName, and there must be at least one instance of xs:IDREF in the typed value of the node. If these conditions are not satisfied, such values are ignored.

An element or attribute typically acquires the is-idrefs property by being validated against the schema type xs:IDREF or xs:IDREFS, or (for attributes only) by being described as of type IDREF or IDREFS in a DTD.

Because the function is sensitive to the way in which the data model is constructed, calls on this function are not always interoperable.

No error is raised in respect of a candidate ID value that does not match the IDREF value of any element or attribute in the document. If no candidate ID value matches the IDREF value of any element or attribute, the function returns the empty sequence.

It is possible for two or more nodes to have an IDREF value that matches a given candidate ID value. In this situation, the function will return all such nodes. However, each matching node will be returned at most once, regardless how many candidate ID values it matches.

It is possible in a well-formed but invalid document to have a node whose is-idrefs property is true but that does not conform to the lexical rules for the xs:IDREF type. The effect of the above rules is that ill-formed candidate ID values and ill-formed IDREF values are ignored.

If the data model is constructed from a PSVI, the typed value of a node that has the is-idrefs property will contain at least one atomic item of type xs:IDREF (or a type derived by restriction from xs:IDREF). It may also contain atomic items of other types. These atomic items are treated as candidate ID values if two conditions are met: their lexical form must be valid as an xs:NCName, and there must be at least one instance of xs:IDREF in the typed value of the node. If these conditions are not satisfied, such values are ignored.

Examples
Variables
let $emp := validate lax {  
  document {    
    <employees xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
               xmlns:xs="http://www.w3.org/2001/XMLSchema">  
      <employee xml:id="ID21256">
        <empnr xsi:type="xs:ID">E21256</empnr>
        <first>Anil</first>
        <last>Singh</last>
        <deputy xsi:type="xs:IDREF">E30561</deputy>
      </employee>
      <employee xml:id="ID30561">
        <empnr xsi:type="xs:ID">E30561</empnr>
        <first>John</first>
        <last>Brown</last>
        <manager xsi:type="xs:IDREF">ID21256</manager>
      </employee>
    </employees>
  }
}
Expression:
$emp/(
  element-with-id('ID21256')/@xml:id => idref()
)/ancestor::employee/last
=> string()
Result:
"Brown"

(Assuming that manager has the is-idref property, the call on fn:idref selects the manager element. If, instead, the manager had a ref attribute with the is-idref property, the call on fn:idref would select the attribute node.)

Expression:
$emp/(
  element-with-id('E30561')/empnr => idref()
)/ancestor::employee/last
=> string()
Result:
"Singh"

(Assuming that employee/deputy has the is-idref property, the call on fn:idref selects the deputy element.)

13.5.4 fn:generate-id

Summary

This function returns a string that uniquely identifies a given node.

Signature
fn:generate-id(
$nodeas node()?:= .
) 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·.

Rules

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

If the argument is the empty sequence, the result is the zero-length string.

In other cases, the function returns a string that uniquely identifies a given node. More formally, it is guaranteed that within a single ·execution scope·, fn:codepoint-equal(fn:generate-id($N), fn:generate-id($M)) returns true if and only if ($M is $N) returns true.

The returned identifier must consist of ASCII alphanumeric characters and must start with an alphabetic character. Thus, the string is syntactically an XML name.

Error Conditions

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

Notes

An implementation is free to generate an identifier in any convenient way provided that it always generates the same identifier for the same node and that different identifiers are always generated from different nodes. An implementation is under no obligation to generate the same identifiers each time a document is transformed or queried.

There is no guarantee that a generated unique identifier will be distinct from any unique IDs specified in the source document.

There is no inverse to this function; it is not directly possible to find the node with a given generated ID. Of course, it is possible to search a given sequence of nodes using an expression such as $nodes[generate-id()=$id].

It is advisable, but not required, for implementations to generate IDs that are distinct even when compared using a case-blind collation.

An implementation is free to generate an identifier in any convenient way provided that it always generates the same identifier for the same node and that different identifiers are always generated from different nodes. An implementation is under no obligation to generate the same identifiers each time a document is transformed or queried.

There is no guarantee that a generated unique identifier will be distinct from any unique IDs specified in the source document.

There is no inverse to this function; it is not directly possible to find the node with a given generated ID. Of course, it is possible to search a given sequence of nodes using an expression such as $nodes[generate-id()=$id].

It is advisable, but not required, for implementations to generate IDs that are distinct even when compared using a case-blind collation.

Examples

The primary use case for this function is to generate hyperlinks. For example, when generating HTML, an anchor for a given section $sect can be generated by writing (in either XSLT or XQuery):

<a name="{ generate-id($sect) }"/>

and a link to that section can then be produced with code such as:

see <a href="#{ generate-id($sect) }">here</a>

Note that anchors generated in this way will not necessarily be the same each time a document is republished.

Since the keys in a map must be atomic items, it is possible to use generated IDs as surrogates for nodes when constructing a map. For example, in some implementations, testing whether a node $N is a member of a large node-set $S using the expression exists($N intersect $S) may be expensive; there may then be performance benefits in creating a map:

let $SMap := map:merge($S ! { generate-id(.) : . })

and then testing for membership of the node-set using:

map:contains($SMap, generate-id($N))

13.6 Functions giving access to external information

The functions in this section provide access to resources (such as files) in the external environment.

FunctionMeaning
fn:docRetrieves a document using a URI supplied as an xs:string, and returns the corresponding document node.
fn:doc-availableThe function returns true if and only if the function call fn:doc($source) would return a document node.
fn:collectionReturns a sequence of items identified by a collection URI; or a default collection if no URI is supplied.
fn:uri-collectionReturns a sequence of xs:anyURI values representing the URIs in a URI collection.
fn:unparsed-textThe fn:unparsed-text function reads an external resource (for example, a file) and returns a string representation of the resource.
fn:unparsed-text-linesThe fn:unparsed-text-lines function reads an external resource (for example, a file) and returns its contents as a sequence of strings, one for each line of text in the string representation of the resource.
fn:unparsed-text-availableAllows an application to determine whether a call on fn:unparsed-text with particular arguments would succeed.
fn:environment-variableReturns the value of a system environment variable, if it exists.
fn:available-environment-variablesReturns a list of environment variable names that are suitable for passing to fn:environment-variable, as a (possibly empty) sequence of strings.

13.6.3 fn:collection

Summary

Returns a sequence of items identified by a collection URI; or a default collection if no URI is supplied.

Signature
fn:collection(
$sourceas xs:string?:= ()
) as item()*
Properties

This function is ·deterministic·, ·context-dependent·, and ·focus-independent·. It depends on available collections, and static base URI.

Rules

This function takes an xs:string as argument and returns a sequence of items obtained by interpreting $source as an xs:anyURI and resolving it according to the mapping specified in available collections described in Section C.2 Dynamic Context Components XP31.

If available collections provides a mapping from this string to a sequence of items, the function returns that sequence. If available collections maps the string to an empty sequence, then the function returns an empty sequence.

If $source is not specified, the function returns the sequence of items in the default collection in the dynamic context. See Section C.2 Dynamic Context Components XP31.

If $source is a relative xs:anyURI, it is resolved against the value of the base-URI property from the static context.

If $source is the empty sequence, the function behaves as if it had been called without an argument. See above.

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

There is no requirement that any nodes in the result should be in document order, nor is there a requirement that the result should contain no duplicates.

Error Conditions

A dynamic error is raised [err:FODC0002] if no URI is supplied and the value of the default collection is absentDM.

A dynamic error is raised [err:FODC0002] if a relative URI reference is supplied, and the base-URI property in the static context is absent.

A dynamic error is raised [err:FODC0002] if available node collections provides no mapping for the absolutized URI.

A dynamic error may be raised [err:FODC0004] if $source is not a valid xs:anyURI.

Notes

In earlier versions of this specification, the primary use for the fn:collection function was to retrieve a collection of XML documents, perhaps held as lexical XML in operating system filestore, or perhaps held in an XML database. In this release the concept has been generalised to allow other resources to be retrieved: for example JSON documents might be returned as arrays or maps, non-XML text files might be returned as strings, and binary files might be returned as instances of xs:base64Binary.

The abstract concept of a collection might be realized in different ways by different implementations, and the ways in which URIs map to collections can be equally variable. Specifying resources using URIs is useful because URIs are dynamic, can be parameterized, and do not rely on an external environment.

In earlier versions of this specification, the primary use for the fn:collection function was to retrieve a collection of XML documents, perhaps held as lexical XML in operating system filestore, or perhaps held in an XML database. In this release the concept has been generalised to allow other resources to be retrieved: for example JSON documents might be returned as arrays or maps, non-XML text files might be returned as strings, and binary files might be returned as instances of xs:base64Binary.

The abstract concept of a collection might be realized in different ways by different implementations, and the ways in which URIs map to collections can be equally variable. Specifying resources using URIs is useful because URIs are dynamic, can be parameterized, and do not rely on an external environment.

13.6.4 fn:uri-collection

Summary

Returns a sequence of xs:anyURI values representing the URIs in a URI collection.

Signature
fn:uri-collection(
$sourceas xs:string?:= ()
) as xs:anyURI*
Properties

This function is ·deterministic·, ·context-dependent·, and ·focus-independent·. It depends on available URI collections, and static base URI.

Rules

The zero-argument form of the function returns the URIs in the default URI collection described in Section C.2 Dynamic Context Components XP31.

If $source is a relative xs:anyURI, it is resolved against the value of the base-URI property from the static context.

If $source is the empty sequence, the function behaves as if it had been called without an argument. See above.

The single-argument form of the function returns the sequence of URIs corresponding to the supplied URI in the available URI collections described in Section C.2 Dynamic Context Components XP31.

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

There is no requirement that the URIs returned by this function should all be distinct, and no assumptions can be made about the order of URIs in the sequence, unless the implementation defines otherwise.

Error Conditions

A dynamic error is raised [err:FODC0002] if no URI is supplied (that is, if the function is called with no arguments, or with a single argument that evaluates to an empty sequence), and the value of the default resource collection is absentDM.

A dynamic error is raised [err:FODC0002] if a relative URI reference is supplied, and the base-URI property in the static context is absent.

A dynamic error is raised [err:FODC0002] if available resource collections provides no mapping for the absolutized URI.

A dynamic error may be raised [err:FODC0004] if $source is not a valid xs:anyURI.

Notes

In some implementations, there might be a close relationship between collections (as retrieved by the fn:collection function), and URI collections (as retrieved by this function). For example, a collection might return XML documents, and the corresponding URI collection might return the URIs of those documents. However, this specification does not impose such a close relationship. For example, there may be collection URIs accepted by one of the two functions and not by the other; a collection might contain items that do not have any URI; or a URI collection might contain URIs that cannot be dereferenced to return any resource.

Thus, some implementations might ensure that calling fn:uri-collection and then applying fn:doc to each of the returned URIs delivers the same result as calling fn:collection with the same argument; however, this is not guaranteed.

In the case where fn:uri-collection returns the URIs of resources that could also be retrieved directly using fn:collection, there are several reasons why it might be appropriate to use this function in preference to the fn:collection function. For example:

In some implementations, there might be a close relationship between collections (as retrieved by the fn:collection function), and URI collections (as retrieved by this function). For example, a collection might return XML documents, and the corresponding URI collection might return the URIs of those documents. However, this specification does not impose such a close relationship. For example, there may be collection URIs accepted by one of the two functions and not by the other; a collection might contain items that do not have any URI; or a URI collection might contain URIs that cannot be dereferenced to return any resource.

In the case where fn:uri-collection returns the URIs of resources that could also be retrieved directly using fn:collection, there are several reasons why it might be appropriate to use this function in preference to the fn:collection function. For example:

  • It allows different URIs for different kinds of resource to be dereferenced in different ways: for example, the returned URIs might be referenced using the fn:unparsed-text function rather than the fn:doc function.

  • In XSLT 3.0 it allows the documents in a collection to be processed in streaming mode using the xsl:stream instruction.

  • It allows recovery from failures to read, parse, or validate individual documents, by calling the fn:doc (or other dereferencing) function within the scope of try/catch.

  • It allows selection of which documents to read based on their URI, for example they can be filtered to select those whose URIs end in .xml, or those that use the https scheme.

  • An application might choose to limit the number of URIs processed in a single run, for example it might process only the first 50 URIs in the collection; or it might present the URIs to the user and allow the user to select which of them need to be further processed.

  • It allows the URIs to be modified before they are dereferenced, for example by adding or removing query parameters, or by redirecting the request to a local cache or to a mirror site.

For some of these use cases, this assumes that the cost of calling fn:collection might be significant (for example, it might involving retrieving all the documents in the collection over the network and parsing them). This will not necessarily be true of all implementations.

For some of these use cases, this assumes that the cost of calling fn:collection might be significant (for example, it might involving retrieving all the documents in the collection over the network and parsing them). This will not necessarily be true of all implementations.

13.6.5 fn:unparsed-text

Changes in 4.0  

  1. The $options parameter has been added.  [Issue 1116 PR 1117 21 May 2024]

Summary

The fn:unparsed-text function reads an external resource (for example, a file) and returns a string representation of the resource.

Signature
fn:unparsed-text(
$sourceas xs:string?,
$optionsas (xs:string | map(*))?:= ()
) as xs:string?
Properties

This function is ·deterministic·, ·context-dependent·, and ·focus-independent·. It depends on static base URI.

Rules

The $source argument must be a string in the form of a URI reference, which must contain no fragment identifier, and must identify a resource for which a string representation is available. If the URI is a relative URI reference, then it is resolved relative to the static base URI property from the static context.

The $options argument, for backwards compatibility reasons, may be supplied either as a map, or as a string. Supplying a value $S that is not a map is equivalent to supplying the map { "encoding": $S }. After that substitution, the ·option parameter conventions· apply.

The entries that may appear in the $options map are as follows:

record(
encoding?as xs:string?,
normalize-newlines?as xs:boolean
)
KeyValueMeaning

encoding?

Defines the encoding of the resource, as described below.
  • Type: xs:string?

  • Default: ()

normalize-newlines?

Determines whether CR and CRLF character sequences are treated as equivalent to NL characters.
  • Type: xs:boolean

  • Default: false

falseNo normalization of line endings takes place.
trueThe character U+000D (CARRIAGE RETURN) and the character pair (U+000D (CARRIAGE RETURN) , U+000A (NEWLINE) ) are converted to the single character U+000A (NEWLINE) .

The mapping of URIs to the string representation of a resource is the mapping defined in the available text resourcesXP31 component of the dynamic context.

If the $source argument is an empty sequence, the function returns an empty sequence.

The encoding option, if present and non-empty, is the name of an encoding. The values for this option follow the same rules as for the encoding attribute in an XML declaration. The only values which every implementation is required to recognize are utf-8 and utf-16.

The encoding of the external resource is determined as follows:

  1. external encoding information is used if available, otherwise

  2. if the media type of the resource is text/xml or application/xml (see [RFC 2376]), or if it matches the conventions text/*+xml or application/*+xml (see [RFC 7303] and/or its successors), then the encoding is recognized as specified in [Extensible Markup Language (XML) 1.0 (Fifth Edition)], otherwise

  3. the encoding option is used if present, otherwise

  4. the processor may use ·implementation-defined· heuristics to determine the likely encoding, otherwise

  5. UTF-8 is assumed.

The result of the function is a string containing the string representation of the resource retrieved using the URI, decoded according to the specified encoding.

Error Conditions

A dynamic error is raised [err:FOUT1170] if the $source argument contains a fragment identifier, or if it cannot be resolved to an absolute URI (for example, because the base-URI property in the static context is absent), or if it cannot be used to retrieve the string representation of a resource.

A dynamic error is raised [err:FOUT1190] if the value of the encoding option is not a valid encoding name, if the processor does not support the specified encoding, if the string representation of the retrieved resource contains octets that cannot be decoded into Unicode ·characters· using the specified encoding, or if any resulting character is not a ·permitted character·.

A dynamic error is raised [err:FOUT1200] if the encoding option is absent and the processor cannot infer the encoding using external information and the actual encoding is not UTF-8.

Notes

If it is appropriate to use a base URI other than the dynamic base URI (for example, when resolving a relative URI reference read from a source document) then it is advisable to resolve the relative URI reference using the fn:resolve-uri function before passing it to the fn:unparsed-text function.

There is no essential relationship between the sets of URIs accepted by the two functions fn:unparsed-text and fn:doc (a URI accepted by one may or may not be accepted by the other), and if a URI is accepted by both there is no essential relationship between the results (different resource representations are permitted by the architecture of the web).

There are no constraints on the MIME type of the resource.

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:

If it is appropriate to use a base URI other than the dynamic base URI (for example, when resolving a relative URI reference read from a source document) then it is advisable to resolve the relative URI reference using the fn:resolve-uri function before passing it to the fn:unparsed-text function.

There is no essential relationship between the sets of URIs accepted by the two functions fn:unparsed-text and fn:doc (a URI accepted by one may or may not be accepted by the other), and if a URI is accepted by both there is no essential relationship between the results (different resource representations are permitted by the architecture of the web).

There are no constraints on the MIME type of the resource.

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:

  • The set of URI schemes that the implementation recognizes is implementation-defined. Implementations may allow the mapping of URIs to resources to be configured by the user, using mechanisms such as catalogs or user-written URI handlers.

  • The handling of media types is implementation-defined.

  • Implementations may provide user-defined error handling options that allow processing to continue following an error in retrieving a resource, or in reading its content. When errors have been handled in this way, the function may return a fallback document provided by the error handler.

  • For backwards compatibility reasons, implementations may provide configuration options that alter the default for the deterministic option.

The rules for determining the encoding are chosen for consistency with [XML Inclusions (XInclude) Version 1.0 (Second Edition)]. Files with an XML media type are treated specially because there are use cases for this function where the retrieved text is to be included as unparsed XML within a CDATA section of a containing document, and because processors are likely to be able to reuse the code that performs encoding detection for XML external entities.

If the text file contains characters such as < and &, these will typically be output as &lt; and &amp; if the string is serialized as XML or HTML. If these characters actually represent markup (for example, if the text file contains HTML), then an XSLT stylesheet can attempt to write them as markup to the output file using the disable-output-escaping attribute of the xsl:value-of instruction. Note, however, that XSLT implementations are not required to support this feature.

The rules for determining the encoding are chosen for consistency with [XML Inclusions (XInclude) Version 1.0 (Second Edition)]. Files with an XML media type are treated specially because there are use cases for this function where the retrieved text is to be included as unparsed XML within a CDATA section of a containing document, and because processors are likely to be able to reuse the code that performs encoding detection for XML external entities.

If the text file contains characters such as < and &, these will typically be output as &lt; and &amp; if the string is serialized as XML or HTML. If these characters actually represent markup (for example, if the text file contains HTML), then an XSLT stylesheet can attempt to write them as markup to the output file using the disable-output-escaping attribute of the xsl:value-of instruction. Note, however, that XSLT implementations are not required to support this feature.

Examples

This XSLT example attempts to read a file containing “boilerplate” HTML and copy it directly to the serialized output file:

<xsl:output method="html"/>

<xsl:template match="/">
  <xsl:value-of select="unparsed-text('header.html', 'iso-8859-1')"
                disable-output-escaping="yes"/>
  <xsl:apply-templates/>
  <xsl:value-of select="unparsed-text('footer.html', 'iso-8859-1')"
                disable-output-escaping="yes"/>
</xsl:template>

13.6.6 fn:unparsed-text-lines

Changes in 4.0  

  1. The $options parameter has been added.  [Issues 1116 1278 PRs 1117 1279 21 May 2024]

Summary

The fn:unparsed-text-lines function reads an external resource (for example, a file) and returns its contents as a sequence of strings, one for each line of text in the string representation of the resource.

Signature
fn:unparsed-text-lines(
$sourceas xs:string?,
$optionsas (xs:string | map(*))?:= ()
) as xs:string*
Properties

This function is ·deterministic·, ·context-dependent·, and ·focus-independent·. It depends on static base URI.

Rules

The unparsed-text-lines function reads an external resource (for example, a file) and returns its string representation as a sequence of strings, separated at newline boundaries.

The $options argument, for backwards compatibility reasons, may be supplied either as a map, or as a string. Supplying a value $S that is not a map is equivalent to supplying the map { "encoding": $S }. After that substitution, the ·option parameter conventions· apply.

The entries that may appear in the $options map are as follows:

record(
encoding?as xs:string?
)
KeyMeaning

encoding?

Defines the encoding of the resource, following the rules of fn:unparsed-text.
  • Type: xs:string?

  • Default: ()

The result of the function is the same as the result of the expression:

let $text := unparsed-text($source, map:put($options, 'normalize-newlines', true()))
let $lines := tokenize($text, '\n')
return $lines[not(position() = last() and . = '')]

The result is thus a sequence of strings containing the text of the resource retrieved using the URI, each string representing one line of text. Lines may be delimited by any of the character sequences U+000A (NEWLINE) , U+000D (CARRIAGE RETURN) , or U+000D (CARRIAGE RETURN) followed by U+000A (NEWLINE) . Line ending characters are not included in the returned strings. If there are two adjacent newline sequences, a zero-length string will be returned to represent the empty line; but if the external resource ends with a newline sequence, the result will be as if this final line ending were not present.

Error Conditions

Error conditions are the same as for the fn:unparsed-text function.

Notes

See the notes for fn:unparsed-text.

See the notes for fn:unparsed-text.

13.6.7 fn:unparsed-text-available

Changes in 4.0  

  1. The $options parameter has been added.  [Issue 1116 PR 1117 21 May 2024]

Summary

Allows an application to determine whether a call on fn:unparsed-text with particular arguments would succeed.

Signature
fn:unparsed-text-available(
$sourceas xs:string?,
$optionsas (xs:string | map(*))?:= ()
) as xs:boolean
Properties

This function is ·deterministic·, ·context-dependent·, and ·focus-independent·. It depends on static base URI.

Rules

The fn:unparsed-text-available function determines whether a call on the fn:unparsed-text function with identical arguments would return a string.

If the first argument is an empty sequence, the function returns false.

In other cases, the function returns true if a call on fn:unparsed-text or fn:unparsed-text-lines with the same arguments would succeed, and false if a call on fn:unparsed-text or fn:unparsed-text-lines with the same arguments would fail with a non-recoverable dynamic error.

The functions fn:unparsed-text and fn:unparsed-text-available have the same requirement for ·determinism· as the functions fn:doc and fn:doc-available. This means that unless the user has explicitly stated a requirement for a reduced level of determinism, either of these functions if called twice with the same arguments during the course of a transformation must return the same results each time; moreover, the results of a call on fn:unparsed-text-availablemust be consistent with the results of a subsequent call on unparsed-text with the same arguments.

Notes

This function was introduced before XQuery and XSLT allowed errors to be caught; with current versions of these host languages, catching an error from fn:unparsed-text may provide a better alternative.

The specification requires that the fn:unparsed-text-available function should actually attempt to read the resource identified by the URI, and check that it is correctly encoded and contains no characters that are invalid in XML. Implementations may avoid the cost of repeating these checks for example by caching the validated contents of the resource, to anticipate a subsequent call on the fn:unparsed-text or fn:unparsed-text-lines function. Alternatively, implementations may be able to rewrite an expression such as if (unparsed-text-available(A)) then unparsed-text(A) else ... to generate a single call internally.

Since the function fn:unparsed-text-lines succeeds or fails under exactly the same circumstances as fn:unparsed-text, the fn:unparsed-text-available function may equally be used to test whether a call on fn:unparsed-text-lines would succeed.

This function was introduced before XQuery and XSLT allowed errors to be caught; with current versions of these host languages, catching an error from fn:unparsed-text may provide a better alternative.

The specification requires that the fn:unparsed-text-available function should actually attempt to read the resource identified by the URI, and check that it is correctly encoded and contains no characters that are invalid in XML. Implementations may avoid the cost of repeating these checks for example by caching the validated contents of the resource, to anticipate a subsequent call on the fn:unparsed-text or fn:unparsed-text-lines function. Alternatively, implementations may be able to rewrite an expression such as if (unparsed-text-available(A)) then unparsed-text(A) else ... to generate a single call internally.

Since the function fn:unparsed-text-lines succeeds or fails under exactly the same circumstances as fn:unparsed-text, the fn:unparsed-text-available function may equally be used to test whether a call on fn:unparsed-text-lines would succeed.

13.6.8 fn:environment-variable

Summary

Returns the value of a system environment variable, if it exists.

Signature
fn:environment-variable(
$nameas xs:string
) as xs:string?
Properties

This function is ·deterministic·, ·context-dependent·, and ·focus-independent·. It depends on environment variables.

Rules

The set of available environment variablesXP31 is a set of (name, value) pairs forming part of the dynamic context, in which the name is unique within the set of pairs. The name and value are arbitrary strings.

If the $name argument matches the name of one of these pairs, the function returns the corresponding value.

If there is no environment variable with a matching name, the function returns the empty sequence.

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.

The function is ·deterministic·, which means that if it is called several times within the same ·execution scope·, with the same arguments, it must return the same result.

Notes

On many platforms, the term “environment variable” has a natural meaning in terms of facilities provided by the operating system. This interpretation of the concept does not exclude other interpretations, such as a mapping to a set of configuration parameters in a database system.

Environment variable names are usually case sensitive. Names are usually of the form (letter|_) (letter|_|digit)*, but this varies by platform.

On some platforms, there may sometimes be multiple environment variables with the same name; in this case, it is implementation-dependent as to which is returned; see for example [POSIX.1-2008] (Chapter 8, Environment Variables). Implementations may use prefixes or other naming conventions to disambiguate the names.

The requirement to ensure that the function is deterministic means in practice that the implementation must make a snapshot of the environment variables at some time during execution, and return values obtained from this snapshot, rather than using live values that are subject to change at any time.

Operating system environment variables may be associated with a particular process, while queries and stylesheets may execute across multiple processes (or multiple machines). In such circumstances implementations may choose to provide access to the environment variables associated with the process in which the query or stylesheet processing was initiated.

Security advice: Queries from untrusted sources should not be permitted unrestricted access to environment variables. For example, the name of the account under which the query is running may be useful information to a would-be intruder. An implementation may therefore choose to restrict access to the environment, or may provide a facility to make fn:environment-variable always return the empty sequence.

On many platforms, the term “environment variable” has a natural meaning in terms of facilities provided by the operating system. This interpretation of the concept does not exclude other interpretations, such as a mapping to a set of configuration parameters in a database system.

Environment variable names are usually case sensitive. Names are usually of the form (letter|_) (letter|_|digit)*, but this varies by platform.

On some platforms, there may sometimes be multiple environment variables with the same name; in this case, it is implementation-dependent as to which is returned; see for example [POSIX.1-2008] (Chapter 8, Environment Variables). Implementations may use prefixes or other naming conventions to disambiguate the names.

The requirement to ensure that the function is deterministic means in practice that the implementation must make a snapshot of the environment variables at some time during execution, and return values obtained from this snapshot, rather than using live values that are subject to change at any time.

Operating system environment variables may be associated with a particular process, while queries and stylesheets may execute across multiple processes (or multiple machines). In such circumstances implementations may choose to provide access to the environment variables associated with the process in which the query or stylesheet processing was initiated.

Security advice: Queries from untrusted sources should not be permitted unrestricted access to environment variables. For example, the name of the account under which the query is running may be useful information to a would-be intruder. An implementation may therefore choose to restrict access to the environment, or may provide a facility to make fn:environment-variable always return the empty sequence.

13.6.9 fn:available-environment-variables

Summary

Returns a list of environment variable names that are suitable for passing to fn:environment-variable, as a (possibly empty) sequence of strings.

Signature
fn:available-environment-variables() as xs:string*
Properties

This function is ·deterministic·, ·context-dependent·, and ·focus-independent·. It depends on environment variables.

Rules

The function returns a sequence of strings, being the names of the environment variables in the dynamic context in some ·implementation-dependent· order.

The function is ·deterministic·: that is, the set of available environment variables does not vary during evaluation.

Notes

The function returns a list of strings, containing no duplicates.

It is intended that the strings in this list should be suitable for passing to fn:environment-variable.

See also the note on security under the definition of the fn:environment-variable function. If access to environment variables has been disabled, fn:available-environment-variables always returns the empty sequence.

The function returns a list of strings, containing no duplicates.

It is intended that the strings in this list should be suitable for passing to fn:environment-variable.

See also the note on security under the definition of the fn:environment-variable function. If access to environment variables has been disabled, fn:available-environment-variables always returns the empty sequence.

14 Parsing and serializing

These functions convert between the lexical representation and XPath and XQuery data model representation of various file formats.

14.1 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 represented as a string, 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.

14.1.1 fn:parse-xml

Changes in 4.0  

  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]

Summary

This function takes as input an XML document represented as a string, and returns the document node at the root of an XDM tree representing the parsed document.

Signature
fn:parse-xml(
$valueas xs:string?,
$optionsas map(*)?:= {}
) as document-node(*)?
Properties

This function is ·nondeterministic·, ·context-dependent·, and ·focus-independent·. It depends on static base URI.

Rules

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

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,
xsd-validation?as xs:string
)
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()

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

xsd-validation?

Determines whether XSD validation takes place.
  • 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.

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 not·deterministic·: 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 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 DTD validation is requested and the processor does not have access to a validating XML parser.

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

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 are 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

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

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.

14.1.2 fn:parse-xml-fragment

Changes in 4.0  

  1. The $options parameter has been added.  [Issue 305 PR 1257 11 June 2024]

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?,
$optionsas map(*)?:= {}
) as document-node()?
Properties

This function is ·nondeterministic·, ·context-dependent·, and ·focus-independent·. It depends on static base URI.

Rules

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

The input must be a namespace-well-formed external general parsed entity. More specifically, it must be a string conforming 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 string 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.

Schema validation is not invoked, which means that the nodes in the returned document will all be untyped.

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 not·deterministic·: 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.

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

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.

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

The expression parse-xml-fragment("") returns 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.

The expression parse-xml-fragment(" ", { "strip-space": true() }) returns a document node having no children.

The expression parse-xml-fragment('<?xml version="1.0" encoding="utf8" standalone="yes"?><a/>') 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 fn:parse-xml-fragment.)

14.1.3 fn:serialize

Summary

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

Signature
fn:serialize(
$inputas item()*,
$optionsas (element(output:serialization-parameters) | map(*))?:= ()
) as xs:string
Properties

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

Rules

The value of the first argument $input acts as the input sequence to the serialization process, which starts with sequence normalization.

The second argument $options, if present, provides serialization parameters. These may be supplied in either of two forms:

  1. As an output:serialization-parameters element, having the format described in Section 3.1 Setting Serialization Parameters by Means of a Data Model Instance SER31. In this case the type of the supplied argument must match the required type element(output:serialization-parameters).

  2. As a map. In this case the type of the supplied argument must match the required type map(*)

The single-argument version of this function has the same effect as the two-argument version called with $options set to an empty sequence. This in turn is the same as the effect of passing an output:serialization-parameters element with no child elements.

The final stage of serialization, that is, encoding, is skipped. If the serializer does not allow this phase to be skipped, then the sequence of octets returned by the serializer is decoded into a string by reversing the character encoding performed in the final stage.

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.

If the second argument is supplied as a map, then the ·option parameter conventions· apply. In this case:

  1. Each entry in the map defines one serialization parameter.

  2. The key of the entry is an xs:string value in the cases of parameter names defined in these specifications, or an xs:QName (with non-absent namespace) in the case of implementation-defined serialization parameters.

  3. The required type of each parameter, and its default value, are defined by the following table. The default value is used when the map contains no entry for the parameter in question, and also when an entry is present, with the empty sequence as its value. The table also indicates how the value of the map entry is to be interpreted in cases where further explanation is needed.

ParameterRequired typeInterpretationDefault Value
allow-duplicate-namesxs:boolean?true() means "yes", false() means "no"no
byte-order-markxs:boolean?true() means "yes", false() means "no"no
cdata-section-elementsxs:QName*()
doctype-publicxs:string?Zero-length string and () both represent "absent"absent
doctype-systemxs:string?Zero-length string and () both represent "absent"absent
encodingxs:string?utf-8
escape-solidusxs:boolean?true() means "yes", false() means "no"yes
escape-uri-attributesxs:boolean?true() means "yes", false() means "no"yes
html-versionxs:decimal?5
include-content-typexs:boolean?true() means "yes", false() means "no"yes
indentxs:boolean?true() means "yes", false() means "no"no
item-delimiterxs:string?absent
json-linesxs:boolean?true() means "yes", false() means "no"no
json-node-output-method(xs:string | xs:QName)?See Notes 1, 2xml
media-typexs:string?(a media type suitable for the chosen method)
method(xs:string | xs:QName)?See Notes 1, 2xml
normalization-formxs:string?none
omit-xml-declarationxs:boolean?true() means "yes", false() means "no"yes
standalonexs:boolean?true() means "yes", false() means "no", () means "omit"omit
suppress-indentationxs:QName*()
undeclare-prefixesxs:boolean?true() means "yes", false() means "no"no
use-character-mapsmap(xs:string, xs:string)?See Note 3{}
versionxs:string?1.0

Notes to the table:

  1. The notation (A | B) represents a union type whose member types are A and B.

  2. If an xs:QName is supplied for the method or json-node-output-method options, then it must have a non-absent namespace URI. This means that system-defined serialization methods such as xml and json are defined as strings, not as xs:QName values.

  3. For the use-character-maps option, the value is a map, whose keys are the characters to be mapped (as xs:string instances), and whose corresponding values are the strings to be substituted for these characters.

Error Conditions

A type error [err:XPTY0004]XP occurs if the $options argument is present and does not match either of the types element(output:serialization-parameters)? or map(*).

Note:

This is defined as a type error so that it can be enforced via the function signature by implementations that generalize the type system in a suitable way.

If the host language makes serialization an optional feature and the implementation does not support serialization, then a dynamic error [err:FODC0010] is raised.

When the second argument is supplied as a map, and the supplied value is of the wrong type for the particular parameter, for example if the value of indent is a string rather than a boolean, then as defined by the ·option parameter conventions·, a type error [err:XPTY0004]XP is raised. If the value is of the correct type, but does not satisfy the rules for that parameter defined in [XSLT and XQuery Serialization 3.1], then a dynamic error [err:SEPM0016]SER31 is raised. (For example, this occurs if the map supplied to use-character-maps includes a key that is a string whose length is not one (1)).

If any serialization error occurs, including the detection of an invalid value for a serialization parameter as described above, this results in the fn:serialize call failing with a dynamic error.

Notes

One use case for this function arises when there is a need to construct an XML document containing nested XML documents within a CDATA section (or on occasions within a comment). See fn:parse-xml for further details.

Another use case arises when there is a need to call an extension function that expects a lexical XML document as input.

Another use case for this function is serializing instances of the data model into a human readable format for the purposes of debugging. Using the Section 10 Adaptive Output Method SER31 by specifying it as the output method defined in the second argument via output:serialization-parameters, allows for serializing any valid XDM instance without raising a serialization error.

There are also use cases where the application wants to post-process the output of a query or transformation, for example by adding an internal DTD subset, or by inserting proprietary markup delimiters such as the <% ... %> used by some templating languages.

The ability to specify the serialization parameters in an output:serialization-parameters element provides backwards compatibility with the 3.0 version of this specification; the ability to use a map takes advantage of new features in the 3.1 version. The default parameter values are implementation-defined when an output:serialization-parameters element is used (or when the argument is omitted), but are fixed by this specification in the case where a map (including an empty map) is supplied for the argument.

One use case for this function arises when there is a need to construct an XML document containing nested XML documents within a CDATA section (or on occasions within a comment). See fn:parse-xml for further details.

Another use case arises when there is a need to call an extension function that expects a lexical XML document as input.

Another use case for this function is serializing instances of the data model into a human readable format for the purposes of debugging. Using the Section 10 Adaptive Output Method SER31 by specifying it as the output method defined in the second argument via output:serialization-parameters, allows for serializing any valid XDM instance without raising a serialization error.

There are also use cases where the application wants to post-process the output of a query or transformation, for example by adding an internal DTD subset, or by inserting proprietary markup delimiters such as the <% ... %> used by some templating languages.

The ability to specify the serialization parameters in an output:serialization-parameters element provides backwards compatibility with the 3.0 version of this specification; the ability to use a map takes advantage of new features in the 3.1 version. The default parameter values are implementation-defined when an output:serialization-parameters element is used (or when the argument is omitted), but are fixed by this specification in the case where a map (including an empty map) is supplied for the argument.

Examples
Variables
let $params := <output:serialization-parameters 
    xmlns:output="http://www.w3.org/2010/xslt-xquery-serialization">
  <output:omit-xml-declaration value="yes"/>
</output:serialization-parameters>
let $data := <a b="3"/>

Given the variables:

The following call might produce the output shown:

Expression:

serialize($data, $params)

Result:
'<a b="3"/>'

The following call would also produce the output shown (though the second argument could equally well be supplied as an empty map ({}), since both parameters are given their default values):

Expression:
serialize(
  $data,
  { "method": "xml", "omit-xml-declaration": true() }
)
Result:
'<a b="3"/>'
Expression:

serialize({ "a": "AB", "b": "BC" }, { "method": "adaptive" })

Result:
'{"a":"AB","b":"BC"}'
Expression:
serialize(
  array { "a", 3, attribute test { "true" } },
  { "method": "adaptive" 
})
Result:
'["a",3,test="true"]'

14.2 Functions on HTML Data

Changes in 4.0  

  1. A new function is available for processing input data in HTML format.

These functions convert between the lexical representation of HTML and the tree representation.

FunctionMeaning
fn:parse-htmlThis function takes as input an HTML document represented as a string, and returns the document node at the root of an XDM tree representing the parsed document.

14.2.3 fn:parse-html

Changes in 4.0  

  1. New in 4.0  [Issues 74 850 PRs 259 956 10 January 2023]

Summary

This function takes as input an HTML document represented as a string, and returns the document node at the root of an XDM tree representing the parsed document.

Signature
fn:parse-html(
$htmlas (xs:string | xs:hexBinary | xs:base64Binary)?,
$optionsas map(*)?:= { "method": "html", "html-version": 5 }
) as document-node(*:html)?
Properties

This function is ·nondeterministic·, ·context-independent·, and ·focus-independent·.

Rules

If $html is the empty sequence the function returns the empty sequence.

The entries that may appear in the $options map are as follows:

record(
method?as xs:string,
html-version?as (enum('LS') | xs:decimal),
encoding?as xs:string?,
include-template-content?as xs:boolean?
)
KeyMeaning

method?

The approach used to parse the HTML document into XDM nodes.

Note:

An implementation may use this to specify a specific algorithm, tool, or library that is used, such as tidy or tagsoup.

An implementation may also use this to specify a non-standard variant of HTML to support, such as word for the Microsoft Word HTML variant.

  • Type: xs:string

html-version?

The version of HTML to support when parsing HTML strings or sequences of octets.

Valid values an implementation must support for the html method are:

  1. 3, 3.2 for HTML 3.2 W3C Recommendation, 14 January 1997

  2. 4, 4.01 for HTML 4.01 W3C Recommendation, 24 December 1999

  3. 5.0 for HTML5 W3C Recommendation, 28 October 2014

  4. 5.1 for HTML 5.1 W3C Recommendation, 1 November 2016

  5. 5.2 for HTML 5.2 W3C Recommendation, 14 December 2017

  6. LS for HTML Living Standard, WHATWG

  7. 5 may be equivalent to any of 5.0, 5.1, 5.2, or LS

Valid values an implementation must support for the xhtml method are:

  1. 1.0 for XHTML 1.0 W3C Recommendation, 26 January 2000

  2. 1.1 for XHTML 1.1 W3C Recommendation, 31 May 2001

Any other method and html-version combinations are ·implementation-defined·.

  • Type: (enum('LS') | xs:decimal)

encoding?

The character encoding to use to decode a sequence of octets that represents an HTML document.

  • Type: xs:string?

include-template-content?

Defines how to handle elements in the HTMLTemplateElement.content property.

If this option is true, the template element’s children are the children of the content property’s document fragment node.

If this option is false, the template element’s children are the empty sequence.

The default behaviour is ·implementation-defined·.

Note:

This allows an implementation to support the behaviour defined in [HTML: Living Standard] section 4.12.3.1, Interaction of template elements with XSLT and XPath:

  1. This option would default to true for an XSLT processor operating on an HTML DOM constructed from an XHTML document.

  2. This option would default to false for an XPath processor using the [DOM: Living Standard] section 8, XPath APIs.

  • Type: xs:boolean?

If $html is not the empty sequence, an input byte stream is constructed as follows:

  1. If $html is an xs:string, the encoding of the input byte stream is determined in a way consistent with [HTML: Living Standard] section 13.2.3.1, Parsing with a known character encoding to generate the bytes for that string. The specific character encoding is the ·implementation-dependent· encoding corresponding to the implementation's string representation.

  2. If the type of $html is a sequence of octets (xs:hexBinary or xs:base64Binary) the encoding of the input byte stream is determined in a way consistent with [HTML: Living Standard] section 13.2.3.2, Determining the character encoding:

    1. The encoding key of $options is used in step 2 of Determining the character encoding as the user instructing the user agent to override the document’s character encoding with the specified encoding.

    2. If the encoding key of $options is not specified, step 2 of Determining the character encoding is skipped.

The resulting byte stream is then used to construct an XDM representation of the HTML document in a way that is equivalent to:

  1. Tokenizing the byte stream according to the HTML parsing algorithm determined by the method and html-version keys of $options (see below). For { "method": "html", "html-version": "LS" } this will be equivalent to [HTML: Living Standard] section 13.2.5, Tokenization.

  2. Constructing a HTMLDocument object for HTML documents, or an XMLDocument for XML/XHTML documents according to the method's tree construction algorithm from the tokens. For { "method": "html", "html-version": "LS" } this will be equivalent to [HTML: Living Standard] section 13.2.6, Tree construction.

  3. Building an XDM representation of the HTMLDocument or XMLDocument according to the rules in 14.2.1 XDM Mapping from HTML DOM Nodes.

For any given method key of $options the implementation must use a parser and validator consistent with the html-version key of $options. These are:

Valid method and html version combinations
methodhtml-versionDescription
html3, 3.2, 4, 4.01An ·implementation-dependent· parsing algorithm, tree construction, and validation consistent with the specified HTML version.
html5, 5.0, 5.1, 5.2An HTML5 conformant parsing algorithm, tree construction, and validation consistent with the specified HTML version. An implementation may choose to use LS for all these HTML versions.
htmlLSA parsing algorithm, tree construction, and validation consistent with the [HTML: Living Standard].
xhtml1.0, 1.1

An implementation may choose to use an XML parser to directly construct the XDM nodes, and then use an ·implementation-dependent· validation mechanism (such as DTD or XMLSchema) to validate the XHTML DOM tree.

An implementation may also choose to use [HTML: Living Standard] for all these XHTML versions, or some other HTML parser capable of processing XHTML documents.

**

An ·implementation-defined· parsing algorithm, tree construction, and validation consistent with the specified HTML version.

This allows an implementation to provide their own method and html-version combinations. For example, an implementation could use the values "whatwg" and "2023-01-28" for an implementation of the WHATWG HTML Living Standard at a given date.

The function is ·nondeterministic with respect to node identity·: 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:FODC0011] if the content of $html is not a well-formed HTML document.

A dynamic error is raised [err:FODC0012] if the method key of $options is not supported by the implementation.

A dynamic error is raised [err:FODC0012] if a key passed to $options, or the value of that key, is not supported by the implementation.

Notes

If the HTML parser accepts a string as the input then that may be used directly when $html is an xs:string instead of converting the string to a sequence of octets in an ·implementation-dependent· encoding. The HTML parser must not perform character encoding processing on that input, treating the HTML string as being in a known character encoding that matches the encoding of the string.

The WHATWG Encoding specification defines the ISO 8859-1 (latin1) and ASCII encodings as aliases of the windows-1252 encoding.

If the HTML parser accepts a string as the input then that may be used directly when $html is an xs:string instead of converting the string to a sequence of octets in an ·implementation-dependent· encoding. The HTML parser must not perform character encoding processing on that input, treating the HTML string as being in a known character encoding that matches the encoding of the string.

The WHATWG Encoding specification defines the ISO 8859-1 (latin1) and ASCII encodings as aliases of the windows-1252 encoding.

Examples

The expression parse-html(()) returns ().

The expression parse-html("<p>Hello</p>") returns an XDM document node equivalent to the result of parsing the XML <html xmlns='http://www.w3.org/1999/xhtml'><head/><body><p>Hello</p></body></html>

The expression parse-html("<p>Hi</p>", method:="html") is equivalent to parse-html("<p>Hi</p>").

14.3 Functions on JSON Data

The functions listed in this section parse or serialize JSON data.

JSON is a popular format for exchange of structured data on the web: it is specified in [RFC 7159]. This section describes facilities allowing JSON data to be converted to and from XDM values.

This specification describes two ways of representing JSON data losslessly using XDM constructs. The first method uses XDM maps to represent JSON objects, and XDM arrays to represent JSON arrays. The second method represents all JSON constructs using XDM element and attribute nodes.

FunctionMeaning
fn:parse-jsonParses a string supplied in the form of a JSON text, returning the results typically in the form of a map or array.
fn:json-docReads an external resource containing JSON, and returns the result of parsing the resource as JSON.
fn:json-to-xmlParses a string supplied in the form of a JSON text, returning the results in the form of an XML document node.
fn:xml-to-jsonConverts an XML tree, whose format corresponds to the XML representation of JSON defined in this specification, into a string conforming to the JSON grammar.
fn:pinAdapts a map or array so that retrieval operations retain additional information.
fn:labelReturns the label associated with a labeled item, as a map.

Note also:

  • The function fn:serialize has an option to generate JSON output from a structure of maps and arrays.

  • The function fn:elements-to-maps enables arbitrary XML node trees to be converted to trees of maps and arrays suitable for serializing as JSON.

14.3.4 fn:parse-json

Changes in 4.0  

  1. The rules regarding use of non-XML characters in JSON texts have been relaxed.  [Issue 414 PR 546 25 July 2023]

  2. An option is provided to control how the JSON null value should be handled.  [Issue 960 PR 1028 20 February 2024]

  3. An option is provided to control how JSON numbers should be formatted.  [Issues 973 1037 PRs 975 1058 1246 12 March 2024]

  4. The default for the escape option has been changed to false. The 3.1 specification gave the default value as true, but this appears to have been an error, since it was inconsistent with examples given in the specification and with tests in the test suite.  [Issue 1555  11 November 2024]

  5. The order of entries in maps is retained.  [Issue 1651 PR 1703 14 January 2025]

Summary

Parses a string supplied in the form of a JSON text, returning the results typically in the form of a map or array.

Signature
fn:parse-json(
$valueas xs:string?,
$optionsas map(*)?:= {}
) as item()?
Properties

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

Rules

If the second argument is omitted or an empty sequence, the result is the same as calling the two-argument form with an empty map as the value of the $options argument.

The first argument is a JSON text as defined in [RFC 7159], in the form of a string. The function parses this string to return an XDM value.

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

Note:

The result will also be an empty sequence if $value is the string "null".

The $options argument can be used to control the way in which the parsing takes place. The ·option parameter conventions· apply.

The entries that may appear in the $options map are as follows:

record(
liberal?as xs:boolean,
duplicates?as xs:string,
escape?as xs:boolean,
fallback?as (fn(xs:string) as xs:anyAtomicType)?,
null?as item()*,
number-parser?as (fn(xs:untypedAtomic) as item()?)?
)
KeyValueMeaning

liberal?

Determines whether deviations from the syntax of RFC7159 are permitted.
  • Type: xs:boolean

  • Default: false

false The input must consist of an optional byte order mark (which is ignored) followed by a string that conforms to the grammar of JSON-text in [RFC 7159]. An error must be raised [err:FOJS0001] if the input does not conform to the grammar.
true 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.

duplicates?

Determines the policy for handling duplicate keys in a JSON object. To determine whether keys are duplicates, they are compared using the Unicode codepoint collation, after expanding escape sequences, unless the escape option is set to true, in which case keys are compared in escaped form.
  • Type: xs:string

  • Default: use-first

reject An error is raised [err:FOJS0003] if duplicate keys are encountered.
use-first If duplicate keys are present in a JSON object, all but the first of a set of duplicates are ignored.
use-last If duplicate keys are present in a JSON object, all but the last of a set of duplicates are ignored.

escape?

Determines whether special characters are represented in the XDM output in backslash-escaped form.
  • Type: xs:boolean

  • Default: false

false Any ·permitted character· in the input, whether or not it is represented in the input by means of an escape sequence, is represented as an unescaped character in the result. Any other character or codepoint (for example, an unpaired surrogate) is passed to the fallback function as described below; in the absence of a fallback function, it is replaced by U+FFFD (REPLACEMENT CHARACTER, ) .
true JSON escape sequences are used in the result to represent special characters in the JSON input, as defined below, whether or not they were represented using JSON escape sequences in the input. The characters that are considered “special” for this purpose are:
  • all codepoints in the range U+0000 (NULL) to U+001F (IS1) or U+007F (DELETE) to U+009F (APC) ;

  • all codepoints that do not represent ·permitted characters·, including codepoints representing unpaired surrogates;

  • the character U+005C (REVERSE SOLIDUS, BACKSLASH, \) itself.

Such characters are represented using a two-character escape sequence where available (for example, \t), or a six-character escape sequence otherwise (for example \uDEAD). Characters other than these are not escaped in the result, even if they were escaped in the input.

fallback?

Provides a function which is called when the input contains an escape sequence that represents a character that is not a ·permitted character·. It is an error to supply the fallback option if the escape option is present with the value true.
  • Type: (fn(xs:string) as xs:anyAtomicType)?

  • Default: fn { char(0xFFFD) }

User-supplied function The function is called when the JSON input contains character that is not a ·permitted character· It is called once for any surrogate that is not properly paired with another surrogate. The untyped atomic item supplied as the argument will always be a two- or six-character escape sequence, starting with a backslash, that conforms to the rules in the JSON grammar (as extended by the implementation if liberal:true() is specified): for example \b or \uFFFF or \uDEAD.

By default, the escape sequence is replaced with the Unicode REPLACEMENT CHARACTER. The function is not called for an escape sequence that is invalid against the grammar (for example \x0A). The string, which results from invoking fn:string on the result of the function, is inserted into the result in place of the invalid character. The function also has the option of raising a dynamic error by calling fn:error.

null?

Determines how the JSON null value should be represented.
  • Type: item()*

  • Default: ()

Value The supplied XDM value is used to represent the JSON null value. The default representation of null is an empty sequence, which works well in cases where setting a property of an object to null has the same meaning as omitting the property. It works less well in cases where null is used with some other meaning, because expressions such as the lookup operators ? and ?? flatten the result to a single sequence of items, which means that any entries whose value is an empty sequence effectively disappear. The property can be set to any XDM value; a suggested value is the xs:QName value fn:QName("http://www.w3.org/2005/xpath-functions", "null"), which is recognized by the JSON serialization method as representing the JSON value null.

number-parser?

Determines how numeric values should be processed.
  • Type: (fn(xs:untypedAtomic) as item()?)?

  • Default: xs:double#1

User-supplied function 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.

The various structures that can occur in JSON are transformed recursively to XDM values as follows:

  1. A JSON object is converted to a map. The entries in the map correspond to the key/value pairs in the JSON object. The key is always of type xs:string; the associated value may be of any type, and is the result of converting the JSON value by recursive application of these rules. For example, the JSON text { "x": 2, "y": 5 } is transformed to the value { "x": 2, "y": 5 }.

    If duplicate keys are encountered in a JSON object, they are handled as determined by the duplicates option defined above.

    The order of entries is retained.

  2. A JSON array is transformed to an array whose members are the result of converting the corresponding member of the array by recursive application of these rules. For example, the JSON text [ "a", "b", null ] is transformed (by default) to the value [ "a", "b", () ].

  3. A JSON string is converted to an xs:string value. The handling of special characters depends on the escape and fallback options, as described in the table above.

  4. A JSON number is processed using the function supplied in the number-parser option; by default it is converted to an xs:double value using the rules for casting from xs:string to xs:double.

  5. The JSON boolean values true and false are converted to the corresponding xs:boolean values.

  6. The JSON value null is converted to the value given by the null option, which defaults to an empty sequence.

Error Conditions

A dynamic error [err:FOJS0001] occurs if the value of $value does not conform to the JSON grammar, unless the option "liberal":true() is present and the processor chooses to accept the deviation.

A dynamic error [err:FOJS0003] occurs if the option "duplicates": "reject" is present and the value of $value contains a JSON object with duplicate keys.

A dynamic error [err:FOJS0005] occurs if the $options map contains an entry whose key is defined in this specification and whose value is not valid for that key, or if it contains an entry with the key fallback when the option "escape":true() is also present.

Notes

The result of the function will be an instance of one of the following types. An instance of test (or in XQuery, typeswitch) can be used to distinguish them:

The result of the function will be an instance of one of the following types. An instance of test (or in XQuery, typeswitch) can be used to distinguish them:

  • map(xs:string, item()?) for a JSON object

  • array(item()?) for a JSON array

  • xs:string for a JSON string

  • xs:double for a JSON number

  • xs:boolean for a JSON boolean

  • empty-sequence() for a JSON null (or for empty input)

If the input starts with a byte order mark, this function ignores it. The byte order mark may have been added to the data stream in order to facilitate decoding of an octet stream to a character string, but since this function takes a character string as input, the byte order mark serves no useful purpose.

The possibility of the input containing characters that are not valid in XML (for example, unpaired surrogates) arises only when such characters are expressed using JSON escape sequences. This is the only possibility, because the input to the function is an instance of xs:string, which by definition can contain only those characters that are valid in XML.

If the input starts with a byte order mark, this function ignores it. The byte order mark may have been added to the data stream in order to facilitate decoding of an octet stream to a character string, but since this function takes a character string as input, the byte order mark serves no useful purpose.

The possibility of the input containing characters that are not valid in XML (for example, unpaired surrogates) arises only when such characters are expressed using JSON escape sequences. This is the only possibility, because the input to the function is an instance of xs:string, which by definition can contain only those characters that are valid in XML.

Examples
Expression:

parse-json('{ "x": 1, "y": [ 3, 4, 5 ] }')

Result:
{ "x": 1e0, "y": [ 3e0, 4e0, 5e0 ] }
Expression:

parse-json('"abcd"')

Result:
"abcd"
Expression:

parse-json('{ "x": "\\", "y": "\u0025" }')

Result:
{ "x": "\", "y": "%" }
Expression:
parse-json(
  '{ "x": "\\", "y": "\u0025" }',
  { 'escape': true() }
)
Result:
{ "x": "\\", "y": "%" }
Expression:
parse-json(
  '{ "x": "\\", "y": "\u0000" }'
)
Result:
{ "x": "\", "y": char(0xFFFD) }
Expression:
parse-json(
  '{ "x": "\\", "y": "\u0000" }',
  { 'escape': true() }
)
Result:
{ "x": "\\", "y": "\u0000" }
Expression:
parse-json(
  '{ "x": "\\", "y": "\u0000" }',
  { 'fallback': fn($s) { '[' || $s || ']' } }
)
Result:
{ "x": "\", "y": "[\u0000]" }
Expression:
parse-json(
  "1984.2",
  { 'number-parser': fn { xs:integer(round(.)) } }
)
Result:
1984
Expression:
parse-json(
  '[ 1, -1, 2 ]',
  { 'number-parser': fn  { boolean(. >= 0) } }
)
Result:
[ true(), false(), true() ]
Expression:
parse-json('[ "a", null, "b" ]',
  { 'null': xs:QName("fn:null") }
)
Result:
[ "a", xs:QName("fn:null"), "b" ]

14.3.5 fn:json-doc

Changes in 4.0  

  1. Additional options are available, as defined by fn:parse-json.

Summary

Reads an external resource containing JSON, and returns the result of parsing the resource as JSON.

Signature
fn:json-doc(
$sourceas xs:string?,
$optionsas map(*)?:= {}
) as item()?
Properties

This function is ·deterministic·, ·context-dependent·, and ·focus-independent·. It depends on static base URI.

Rules

If the second argument is omitted or an empty sequence, the result is the same as calling the two-argument form with an empty map as the value of the $options argument.

The effect of the two-argument function call fn:json-doc($H, $M)is equivalent to the function composition fn:unparsed-text($H) => fn:parse-json($M); except that:

  1. The function may accept a resource in any encoding. [RFC 7159] requires UTF-8, UTF-16, or UTF-32 to be accepted, but it is not an error if a different encoding is used. Unless external encoding information is available, the function must assume that the encoding is one of UTF-8, UTF-16, or UTF-32, and must distinguish these cases by examination of the initial octets of the resource.

  2. If the resource contains characters that are not ·permitted characters·, then rather than raising an error as fn:unparsed-text#1 does, the function replaces such characters by the equivalent JSON escape sequence prior to parsing.

    Note:

    Equivalently, the implementation can use some other internal representation of strings that allows non-XML characters to be manipulated.

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

Error Conditions

The function may raise any error defined for the fn:unparsed-text or fn:parse-json functions.

Notes

If the input cannot be decoded (that is, converted into a sequence of Unicode codepoints, which may or may not represent characters), then a dynamic error occurs as with the fn:unparsed-text function.

If the input can be decoded, then the possibility still arises that the resulting sequence of codepoints includes codepoints that do not represent characters that are valid in the version of XML that the processor supports. Such codepoints are translated into JSON escape sequences (for example, \uFFFF), and the JSON escape sequence is then passed to the fallback function specified in the $options argument, which in turn defaults to a function that returns the Unicode REPLACEMENT CHARACTER (xFFFD).

If the input cannot be decoded (that is, converted into a sequence of Unicode codepoints, which may or may not represent characters), then a dynamic error occurs as with the fn:unparsed-text function.

If the input can be decoded, then the possibility still arises that the resulting sequence of codepoints includes codepoints that do not represent characters that are valid in the version of XML that the processor supports. Such codepoints are translated into JSON escape sequences (for example, \uFFFF), and the JSON escape sequence is then passed to the fallback function specified in the $options argument, which in turn defaults to a function that returns the Unicode REPLACEMENT CHARACTER (xFFFD).

14.3.6 fn:json-to-xml

Summary

Parses a string supplied in the form of a JSON text, returning the results in the form of an XML document node.

Signature
fn:json-to-xml(
$valueas xs:string?,
$optionsas map(*)?:= {}
) as document-node(fn:*)?
Properties

This function is ·nondeterministic·, ·context-dependent·, and ·focus-independent·. It depends on static base URI.

Rules

If the second argument is omitted or an empty sequence, the result is the same as calling the two-argument form with an empty map as the value of the $options argument.

The first argument is a JSON text as defined in [RFC 7159], in the form of a string. The function parses this string to return an XDM node.

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

The $options argument can be used to control the way in which the parsing takes place. The ·option parameter conventions· apply.

The entries that may appear in the $options map are as follows:

record(
liberal?as xs:boolean,
duplicates?as xs:string,
validate?as xs:boolean,
escape?as xs:boolean,
fallback?as (fn(xs:string) as xs:anyAtomicType)?,
number-parser?as (fn(xs:untypedAtomic) as item()?)?
)
KeyValueMeaning

liberal?

Determines whether deviations from the syntax of RFC7159 are permitted.
  • Type: xs:boolean

  • Default: false

false The input must consist of an optional byte order mark (which is ignored) followed by a string that conforms to the grammar of JSON-text in [RFC 7159]. An error must be raised (see below) if the input does not conform to the grammar.
true 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.

duplicates?

Determines the policy for handling duplicate keys in a JSON object. To determine whether keys are duplicates, they are compared using the Unicode codepoint collation, after expanding escape sequences, unless the escape option is set to true, in which case keys are compared in escaped form.
  • Type: xs:string

  • Default: If validate is true then reject, otherwise retain.

reject An error is raised [err:FOJS0003] if duplicate keys are encountered.
use-first If duplicate keys are present in a JSON object, all but the first of a set of duplicates are ignored.
retain If duplicate keys are present in a JSON object, the XML result of the function will also contain duplicates (making it invalid against the schema). This value is therefore incompatible with the option validate=true [err:FOJS0005]

validate?

Determines whether the generated XML tree is schema-validated.
true 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 C.2 Schema for the result of fn:json-to-xml, or against an ·implementation-defined· schema if the liberal option has the value true.
false Indicates that the resulting XDM instance must be untyped.

escape?

Determines whether special characters are represented in the XDM output in backslash-escaped form.
  • Type: xs:boolean

  • Default: false

false All characters in the input that are valid in the version of XML supported by the implementation, whether or not they are represented in the input by means of an escape sequence, are represented as unescaped characters in the result. Any characters or codepoints that are not valid XML characters (for example, unpaired surrogates) are passed to the fallback function as described below; in the absence of a fallback function, they are replaced by the character U+FFFD (REPLACEMENT CHARACTER, ) . The attributes escaped and escaped-key will not be present in the XDM output.
true JSON escape sequences are used in the result to represent special characters in the JSON input, as defined below, whether or not they were represented using JSON escape sequences in the input. The characters that are considered “special” for this purpose are:
  • all codepoints in the range U+0000 (NULL) to U+001F (IS1) or U+007F (DELETE) to U+009F (APC) ;

  • all codepoints that do not represent characters that are valid in the version of XML supported by the processor, including codepoints representing unpaired surrogates;

  • the backslash character itself (U+005C (REVERSE SOLIDUS, BACKSLASH, \) ).

Such characters are represented using a two-character escape sequence where available (for example, \t), or a six-character escape sequence otherwise (for example \uDEAD). Characters other than these will not be escaped in the result, even if they were escaped in the input. In the result:
  • Any string element whose string value contains a backslash character must have the attribute value escaped="true".

  • Any element that contains a key attribute whose string value contains a backslash character must have the attribute escaped-key="true".

  • The values of the escaped and escaped-key attributes are immaterial when there is no backslash present, and it is never necessary to include either attribute when its value is false.

fallback?

Provides a function which is called when the input contains an escape sequence that represents a character that is not valid in the version of XML supported by the implementation. It is an error to supply the fallback option if the escape option is present with the value true.
  • Type: (fn(xs:string) as xs:anyAtomicType)?

  • Default: fn { char(0xFFFD) }

User-supplied function The function is called when the JSON input contains an escape sequence that is valid according to the JSON grammar, but which does not represent a character that is valid in the version of XML supported by the processor. In the case of surrogates, it is called once for any six-character escape sequence that is not properly paired with another surrogate. The untyped atomic item supplied as the argument will always be a two- or six-character escape sequence, starting with a backslash, that conforms to the rules in the JSON grammar (as extended by the implementation if liberal:true() is specified): for example \b or \uFFFF or \uDEAD.

By default, the escape sequence is replaced with the Unicode REPLACEMENT CHARACTER. The function is not called for an escape sequence that is invalid against the grammar (for example \x0A). The string, which results from invoking fn:string on the result of the function, is inserted into the result in place of the invalid character. The function also has the option of raising a dynamic error by calling fn:error.

number-parser?

Determines how numeric values should be processed.
  • Type: (fn(xs:untypedAtomic) as item()?)?

  • Default: xs:identity#1

User-supplied function The supplied function is called to process the string value of any JSON number in the input. The string value of the number element generated in the result will be the value obtained by calling the supplied function, and then converting its result to a string by calling fn:string#1.

By default, numbers are represented in the XML output exactly as they were written in the input. Supplying the value xs:double#1 will cause the value to be convered to type xs:double (which will then be represented in the XML by converting the xs:double to a string). Similarly xs:decimal#1 will 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. The default value fn:identity#1 causes the value to be retained unchanged as an xs:untypedAtomic. Before calling the supplied number-parser, the value is first checked to ensure that it conforms to the JSON grammar (for example, a leading plus sign and redundant leading zeroes are not allowed); these checks are disabled if the liberal option is set to true. Note that the option validate=true will cause the result to be validated as type xs:double (disallowing NaN and infinity).

The various structures that can occur in JSON are transformed recursively to XDM values according to the rules given in 14.3.2 XML Representation of JSON.

The function returns a document node, whose only child is the element node representing the outermost construct in the JSON text.

The function is ·nondeterministic with respect to node identity·: 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.

The base URI of the returned document node is taken from the static base URI of the function call.

The choice of namespace prefix (or absence of a prefix) in the names of constructed nodes is ·implementation-dependent·.

The XDM tree returned by the function does not contain any unnecessary (albeit valid) nodes such as whitespace text nodes, comments, or processing instructions. It does not include any whitespace in the value of number or boolean element nodes, nor in the value of escaped or escaped-key attribute nodes.

If the result is typed, every element named string will have an attribute named escaped whose value is either true or false, and every element having an attribute named key will also have an attribute named escaped-key whose value is either true or false.

If the result is untyped, the attributes escaped and escaped-key will either be present with the value true, or will be absent. They will never be present with the value false.

Error Conditions

An error is raised [err:FOJS0001] if the value of $value does not conform to the JSON grammar as defined by [RFC 7159], unless the option "liberal":true() is present and the processor chooses to accept the deviation.

An error is raised [err:FOJS0004] if the value of the validate option is true and the processor does not support schema validation or typed data.

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

To read a JSON file, this function can be used in conjunction with the fn:unparsed-text function.

Many JSON implementations allow commas to be used after the last item in an object or array, although the specification does not permit it. The option spec="liberal" is provided to allow such deviations from the specification to be accepted. Some JSON implementations also allow constructors such as new Date("2000-12-13") to appear as values: specifying spec="liberal" allows such extensions to be accepted, but does not guarantee it. If such extensions are accepted, the resulting value is implementation-defined, and will not necessarily conform to the schema at C.2 Schema for the result of fn:json-to-xml.

If the input starts with a byte order mark, this function ignores it. The byte order mark may have been added to the data stream in order to facilitate decoding of an octet stream to a character string, but since this function takes a character string as input, the byte order mark serves no useful purpose.

The possibility of the input containing characters that are not valid in XML (for example, unpaired surrogates) arises only when such characters are expressed using JSON escape sequences. This is the only possibility because the input to the function is an instance of xs:string, which by definition can contain only those characters that are valid in XML.

To read a JSON file, this function can be used in conjunction with the fn:unparsed-text function.

Many JSON implementations allow commas to be used after the last item in an object or array, although the specification does not permit it. The option spec="liberal" is provided to allow such deviations from the specification to be accepted. Some JSON implementations also allow constructors such as new Date("2000-12-13") to appear as values: specifying spec="liberal" allows such extensions to be accepted, but does not guarantee it. If such extensions are accepted, the resulting value is implementation-defined, and will not necessarily conform to the schema at C.2 Schema for the result of fn:json-to-xml.

If the input starts with a byte order mark, this function ignores it. The byte order mark may have been added to the data stream in order to facilitate decoding of an octet stream to a character string, but since this function takes a character string as input, the byte order mark serves no useful purpose.

The possibility of the input containing characters that are not valid in XML (for example, unpaired surrogates) arises only when such characters are expressed using JSON escape sequences. This is the only possibility because the input to the function is an instance of xs:string, which by definition can contain only those characters that are valid in XML.

Examples
Expression:
json-to-xml(
  '{ "x": 1, "y": [ 3, 4, 5 ] }',
  { "validate": false() }
)
Result:
<map xmlns="http://www.w3.org/2005/xpath-functions">
  <number key="x">1</number>
  <array key="y">
   <number>3</number>
   <number>4</number>
   <number>5</number>
  </array>
</map>

(with whitespace added for legibility)

Expression:
json-to-xml(
  '"abcd"',
  { 'liberal': false() }
)
Result:
<string xmlns="http://www.w3.org/2005/xpath-functions">abcd</string>
Expression:
json-to-xml(
  '{ "x": "\\", "y": "\u0025" }',
  { "validate": false() }
)
Result:
<map xmlns="http://www.w3.org/2005/xpath-functions">
  <string key="x">\</string>
  <string key="y">%</string>
</map>

(with whitespace added for legibility)

Expression:
json-to-xml(
  '{ "x": "\\", "y": "\u0025" }',
  { 'escape': true(), "validate": false() }
)
Result:
<map xmlns="http://www.w3.org/2005/xpath-functions">
  <string escaped="true" key="x">\\</string>
  <string key="y">%</string>
</map>

(with whitespace added for legibility)

(But see the detailed rules for alternative values of the escaped attribute on the second string element.)

The following example illustrates use of the fallback function to handle characters that are invalid in XML.

let $json := unparsed-text('http://example.com/endpoint')
let $options := {
  'liberal': true(),
  'fallback': fn($char as xs:string) as xs:string {
    let $c0chars := {
      '\u0000':'[NUL]',
      '\u0001':'[SOH]',
      '\u0002':'[STX]',
      ...
      '\u001E':'[RS]',
      '\u001F':'[US]'
    }
    let $replacement := $c0chars($char)
    return if (exists($replacement)) then (
      $replacement
    ) else (
      error(
        xs:QName('err:invalid-char'),
        'Error: ' || $char || ' is not a C0 control character.'
      )
    )
  }
}
return json-to-xml($json, $options)

14.3.7 fn:xml-to-json

Changes in 4.0  

  1. An option has been added to suppress the escaping of the solidus (forwards slash) character.  [Issue 1347 PR 1353]

  2. Numbers now retain their original lexical form, except for any changes needed to satisfy JSON syntax rules (for example, stripping leading zero digits).  [Issue 1445 PR 1455]

Summary

Converts an XML tree, whose format corresponds to the XML representation of JSON defined in this specification, into a string conforming to the JSON grammar.

Signature
fn:xml-to-json(
$nodeas node()?,
$optionsas map(*)?:= {}
) as xs:string?
Properties

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

Rules

If the second argument is omitted or an empty sequence, the result is the same as calling the two-argument form with an empty map as the value of the $options argument.

The first argument $node is a node; the subtree rooted at this node will typically be the XML representation of a JSON document as defined in 14.3.2 XML Representation of JSON.

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

The $options argument can be used to control the way in which the conversion takes place. The ·option parameter conventions· apply.

The entries that may appear in the $options map are as follows:

record(
escape-solidus?as xs:boolean,
indent?as xs:boolean
)
KeyValueMeaning

escape-solidus?

Determines whether the character U+002F (SOLIDUS, FORWARD SLASH, /) should be escaped as \/. By default the character is escaped, but this is only necessary when the resulting JSON is embedded in HTML.
  • Type: xs:boolean

  • Default: true

false The character U+002F (SOLIDUS, FORWARD SLASH, /) is output as is, without escaping.
true The character U+002F (SOLIDUS, FORWARD SLASH, /) is escaped by preceding it with U+005C (REVERSE SOLIDUS, BACKSLASH, \) .

indent?

Determines whether additional whitespace should be added to the output to improve readability.
  • Type: xs:boolean

  • Default: false

false The processor must not insert any insignificant whitespace between JSON tokens.
true The processor may insert whitespace between JSON tokens in order to improve readability. The specification imposes no constraints on how this is done.

The node supplied as $node must be one of the following: [err:FOJS0006]

  1. An element node whose name matches the name of a global element declaration in the schema given in C.2 Schema for the result of fn:json-to-xml (“the schema”) and that is valid as defined below:

    1. If the type annotation of the element matches the type of the relevant element declaration in the schema (indicating that the element has been validated against the schema), then the element is considered valid.

    2. Otherwise, the processor may attempt to validate the element against the schema, in which case it is treated as valid if and only if the outcome of validation is valid.

    3. Otherwise (if the processor does not attempt validation using the schema), the processor must ensure that the content of the element, after stripping all attributes (at any depth) in namespaces other than http://www.w3.org/2005/xpath-functions, is such that validation against the schema would have an outcome of valid.

      Note:

      The process described here is not precisely equivalent to schema validation. For example, schema validation will fail if there is an invalid xsi:type or xsi:nil attribute, whereas this process will ignore such attributes.

  2. An element node E having a key attribute and/or an escaped-key attribute provided that E would satisfy one of the above conditions if the key and/or escaped-key attributes were removed.

  3. A document node having exactly one element child and no text node children, where the element child satisfies one of the conditions above.

Furthermore, $node must satisfy the following constraint (which cannot be conveniently expressed in the schema). Every element M that is a descendant-or-self of $node and has local name map and namespace URI http://www.w3.org/2005/xpath-functions must satisfy the following rule: there must not be two distinct children of M (say C1 and C2) such that the normalized key of C1 is equal to the normalized key of C2. The normalized key of an element C is as follows:

  • If C has the attribute value escaped-key="true", then the value of the key attribute of C, with all JSON escape sequences replaced by the corresponding Unicode characters according to the JSON escaping rules.

  • Otherwise (the escaped-key attribute of C is absent or set to false), the value of the key attribute of C.

Nodes in the input tree are handled by applying the following rules, recursively. In these rules the term “an element named N” means “an element node whose local name is N and whose namespace URI is http://www.w3.org/2005/xpath-functions”.

  1. A document node having a single element node child is processed by processing that child.

  2. An element named null results in the output null.

  3. An element $E named boolean results in the output true or false depending on the result of xs:boolean(fn:string($E)).

  4. An element $E named number is processed as follows.

    The input is required to conform to the XSD rules defining a valid instance of xs:double (excluding infinity and NaN), while the output is required to conform to the JSON rules defining a valid JSON number. These rules are slightly different.

    Specifically, the XSD rules require the value (after removing leading and trailing whitespace) to match the regular expression:

    (\+|-)?([0-9]+(\.[0-9]*)?|\.[0-9]+)([Ee](\+|-)?[0-9]+)?

    while the JSON rules require:

    -?(0|[1-9][0-9]*)(\.[0-9]+)?([Ee](\+|-)?[0-9]+)?

    If the input value does not match the required JSON format, it must therefore be adjusted by applying the following steps:

    • Remove leading and trailing whitespace.

    • Remove any leading plus sign.

    • Remove any leading zero digits in the integer part, while ensuring that at least one digit remains.

    • If there is a decimal point that is not preceded by a digit, add a zero digit before the decimal point.

    • If there is a decimal point that is not followed by a digit, add a zero digit after the decimal point.

    Note:

    The output uses exponential notation if and only if the input uses exponential notation.

    The rules have changed since version 3.1 of this specification. In previous versions, the supplied number was cast to an xs:double, and then serialized using the rules of the fn:string function. This resulted in JSON numbers using exponential notation for values outside the range 1e-6 to 1e6, and led to a loss of precision for 64-bit integer values.

  5. An element named string results in the output of the string value of the element, enclosed in quotation marks, with any special characters in the string escaped as described below.

  6. An element named array results in the output of the children of the array element, each processed by applying these rules recursively: the items in the resulting list are enclosed between square brackets, and separated by commas.

  7. An element named map results in the output of a sequence of map entries corresponding to the children of the map element, enclosed between curly braces and separated by commas. Each entry comprises the value of the key attribute of the child element, enclosed in quotation marks and escaped as described below, followed by a colon, followed by the result of processing the child element by applying these rules recursively. The order of properties in the output JSON representation retains the order of the children of the map element.

  8. Comments, processing instructions, and whitespace text node children of map and array are ignored.

Strings are escaped as follows:

  1. If the attribute escaped="true" is present for a string value, or escaped-key="true" for a key value, then:

    1. any valid JSON escape sequence present in the string is copied unchanged to the output;

    2. any invalid JSON escape sequence results in a dynamic error [err:FOJS0007];

    3. any unescaped occurrence of U+0022 (QUOTATION MARK, ") , U+0008 (BACKSPACE) , U+000C (FORM FEED) , U+000A (NEWLINE) , U+000D (CARRIAGE RETURN) , U+0009 (TAB) , or (subject to the escape-solidus option) U+002F (SOLIDUS, FORWARD SLASH, /) is replaced by \", \b, \f, \n, \r, \t, or \/ respectively;

    4. any other codepoint in the range 1-31 or 127-159 is replaced by an escape in the form \uHHHH where HHHH is the upper-case hexadecimal representation of the codepoint value.

  2. Otherwise (that is, in the absence of the attribute escaped="true" for a string value, or escaped-key="true" for a key value):

    1. any occurrence of backslash is replaced by \\

    2. any occurrence of U+0022 (QUOTATION MARK, ") , U+0008 (BACKSPACE) , U+000C (FORM FEED) , U+000A (NEWLINE) , U+000D (CARRIAGE RETURN) , or U+0009 (TAB) is replaced by \", \b, \f, \n, \r, or \t respectively;

    3. any other codepoint in the range 1-31 or 127-159 is replaced by an escape in the form \uHHHH where HHHH is the upper-case hexadecimal representation of the codepoint value.

Error Conditions

A dynamic 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.

A dynamic error is raised [err:FOJS0006] if the value of $node is not a document or element node or is not valid according to the schema for the XML representation of JSON, or if a map element has two children whose normalized key values are the same.

A dynamic error is raised [err:FOJS0007] if the value of $node includes a string labeled with escaped="true", or a key labeled with escaped-key="true", where the content of the string or key contains an invalid JSON escape sequence: specifically, where it contains a backslash (\) that is not followed by one of the characters ", \, /, b, f, n, r, t, or u, or where it contains the characters \u not followed by four hexadecimal digits (that is [0-9A-Fa-f]{4}).

Notes

The rule requiring schema validity has a number of consequences, including the following:

The rule requiring schema validity has a number of consequences, including the following:

  1. The input cannot contain no-namespace attributes, or attributes in the namespace http://www.w3.org/2005/xpath-functions, except where explicitly allowed by the schema. Attributes in other namespaces, however, are ignored.

  2. Nodes that do not affect schema validity, such as comments, processing instructions, namespace nodes, and whitespace text node children of map and array, are ignored.

  3. Numeric values are restricted to those that are valid in JSON: the schema disallows positive and negative infinity and NaN.

  4. Duplicate key values are not permitted. Most cases of duplicate keys are prevented by the rules in the schema; additional cases (where the keys are equal only after expanding JSON escape sequences) are prevented by the prose rules of this function. For example, the key values \n and \u000A are treated as duplicates even though the rules in the schema do not treat them as such.

The rule allowing the top-level element to have a key attribute (which is ignored) allows any element in the output of the fn:json-to-xml function to be processed: for example, it is possible to take a JSON document, convert it to XML, select a subtree based on the value of a key attribute, and then convert this subtree back to JSON, perhaps after a transformation. The rule means that an element with the appropriate name will be accepted if it has been validated against one of the types mapWithinMapType, arrayWithinMapType, stringWithinMapType, numberWithinMapType, booleanWithinMapType, or nullWithinMapType.

The rule allowing the top-level element to have a key attribute (which is ignored) allows any element in the output of the fn:json-to-xml function to be processed: for example, it is possible to take a JSON document, convert it to XML, select a subtree based on the value of a key attribute, and then convert this subtree back to JSON, perhaps after a transformation. The rule means that an element with the appropriate name will be accepted if it has been validated against one of the types mapWithinMapType, arrayWithinMapType, stringWithinMapType, numberWithinMapType, booleanWithinMapType, or nullWithinMapType.

Examples

The input <array xmlns="http://www.w3.org/2005/xpath-functions"><number>1</number><string>is</string><boolean>1</boolean></array> produces the result [ 1, "is", true ].

The input <map xmlns="http://www.w3.org/2005/xpath-functions"><number key="Sunday">1</number><number key="Monday">2</number></map> produces the result { "Sunday": 1, "Monday": 2 }.

The input <array xmlns="http://www.w3.org/2005/xpath-functions"><number>10</number><number>17e2</number><number>0005</number></array> produces the result [ 10, 17e2, 5 ].

14.3.8 fn:pin

Changes in 4.0  

  1. New in 4.0  [Issue 960 PR 988 27 February 2024]

Summary

Adapts a map or array so that retrieval operations retain additional information.

Signature
fn:pin(
$inputas (map(*)|array(*))
) as (map(*)|array(*))
Properties

This function is ·nondeterministic·, ·context-independent·, and ·focus-independent·.

Rules

The function creates a deep copy of the supplied map or array, adapted so that navigation within the deep copy returns items that are labeled with additional information about their position within the containing tree structure.

Note:

The formal specification of the function describes it as constructing a deep copy of the entire tree, but a practical implementation is likely to use a lazy evaluation strategy, so the only costs incurred are for items actually selected within the tree.

The function makes use of the concept of labeled items, an extension to the data model described in Section 2.10 Labeled ItemsDM.

The supplied value of $input must be either a map or an array.

The result is as follows:

  1. If $input is a map M, the result is a map M′ derived from M as follows:

    1. Any existing label on M is discarded.

    2. M′ acquires a label having the property pinned set to the value true, and the property id set to an arbitrary xs:string value that is unique within the execution scope.

    3. For every key-value pair (K, V) in M, M′ will have a key-value pair (K, V′) in which the key K is unchanged, and the value V′ is derived from V by applying the function derived-value(M', K, V), defined below.

    4. The entry orderDM of M is retained in M′.

  2. If $input is an array A, the result is an array A′ derived from A as follows:

    1. Any existing label on A is discarded.

    2. A′ acquires a label having the property pinned set to the value true, and the property id set to an arbitrary xs:string value that is unique within the execution scope.

    3. For every member V in A, whose 1-based index position in A is X, A′ will have a member V′ derived from V by applying the function derived-value(A', X, V), defined below.

  3. The id property described in the previous paragraphs is allocated only to the top-level map or array (the one supplied as an explicit argument to the fn:pin function). The function is not·deterministic·: that is, if the function is called twice with the same arguments, it is ·implementation-dependent· whether the same id property is allocated on both occasions.

  4. If $input is anything other than a map or an array, a type error is raised.

  5. The function derived-value(P, K, V) has the following logic. For every item J in V, V′ will contain an item J′ that is derived from J as follows:

    1. Let TEMP be:

      1. If J is a map or array, then fn:pin(J).

        Note:

        Note however that the id property of TEMP is not used, so there is no need to generate it.

      2. Otherwise, J.

    2. J′ is then a labeled item having the same subject as TEMP, together with a label having the following properties:

      pinned

      true

      key

      K

      position

      The 1-based position of J within V.

      parent

      P

      ancestors

      A zero-arity function item delivering the value of (?parent, ?parent ! label(.)?ancestors()).

      path

      A zero-arity function item delivering the value of (?parent ! label(.)?path(), ?key).

Notes

The effect of calling pin on a map or array is that subsequent retrieval operations within the pinned map or array return labeled results, whose labels contain useful information about where the results were found. For example, an expression such as json-doc($source)??name will return the values of all entries in the JSON tree having the key "name"; but very little can be done with this information because the result is simply a sequence of (typically) strings with no context. By contrast, the result of pin(json-doc($source))??name is the same set of strings, labeled with information about where they were found. For example, if $result is the result of the expression pin(json-doc($source))??name, then:

The effect of calling pin on a map or array is that subsequent retrieval operations within the pinned map or array return labeled results, whose labels contain useful information about where the results were found. For example, an expression such as json-doc($source)??name will return the values of all entries in the JSON tree having the key "name"; but very little can be done with this information because the result is simply a sequence of (typically) strings with no context. By contrast, the result of pin(json-doc($source))??name is the same set of strings, labeled with information about where they were found. For example, if $result is the result of the expression pin(json-doc($source))??name, then:

  • $result => label()?parent?ssn locates the map that contained each name, and returns the value of the ssn entry in that map.

  • $result => label()?ancestors()?course returns the values of any course entries in containing maps.

  • $result => label()?path() returns a sequence of map keys and array index values representing the location of the found entries within the JSON structure.

Editorial note 
The id property on the root of a pinned map or array is intended to support deep update operations, which have not yet been defined.
Editorial note 
The id property on the root of a pinned map or array is intended to support deep update operations, which have not yet been defined.
Examples
Expression:

pin([ "a", "b", "c" ])?1 ! label(.)?parent ! array:foot(.)

Result:
"c"
Expression:

pin([ "a", "b", "c", "d" ]) ! array:remove(., 2)?* ! label(.)?key

Result:
1, 3, 4
Expression:
let $data := {
  "fr": { "capital": "Paris", "languages": [ "French" ] }, 
  "de": { "capital": "Berlin", "languages": [ "German" ] }
}
return pin($data)??languages[. = 'German'] ! label(.)?path()[1]
Result:
"de"

14.3.9 fn:label

Changes in 4.0  

  1. New in 4.0  [Issue 960 PR 988 27 February 2024]

Summary

Returns the label associated with a labeled item, as a map.

Signature
fn:label(
$inputas item()?
) as map(xs:string, item()*)?
Properties

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

Rules

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

If $input is an item that has no label, the function returns an empty map.

If $input is a labeled item, the function returns the label, as a map.

Notes

The function makes use of the concept of labeled items, an extension to the data model described in Section 2.10 Labeled ItemsDM.

The data model allows any item to be labeled, and allows the label to be any map with string-valued keys. Currently the only operation that creates labeled values is the fn:pin function. For examples illustrating the use of fn:label, see fn:pin.

The function makes use of the concept of labeled items, an extension to the data model described in Section 2.10 Labeled ItemsDM.

The data model allows any item to be labeled, and allows the label to be any map with string-valued keys. Currently the only operation that creates labeled values is the fn:pin function. For examples illustrating the use of fn:label, see fn:pin.

14.4 Functions on CSV Data

Changes in 4.0  

  1. New functions are available for processing input data in CSV (comma separated values) format.   [Issue 413 PRs 533 719 834]

This section describes functions that parse CSV data.

[Definition] The term comma separated values or CSV refers to a wide variety of plain-text tabular data formats with fields and records separated by standard character delimiters (often, but not invariably, commas).

A CSV is a 2-dimensional tabular data structure consisting of multiple rows (also known as records). Each row contains multiple fields. Fields occupying the same position in successive rows constitute a column. Columns are identified by position and optionally by name. Column names can be assigned within a CSV using an optional header row.

CSV has developed informally for decades, and many variations are found. This specification refers to [RFC 4180], which provides a standardized grammar. This specification extends the grammar defined in [RFC 4180] as follows:

  • This specification uses the term row where RFC 4180 uses record.

  • Line endings are normalized: specifically, the character sequences U+000D (CARRIAGE RETURN) , or U+000D (CARRIAGE RETURN) followed by U+000A (NEWLINE) , are converted to a single U+000A (NEWLINE) character. This applies whether or not the line ending appears within a quoted string, and whether or not U+000A (NEWLINE) is the chosen row delimiter.

  • Row delimiters other than newline are recognized.

  • Field delimiters other than U+002C (COMMA, ,) are recognized.

  • Quote characters other than U+0022 (QUOTATION MARK, ") are recognized.

  • Non-ASCII characters are recognized.

This specification defines a mapping from this extended grammar to constructs in the XDM model, and provides illustrative examples of how these constructs can be combined with other language features to process CSV data.

FunctionMeaning
fn:csv-to-arraysParses CSV data supplied as a string, returning the results in the form of a sequence of arrays of strings.
fn:parse-csvParses CSV data supplied as a string, returning the results in the form of a record containing information about the names in the header, as well as the data itself.
fn:csv-to-xmlParses CSV data supplied as a string, returning the results as an XML document, as described by 14.4.8 Representing CSV data as XML.

The most basic function for parsing CSV is fn:csv-to-arrays which recognizes the delimiters for rows and fields and returns a sequence of arrays each corresponding to one row. The fields within each array are represented as instances of xs:string.

The other two functions recognize column names, and make it easier to address individual fields using these names. The parse-csv function delivers this capability using XDM maps and functions, while csv-to-xml function represents the information using XDM element nodes.

14.4.4 fn:csv-to-arrays

Changes in 4.0  

  1. New in 4.0  [Issues 413 1052 PRs 533 719 834 1066]

Summary

Parses CSV data supplied as a string, returning the results in the form of a sequence of arrays of strings.

Signature
fn:csv-to-arrays(
$valueas xs:string?,
$optionsas map(*)?:= {}
) as array(xs:string)*
Properties

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

Rules

The $value argument is CSV data, as defined in [RFC 4180], in the form of an xs:string value. The function parses this string, after normalizing newlines so that U+000D (CARRIAGE RETURN) and (U+000D (CARRIAGE RETURN) , U+000A (NEWLINE) ) sequences are converted to U+000A (NEWLINE) . The result of the function is a sequence of arrays of strings, that is array(xs:string)*; each array represents one row of the CSV input.

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

The $options argument can be used to control the way in which the parsing takes place. The ·option parameter conventions· apply.

If the $options argument is omitted or an empty sequence, the result is the same as calling the two-argument form with an empty map as the value of the $options argument.

The entries that may appear in the $options map are as follows:

record(
field-delimiter?as xs:string,
row-delimiter?as xs:string,
quote-character?as xs:string,
trim-whitespace?as xs:boolean
)
KeyValueMeaning

field-delimiter?

The character used to delimit fields within a record. An instance of xs:string whose length is exactly one.
  • Type: xs:string

  • Default: ","

row-delimiter?

The character used to delimit rows within the CSV string. An instance of xs:string whose length is exactly one. Defaults to a single newline character (U+000A (NEWLINE) ).
  • Type: xs:string

  • Default: char('\n')

quote-character?

The character used to quote fields within the CSV string. An instance of xs:string whose length is exactly one.
  • Type: xs:string

  • Default: '"'

trim-whitespace?

Determines whether leading and trailing whitespace is removed from the content of unquoted fields.
  • Type: xs:boolean

  • Default: false

falseUnquoted fields will be returned with any leading or trailing whitespace intact.
trueUnquoted fields will be returned with leading or trailing whitespace removed, and all other whitespace preserved.

An empty field is represented by a zero-length string. An empty field is deemed to exist when a field delimiter immediately follows either another field delimiter, or a row delimiter, or the start of $value; or when a row delimiter or the end of $value immediately follows a field delimiter.

A blank row is represented as an empty array (not as an array containing a single empty field). A blank row is deemed to exist when a row delimiter immediately follows either another row delimiter or the start of $value, after trimming of whitespace if the trim-whitespace option is true. No blank row occurs after the final row delimiter.

If $value is a zero-length string, the CSV is considered to contain no rows; while if $value consists of a single row delimiter, it is considered to contain a single blank row. The presence or absence of a final row delimiter generally has no effect on the result, except when it appears at the start of the input, in which case it causes a single blank row to exist.

Error Conditions

A dynamic error [err:FOCV0001] occurs if the value of $csv does not conform to the required grammar.

A dynamic error [err:FOCV0002] occurs if the value of the field-delimiter, row-delimiter, or quote-character option is not a single character.

A dynamic error [err:FOCV0003] occurs if the same character is used for more than one of the field-delimiter, row-delimiter, and quote-character.

Notes

The default row delimiter is a single newline character U+000A (NEWLINE) . Alternative line endings such as CR and CRLF will already have been normalized to a single newline.

All fields are returned as xs:string values.

Quoted fields in the input are returned without the quotes.

The first row is not treated specially.

For more discussion of the returned data, see 14.4.3 Basic parsing of CSV to arrays.

The default row delimiter is a single newline character U+000A (NEWLINE) . Alternative line endings such as CR and CRLF will already have been normalized to a single newline.

All fields are returned as xs:string values.

Quoted fields in the input are returned without the quotes.

The first row is not treated specially.

For more discussion of the returned data, see 14.4.3 Basic parsing of CSV to arrays.

Examples

Handling trivial input:

Expression:
csv-to-arrays(())
Result:
()
Expression:
csv-to-arrays("")
Result:
()
Expression:
csv-to-arrays(char('\n'))
Result:
[]
Expression:
csv-to-arrays(" ", { 'trim-whitespace': true() })
Result:
()
Expression:
csv-to-arrays(" ", { 'trim-whitespace': false() })
Result:
[" "]
Expression:
csv-to-arrays(` {char('\n')}`, { 'trim-whitespace': true() })
Result:
[]
Expression:
csv-to-arrays(` {char('\n')}`, { 'trim-whitespace': false() })
Result:
[" "]
Expression:
csv-to-arrays(`{char('\n')} `, { 'trim-whitespace': true() })
Result:
[]
Expression:
csv-to-arrays(`{char('\n')} `, { 'trim-whitespace': false() })
Result:
[], [" "]

Using newline separators:

Expression:
csv-to-arrays(
  `name,city{ char('\n') }` ||
  `Bob,Berlin{ char('\n') }` ||
  `Alice,Aachen{ char('\n') }`
)
Result:
[ "name", "city" ],
[ "Bob", "Berlin" ],
[ "Alice", "Aachen" ]
Expression:
let $CRLF := `{ char('\r') }{ char('\n') }`
return csv-to-arrays(
  `name,city{ $CRLF }` ||
  `Bob,Berlin{ $CRLF }` ||
  `Alice,Aachen{ $CRLF }`
)
Result:
[ "name", "city" ],
[ "Bob", "Berlin" ],
[ "Alice", "Aachen" ]

Quote handling:

Expression:
csv-to-arrays(
  string-join(
    (`"name","city"`, `"Bob","Berlin"`, `"Alice","Aachen"`),
    char('\n')
  )
)
Result:
[ "name", "city" ],
[ "Bob", "Berlin" ],
[ "Alice", "Aachen" ]
Expression:
csv-to-arrays(
  `"name","city"{ char('\n') }` ||
  `"Bob ""The Exemplar"" Mustermann","Berlin"{ char('\n') }`
)
Result:
(
  [ "name", "city" ],
  [ 'Bob "The Exemplar" Mustermann', "Berlin" ]
)

Non-default record- and field-delimiters:

Expression:
csv-to-arrays(
  "name;city§Bob;Berlin§Alice;Aachen", 
  { "row-delimiter": "§", "field-delimiter": ";" }
)
Result:
[ "name", "city" ],
[ "Bob", "Berlin" ],
[ "Alice", "Aachen" ]

Non-default quote character:

Expression:
csv-to-arrays(
  string-join(
    ("|name|,|city|", "|Bob|,|Berlin|"),
    char('\n')
  ), 
  { "quote-character": "|" }
)
Result:
[ "name", "city" ],
[ "Bob", "Berlin" ]

Trimming whitespace in fields:

Expression:
csv-to-arrays(
  string-join(
    ("name  ,city    ", "Bob   ,Berlin  ", "Alice ,Aachen  "),
    char('\n')
  ),
  { "trim-whitespace": true() }
)
Result:
[ "name", "city" ],
[ "Bob", "Berlin" ],
[ "Alice", "Aachen" ]

14.4.7 fn:parse-csv

Changes in 4.0  

  1. New in 4.0  [Issues 413 1052 PRs 533 719 834 1066 19 March 2024]

Summary

Parses CSV data supplied as a string, returning the results in the form of a record containing information about the names in the header, as well as the data itself.

Signature
fn:parse-csv(
$valueas xs:string?,
$optionsas map(*)?:= {}
) as parsed-csv-structure-record
Properties

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

Rules

The $value argument is CSV data, as defined in [RFC 4180], in the form of an xs:string value. The function first parses this string using fn:csv-to-arrays, and then further processes the result. The initial parsing is exactly as defined for fn:csv-to-arrays, and can be controlled using the same options. Additional options are available to control the way in which header information and column names are handled.

If $value is the empty sequence or a zero-length string, the function returns a parsed-csv-structure-record whose rows entry is the empty sequence.

The $options argument can be used to control the way in which the parsing takes place. The ·option parameter conventions· apply.

If the $options argument is omitted or is an empty sequence, the result is the same as calling the two-argument form with an empty map as the value of the $options argument.

The entries that may appear in the $options map are as follows:

record(
field-delimiter?as xs:string,
row-delimiter?as xs:string,
quote-character?as xs:string,
trim-whitespace?as xs:boolean,
header?as item()*,
select-columns?as xs:positiveInteger*,
trim-rows?as xs:boolean
)
KeyValueMeaning

field-delimiter?

The character used to delimit fields within a record. An instance of xs:string whose length is exactly one.
  • Type: xs:string

  • Default: ","

row-delimiter?

The character used to delimit rows within the CSV string. An instance of xs:string whose length is exactly one. Defaults to a single newline character (U+000A (NEWLINE) ). Note that this is tested after line endings are normalized.
  • Type: xs:string

  • Default: char('\n')

quote-character?

The character used to quote fields within the CSV string. An instance of xs:string whose length is exactly one.
  • Type: xs:string

  • Default: '"'

trim-whitespace?

Determines whether leading and trailing whitespace is removed from the content of unquoted fields.
  • Type: xs:boolean

  • Default: false

falseUnquoted fields will be returned with any leading or trailing whitespace intact.
trueUnquoted fields will be returned with leading or trailing whitespace removed, and all other whitespace preserved.

header?

Determines whether the first row of the CSV should be treated as a list of column names, or whether column names are being supplied by the caller. The value must either be a single boolean, or a sequence of zero or more strings.
  • Type: item()*

  • Default: false

trueColumn names are taken from the first row of the CSV data.
falseColumn names are not available; all references to columns are by ordinal position.
xs:string*Supplies explicit names for the columns. The Nth name in the list applies to the Nth column after any filtering or rearrangement. A zero-length string can be used when there is a column that requires no name.

select-columns?

A sequence of integers indicating which columns to include and in which order. If this option is absent or empty, all columns are returned in their original order. For example, the value 1 to 4 indicates that the output contains the first, second, third, and fourth columns from the input, in order, while (1, 5, 4) indicates that the output contains three columns, taken from the first, fifth, and fourth columns of the input, in that order. An integer in the sequence is treated as the 1-based index of the column to include. Any other columns are dropped. If a particular row includes no field at the specified index, an empty field is included at the relevant position in the result. If an integer appears more than once then the result will include duplicated columns.
  • Type: xs:positiveInteger*

  • Default: ()

trim-rows?

Determines whether all rows should be adjusted to contain the same number of fields. This option is ignored if select-columns is specified.
  • Type: xs:boolean

  • Default: false

falseNo padding or trimming of rows takes place, unless requested using the select-columns option.
trueThe number of fields in the first row (whether this be a header or a data row) determines the number of fields in every subsequent row; to achieve this, excess fields are removed, or additional zero-length fields are added.

The result of the function is a parsed-csv-structure-record, as defined in 14.4.6 Record fn:parsed-csv-structure-record.

Error Conditions

A dynamic error [err:FOCV0001] occurs if the value of $csv does not conform to the required grammar.

A dynamic error [err:FOCV0002] occurs if any of the options field-delimiter, row-delimiter, or quote-character is not a single character.

A dynamic error [err:FOCV0003] occurs if the same character is used for more than one of the options field-delimiter, row-delimiter, and quote-character.

Notes

The default row delimiter is a single newline character U+000A (NEWLINE) . Alternative line endings such as CR and CRLF will already have been normalized to a single newline.

All fields are returned as xs:string values.

Quoted fields in the input are returned without the quotes.

For more discussion of the returned data, see 14.4.5 Enhanced parsing of CSV data to maps and arrays.

The default row delimiter is a single newline character U+000A (NEWLINE) . Alternative line endings such as CR and CRLF will already have been normalized to a single newline.

All fields are returned as xs:string values.

Quoted fields in the input are returned without the quotes.

For more discussion of the returned data, see 14.4.5 Enhanced parsing of CSV data to maps and arrays.

Examples
Variables
let $display := fn($result) {
   (: tidy up the result for display (function items cannot be properly displayed) :)         
   map:put($result, "get", "(: function :)")
}

Default delimiters, no column headers:

Expression:
let $input := string-join(
  ("name,city", "Bob,Berlin", "Alice,Aachen"),
  char('\n')
)
let $result := parse-csv($input)
return (
  $result => $display(),
  $result?get(1, 2),
  $result?get(2, 2)
)
Result:
{
  "columns": (),
  "column-index": {},
  "rows": ([ "name", "city" ], [ "Bob", "Berlin" ], [ "Alice", "Aachen" ]),
  "get": "(: function :)"
},
"city",
"Berlin"

Default delimiters, column headers:

Expression:
let $input := string-join(
  ("name,city", "Bob,Berlin", "Alice,Aachen"),
  char('\n')
)
let $result := parse-csv($input, { "header": true() })
return (
  $result => $display(),
  $result?get(1, "name"),
  $result?get(2, "city")
)
Result:
{
  "columns": ("name", "city"),
  "column-index": { "name": 1, "city": 2 },
  "rows": ([ "Bob", "Berlin" ], [ "Alice", "Aachen" ]),
  "get": "(: function :)"
},
"Bob",
"Aachen"

Custom delimiters, no column headers:

Expression:
let $options := {
  "row-delimiter": "§", 
  "field-delimiter": ";", 
  "quote-character": "|"
}
let $input := "|name|;|city|§|Bob|;|Berlin|§|Alice|;|Aachen|"
let $result := parse-csv($input, $options)
return (
  $result => $display(),
  $result?get(3, 1)
)
Result:
{
  "columns": (),
  "column-index": {},
  "rows": ([ "name", "city" ], [ "Bob", "Berlin" ], [ "Alice", "Aachen" ]),
  "get": "(: function :)"
},
"Alice"

Supplied column names:

Expression:
let $headers := ("Person", "Location")
let $options := { "header": $headers, "row-delimiter": ";" }
let $input := "Alice,Aachen;Bob,Berlin;"
let $parsed-csv := parse-csv($input, $options)
return (
  $parsed-csv => $display(), 
  $parsed-csv?get(2, "Location")
)
Result:
{
  "columns": ("Person", "Location"),
  "column-index": { "Person": 1, "Location": 2 },
  "rows": ([ "Alice", "Aachen" ], [ "Bob", "Berlin" ]),
  "get": "(: function :)"                  
},
"Berlin"

Filtering columns, with ragged input and header: true()

Expression:
let $input := string-join((
   "date,name,city,amount,currency,original amount,note",
   "2023-07-19,Bob,Berlin,10.00,USD,13.99",
   "2023-07-20,Alice,Aachen,15.00",
   "2023-07-20,Charlie,Celle,15.00,GBP,11.99,cake,not a lie"
), char('\n'))
let $options := { 
  "header": true(), 
  "select-columns": (2, 1, 4)
}
let $result := parse-csv($input, $options)
return (
  $result => $display(),
  $result?get(2, "amount")
)
Result:
{
  "columns": ("name", "date", "amount"),
  "column-index": { "name": 1, "date": 2, "amount": 3 },
  "rows": (
    [ "Bob", "2023-07-19", "10.00" ],
    [ "Alice", "2023-07-20", "15.00" ],
    [ "Charlie", "2023-07-20", "15.00" ]
  ),
  "get": "(: function :)"                  
},
"15.00"

Filtering columns, with supplied column map

Expression:
let $input := string-join((
  "2023-07-20,Alice,Aachen,15.00",                  
  "2023-07-19,Bob,Berlin,10.00,USD,13.99",
  "2023-07-20,Charlie,Celle,15.00,GBP,11.99,cake,not a lie"
), char('\n'))
let $options := { 
  "header": ( "Person", "", "Amount" ),
  "select-columns": (2, 1, 4)
}
let $result := parse-csv($input, $options)
return (
  $result => $display(),
  $result?get(2, "Person"),
  $result?get(2, "Amount")
)
Result:
{
  "columns": ("Person", "", "Amount"),
  "column-index": { "Person": 1, "Amount": 3 },
  "rows": ([ "Alice", "2023-07-20", "15.00" ], 
           [ "Bob", "2023-07-19", "10.00" ], 
           [ "Charlie", "2023-07-20", "15.00" ]),
  "get": "(: function :)"                  
},
"Bob",
"10.00"

Specifying the number of columns explicitly, with header: false()

Expression:
let $input := string-join((
  "date,      name,     amount,    currency,   original amount",               
  "2023-07-19,Bob,      10.00,     USD,        13.99",
  "2023-07-20,Alice,    15.00",
  "2023-07-20,Charlie,  15.00,     GBP,        11.99,             extra data"
), char('\n'))
let $options := {
  "header": false(), 
  "select-columns": 1 to 5, 
  "trim-whitespace" :true()
}
let $result := parse-csv($input, $options)
return (
  $result => $display(),
  $result?get(4, 3)
)
Result:
{
  "columns": (),
  "column-index": {},
  "rows": (
    [ "date", "name", "amount", "currency", "original amount" ],
    [ "2023-07-19", "Bob", "10.00", "USD", "13.99" ],
    [ "2023-07-20", "Alice", "15.00", "", "" ],
    [ "2023-07-20", "Charlie", "15.00", "GBP", "11.99" ]
  ),
  "get": "(: function :)"                  
},
"15.00"

Specifying the number of columns with a number and header: true()

Expression:
let $input := string-join((
  "date,name,city,amount,currency,original amount,note",               
  "2023-07-19,Bob,Berlin,10.00,USD,13.99",
  "2023-07-20,Alice,Aachen,15.00",
  "2023-07-20,Charlie,Celle,15.00,GBP,11.99,cake,not a lie"
), char('\n'))
let $options := { "header": true(), "select-columns": 1 to 6 }
let $result := parse-csv($input, $options)
return (
  $result => $display(),
  $result?get(3, "original amount")
)
Result:
{
  "columns": ("date", "name", "city", 
              "amount", "currency", "original amount"),
  "column-index": {
    "date": 1, "name": 2, "city": 3, "amount": 4,
    "currency": 5, "original amount": 6
  },
  "rows": (
    [ "2023-07-19", "Bob", "Berlin", "10.00", "USD", "13.99"],
    [ "2023-07-20", "Alice", "Aachen", "15.00", "", ""],
    [ "2023-07-20", "Charlie", "Celle", "15.00", "GBP", "11.99"]
  ),
  "get": "(: function :)"                  
},
"11.99"

15 Context functions

The following functions are defined to obtain information from the static or dynamic context.

FunctionMeaning
fn:positionReturns the context position from the dynamic context.
fn:lastReturns the context size from the dynamic context.
fn:current-dateTimeReturns the current date and time (with timezone).
fn:current-dateReturns the current date.
fn:current-timeReturns the current time.
fn:implicit-timezoneReturns the value of the implicit timezone property from the dynamic context.
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:static-base-uriThis function returns the value of the executable base URI property from the dynamic context.

15.2 fn:last

Summary

Returns the context size from the dynamic context.

Signature
fn:last() as xs:integer
Properties

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

Rules

Returns the context size from the dynamic context. (See Section C.2 Dynamic Context Components XP31.)

Error Conditions

A type error is raised [err:XPDY0002]XP if the context size is absentDM.

Notes

Under most circumstances, the context size is absent only if the context value is absent. However, XSLT 3.0 with streaming defines situations in which the context value and context position are known, but the context size is unknown.

Under most circumstances, the context size is absent only if the context value is absent. However, XSLT 3.0 with streaming defines situations in which the context value and context position are known, but the context size is unknown.

Examples
ExpressionResult
(1 to 20)[last() - 1]
19

15.3 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 Section C.2 Dynamic Context Components XP31.) 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

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

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.

15.4 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

The returned date will always have an associated timezone, which will always be the same as the implicit timezone in the dynamic context

Examples

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.

15.5 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

The returned time will always have an associated timezone, which will always be the same as the implicit timezone in the dynamic context

Examples

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.

15.7 fn:default-collation

Summary

Returns the value of the default collation property from the dynamic context.

Signature
fn:default-collation() as xs:string
Properties

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

Rules

Returns the value of the default collation property from the dynamic context context. Components of the dynamic context are described in Section 2.2.2 Dynamic ContextXP.

Notes

The default collation property can never be absent. If it is not explicitly defined, a system defined default can be invoked. If this is not provided, the Unicode codepoint collation (http://www.w3.org/2005/xpath-functions/collation/codepoint) is used.

In most cases, the default collation is known statically, and a call on this function can therefore be pre-evaluated during static analysis. The only notable exception is when a call on default-collation() is used to define the default value of a parameter to a user-defined function. In this case it is interpreted as a reference to the default collation in the context of the relevant function call, which may differ from the default collation of the function definition.

The default collation property can never be absent. If it is not explicitly defined, a system defined default can be invoked. If this is not provided, the Unicode codepoint collation (http://www.w3.org/2005/xpath-functions/collation/codepoint) is used.

In most cases, the default collation is known statically, and a call on this function can therefore be pre-evaluated during static analysis. The only notable exception is when a call on default-collation() is used to define the default value of a parameter to a user-defined function. In this case it is interpreted as a reference to the default collation in the context of the relevant function call, which may differ from the default collation of the function definition.

15.8 fn:default-language

Summary

Returns the value of the default language property from the dynamic context.

Signature
fn:default-language() as xs:language
Properties

This function is ·deterministic·, ·context-dependent·, and ·focus-independent·. It depends on default language.

Rules

Returns the value of the default language property from the dynamic context. Components of the dynamic context are described in Section 2.1.2 Dynamic Context XP31.

Notes

The default language property can never be absent. The functions fn:format-integer, fn:format-date, fn:format-time, and fn:format-dateTime are defined to use the default language if no explicit language is supplied. The default language may play a role in selection of a default collation, but this is not a requirement.

The default language property can never be absent. The functions fn:format-integer, fn:format-date, fn:format-time, and fn:format-dateTime are defined to use the default language if no explicit language is supplied. The default language may play a role in selection of a default collation, but this is not a requirement.

15.9 fn:static-base-uri

Summary

This function returns the value of the executable base URI property from the dynamic context.

Signature
fn:static-base-uri() as xs:anyURI?
Properties

This function is ·deterministic·, ·context-dependent·, and ·focus-independent·. It depends on static base URI.

Rules

The function (despite its name) returns the value of the executable base URI property from the dynamic context. If the property is absent, the empty sequence is returned.

Components of the dynamic context are described in Section 2.2.2 Dynamic ContextXP .

Notes

The executable base URI will in many cases be the same as the static base URI in the static context. However, XQuery and XSLT give an implementation freedom to use different base URIs during the static analysis phase and the dynamic evaluation phase, that is, for retrieval of compile-time and run-time resources respectively. This is appropriate when the implementation allows the output of static analysis (a “compiled” query or stylesheet) to be deployed for execution to a different location from the one where static analysis took place. In this situation, the fn:static-base-uri function should return a URI suitable for locating resources needed during dynamic evaluation.

If a call on the fn:static-base-uri function appears within the expression used to define the value of an optional parameter to a user-defined function, then the value supplied to the function (if the argument is omitted) will be the executable base URI from the dynamic context of the function caller. This allows such a function to resolve relative URIs supplied in other parameters to the same function.

The executable base URI will in many cases be the same as the static base URI in the static context. However, XQuery and XSLT give an implementation freedom to use different base URIs during the static analysis phase and the dynamic evaluation phase, that is, for retrieval of compile-time and run-time resources respectively. This is appropriate when the implementation allows the output of static analysis (a “compiled” query or stylesheet) to be deployed for execution to a different location from the one where static analysis took place. In this situation, the fn:static-base-uri function should return a URI suitable for locating resources needed during dynamic evaluation.

If a call on the fn:static-base-uri function appears within the expression used to define the value of an optional parameter to a user-defined function, then the value supplied to the function (if the argument is omitted) will be the executable base URI from the dynamic context of the function caller. This allows such a function to resolve relative URIs supplied in other parameters to the same function.

16 Higher-order functions

16.1 Functions on functions

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-annotationsReturns the annotations of the function item.

16.1.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 an 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 Section 4.5.2.4 Named Function ReferencesXP). 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(xs:QName("fn:name"), 0) if the context value is absent, and [err:FODC0001] is raised for the call function-lookup(xs:QName("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.

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(xs:QName('fn:substring'), 2)('abcd', 2)

Result:
'bcd'

The expression (fn:function-lookup(xs:QName('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.

The expression

let $f := function-lookup(xs:QName('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 an empty sequence otherwise.

16.1.4 fn:function-annotations

Changes in 4.0  

  1. Changes the function to return a sequence of key-value pairs rather than a map.  [Issue 36 PR 710 17 September 2023]

  2. Changes the function to return a sequence of key-value pairs rather than a map.  [Issue 1391 PR 1393 19 August 2024]

Summary

Returns the annotations of the function item.

Signature
fn:function-annotations(
$functionas fn(*)
) as map(xs:QName, xs:anyAtomicType*)*
Properties

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

Rules

The fn:function-annotations function returns the annotations of $function as a sequence of singleton maps, each associating the name of a function annotation with the value of the annotation. Note that several annotations on a function can share the same name. The order of the annotations is retained.

The result is a sequence of singleton maps, each being an instance of map(xs:QName, xs:anyAtomicType*). If a function (for example, a built-in function) has no annotations, the result of the function is an empty sequence.

For each annotation, a map is returned, with a single entry. The key of the map entry is the name of the annotation as an xs:QName. The value of the entry is the the value of the annotation as a sequence of atomic items. If the annotation has no values, the associated value is an empty sequence.

Notes

In the common case where the annotation names are all unique, the result of the function can readily be converted into single map by applying the function map:merge.

In the common case where the annotation names are all unique, the result of the function can readily be converted into single map by applying the function map:merge.

Examples
Expression:
function-annotations(true#0)
Result:
()
Expression:
declare %private function local:inc($c) { $c + 1 };
function-annotations(local:inc#1)
Result:
{ QName("http://www.w3.org/2012/xquery", "private"), () }
Expression:
let $old := %local:deprecated('0.1', '0.2') fn() {}
let $ann := function-annotations($old)
return map:of-pairs($ann)
Result:
{ QName("http://www.w3.org/2005/xquery-local-functions", "deprecated"):
    ("0.1", "0.2") 
}

16.2 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:chainApplies a sequence of functions starting with an initial input.
fn:do-untilProcesses a supplied value repeatedly, continuing when some condition is false, and returning the value that satisfies the condition.
fn:everyReturns true if every item in the input sequence matches a supplied predicate.
fn:filterReturns those items from the sequence $input for which the supplied function $predicate returns true.
fn:fold-leftProcesses the supplied sequence from left to right, applying the supplied function repeatedly to each item in turn, together with an accumulated result value.
fn:fold-rightProcesses the supplied sequence from right to left, applying the supplied function repeatedly to each item in turn, together with an accumulated result value.
fn:for-eachApplies the function item $action to every item from the sequence $input in turn, returning the concatenation of the resulting sequences in order.
fn:for-each-pairApplies the function item $action to successive pairs of items taken one from $input1 and one from $input2, returning the concatenation of the resulting sequences in order.
fn:highestReturns those items from a supplied sequence that have the highest value of a sort key, where the sort key can be computed using a caller-supplied function.
fn:index-whereReturns the positions in an input sequence of items that match a supplied predicate.
fn:lowestReturns those items from a supplied sequence that have the lowest value of a sort key, where the sort key can be computed using a caller-supplied function.
fn: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 complete (ordered) sequence of all partial results from every new value the accumulator is assigned to during the evaluation of fn:fold-left.
fn:scan-rightProduces the complete (ordered) sequence of all partial results from every new value the accumulator is assigned to during the evaluation of fn:fold-right.
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 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 nodes reachable from a given start node 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.

16.2.1 fn:apply

Changes in 4.0  

  1. As a result of changes to the coercion rules, the number of supplied arguments can be greater than the number required: extra arguments are ignored.  [Issue 1267 PR 1280 18 June 2024]

Summary

Makes a dynamic call on a function with an argument list supplied in the form of an array.

Signature
fn:apply(
$functionas fn(*),
$argumentsas array(*)
) as item()*
Properties

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

Rules

The result of the function is obtained by invoking the supplied function $function with arguments taken from the members of the supplied array $arguments. The first argument of the function call is the first member of $arguments, the second argument is the second member of $arguments, and so on.

The arity of the supplied function $function must be less than or equal to the size of the array $arguments.

The effect of calling fn:apply($f, [$a, $b, $c, ...]) is the same as the effect of the dynamic function call $f($a, $b, $c, ....). For example, the coercion rules are applied to the supplied arguments in the usual way. Among other things this means that excess arguments are ignored.

Error Conditions

A dynamic error is raised if the arity of the function $function is greater than the size of the array $arguments ([err:FOAP0001]).

Notes

The function is useful where the arity of a function item is not known statically.

The function is useful where the arity of a function item is not known statically.

Examples
ExpressionResult
apply(concat#3, [ "a", "b", "c" ])
"abc"

The expression apply($f, array:subarray([ "a", "b", "c", "d", "e", "f" ], 1, function-arity($f))) calls the supplied function $f supplying the number of arguments required by its arity.

16.2.3 fn:do-until

Changes in 4.0  

  1. New in 4.0  [Issue 946 PR 962]

  2. The $predicate callback function may return an empty sequence (meaning false).  [Issue 1171 PR 1182 7 May 2024]

Summary

Processes a supplied value repeatedly, continuing when some condition is false, and returning the value that satisfies the condition.

Signature
fn:do-until(
$inputas item()*,
$actionas fn(item()*, xs:integer) as item()*,
$predicateas fn(item()*, xs:integer) as xs:boolean?
) as item()*
Properties

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

Rules

Informally, the function behaves as follows:

  1. $pos is initially set to 1.

  2. $action($input, $pos) is evaluated, and the resulting value is used as a new $input.

  3. $predicate($input, $pos) is evaluated. If the result is true, the function returns the value of $input. Otherwise, the process repeats from step 2 with $pos incremented by 1.

    When the predicate returns an empty sequence, this is treated as false.

Formal Equivalent

The function delivers the same result as the following XQuery implementation.

declare %private function do-until-helper(
  $input     as item()*,
  $action    as fn(item()*, xs:integer) as item()*,
  $predicate as fn(item()*, xs:integer) as xs:boolean?,
  $pos       as xs:integer
) as item()* {
  let $result := $action($input, $pos)
  return if ($predicate($result, $pos)) then (
    $result
  ) else (
    do-until-helper($result, $action, $predicate, $pos + 1)
  )
};

declare function do-until(
  $input     as item()*,
  $action    as fn(item()*, xs:integer) as item()*,
  $predicate as fn(item()*, xs:integer) as xs:boolean?
) as item()* {
  do-until-helper($input, $action, $predicate, 1)
};
Notes

Do-until loops are very common in procedural programming languages, and this function provides a way to write functionally clean and interruptible iterations without side-effects. A new value is computed and tested until a given condition fails. Depending on the use case, the value can be a simple atomic item or an arbitrarily complex data structure.

The function fn:while-do can be used to perform the action after the first predicate test.

Note that, just as when writing recursive functions, it is easy to construct infinite loops.

Do-until loops are very common in procedural programming languages, and this function provides a way to write functionally clean and interruptible iterations without side-effects. A new value is computed and tested until a given condition fails. Depending on the use case, the value can be a simple atomic item or an arbitrarily complex data structure.

The function fn:while-do can be used to perform the action after the first predicate test.

Note that, just as when writing recursive functions, it is easy to construct infinite loops.

Examples
Expression:
do-until(
  (),
  fn($value, $pos) { $value, $pos * $pos },
  fn($value) { foot($value) > 50  }
)
Result:
1, 4, 9, 16, 25, 36, 49, 64

(The loop is interrupted once the last value of the generated sequence is greater than 50.)

Expression:
do-until(
  (1, 0),
  fn($value) { $value[1] + $value[2], $value },
  fn($value) { avg($value) > 10 }
)
Result:
55, 34, 21, 13, 8, 5, 3, 2, 1, 1, 0

(The computation is continued as long as the average of the first Fibonacci numbers is smaller than 10.)

16.2.4 fn:every

Changes in 4.0  

  1. New in 4.0  [  13 September 2022]

  2. The $predicate callback function may return an empty sequence (meaning false).  [Issue 1171 PR 1182 7 May 2024]

Summary

Returns true if every item in the input sequence matches a supplied predicate.

Signature
fn:every(
$inputas item()*,
$predicateas (fn(item(), xs:integer) as xs:boolean?)?:= fn:boolean#1
) as xs:boolean
Properties

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

Rules

The function returns true if $input is empty, or if $predicate($item, $pos) returns true for every item $item at position $pos (1-based) in $input.

Formal Equivalent

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

fold-left($input, true(), fn($result, $item, $pos) {
   $result and $predicate($item, $pos)
})
Error Conditions

An error is raised if the $predicate function raises an error. In particular, when the default predicate fn:boolean#1 is used, an error is raised if an item has no effective boolean value.

Notes

If the second argument is omitted or an empty sequence, the predicate defaults to fn:boolean#1, which takes the effective boolean value of each item.

It is possible for the supplied $predicate to be a function whose arity is less than two. The coercion rules mean that the additional parameters are effectively ignored. Frequently a predicate function will only consider the item itself, and disregard its position in the sequence.

The predicate is required to return either true, false, or an empty sequence (which is treated as false). A predicate such as fn{self::h1} results in a type error because it returns a node, not a boolean.

The implementation may deliver a result as soon as one item is found for which the predicate returns false; it is not required to evaluate the predicate for every item, nor is it required to examine items sequentially from left to right.

If the second argument is omitted or an empty sequence, the predicate defaults to fn:boolean#1, which takes the effective boolean value of each item.

It is possible for the supplied $predicate to be a function whose arity is less than two. The coercion rules mean that the additional parameters are effectively ignored. Frequently a predicate function will only consider the item itself, and disregard its position in the sequence.

The predicate is required to return either true, false, or an empty sequence (which is treated as false). A predicate such as fn{self::h1} results in a type error because it returns a node, not a boolean.

The implementation may deliver a result as soon as one item is found for which the predicate returns false; it is not required to evaluate the predicate for every item, nor is it required to examine items sequentially from left to right.

Examples
Expression:

every(())

Result:
true()
Expression:

every((1 = 1, 2 = 2, 3 = 4))

Result:
false()
Expression:

every((), boolean#1)

Result:
true()
Expression:

every((1, 3, 7), fn { . mod 2 = 1 })

Result:
true()
Expression:

every(-5 to +5, fn { . ge 0 })

Result:
false()
Expression:
every(
  ("January", "February", "March", "April",
   "September", "October", "November", "December"),
  contains(?, "r")
)
Result:
true()
Expression:
every(
  ("January", "February", "March", "April",
   "September", "October", "November", "December")
  =!> contains("r")
)
Result:
true()
Expression:

every((1, 2, number('NaN')))

Result:
false()

(The effective boolean value of NaN is false.)

Expression:

every(1 to 5, fn($num, $pos) { $num = $pos })

Result:
true()
Expression:
let $dl := <dl><dt>Morgawr</dt><dd>Sea giant</dd></dl>
return every($dl/*, fn($elem, $pos) {
  name($elem) = (
    if (($pos mod 2)) then "dt" else "dd"
  )
})
Result:
true()

16.2.5 fn:filter

Changes in 4.0  

  1. The $predicate callback function accepts an optional position argument.  [Issue 516 PR 828 14 November 2023]

  2. The $predicate callback function may return an empty sequence (meaning false).  [Issue 1171 PR 1182 7 May 2024]

Summary

Returns those items from the sequence $input for which the supplied function $predicate returns true.

Signature
fn:filter(
$inputas item()*,
$predicateas fn(item(), xs:integer) as xs:boolean?
) as item()*
Properties

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

Rules

The function returns a sequence containing those items from $input for which $predicate($item, $pos) returns true, where $item is the item in question, and $pos is its 1-based ordinal position within $input.

Formal Equivalent

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

fold-left($input, (), fn($result, $next, $pos) {
  if ($predicate($next, $pos))
  then ($result, $next)
  else $result
})
Error Conditions

As a consequence of the function signature and the function calling rules, a type error occurs if the supplied $predicate function returns anything other than a single xs:boolean item or an empty sequence; there is no conversion to an effective boolean value, but an empty sequence is interpreted as false.

Notes

If $predicate is an arity-1 function, the function call fn:filter($input, $predicate) has a very similar effect to the expression $input[$predicate(.)]. There are some differences, however. In the case of fn:filter, the function $F is required to return an optional boolean; there is no special treatment for numeric predicate values, and no conversion to an effective boolean value. Also, with a filter expression $input[$predicate(.)], the focus within the predicate is different from that outside; this means that the use of a context-sensitive function such as fn:lang#1 will give different results in the two cases.

If $predicate is an arity-1 function, the function call fn:filter($input, $predicate) has a very similar effect to the expression $input[$predicate(.)]. There are some differences, however. In the case of fn:filter, the function $F is required to return an optional boolean; there is no special treatment for numeric predicate values, and no conversion to an effective boolean value. Also, with a filter expression $input[$predicate(.)], the focus within the predicate is different from that outside; this means that the use of a context-sensitive function such as fn:lang#1 will give different results in the two cases.

Examples
Expression:

filter(1 to 10, fn($a) { $a mod 2 = 0 })

Result:
2, 4, 6, 8, 10
Expression:
filter(parse-xml('<doc><a id="2"/><a/></doc>')//a, fn{@id eq "2"})
Result:
<a id="2"/>

(The function returns () when there is no @id attribute; this is treated as false.)

Expression:

filter((), lang("en", ?))

Result:
()
Expression:
let $sequence := (1, 1, 2, 3, 4, 4, 5)
return filter(
  $sequence,
  fn($item, $pos) { $item = $sequence[$pos - 1] }
)
Result:
1, 4

16.2.6 fn:fold-left

Changes in 4.0  

  1. The $predicate callback function accepts an optional position argument.  [Issue 516 PR 828 14 November 2023]

  2. The $predicate callback function may return an empty sequence (meaning false).  [Issue 1171 PR 1182 7 May 2024]

Summary

Processes the supplied sequence from left to right, applying the supplied function repeatedly to each item in turn, together with an accumulated result value.

Signature
fn:fold-left(
$inputas item()*,
$zeroas item()*,
$actionas fn(item()*, item(), xs:integer) as item()*
) as item()*
Properties

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

Rules

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

If $input contains a single item $item1, the function calls $action($zero, $item1, 1).

If $input contains a second item $item2, the function then calls $action($zero1, $item2, 2), where $zero1 is the result after processing the first item.

This continues in the same way until the end of the $input sequence; the final result is the result of the last call on $action.

Formal Equivalent

The function delivers the same result as the following XQuery implementation.

declare %private function fold-left-2(
  $input  as item()*,
  $zero   as item()*,
  $action as function(item()*, item()) as item()*
) as item()* {
  if (empty($input))
  then $zero
  else fold-left-2(tail($input), $action($zero, head($input)), $action)
};

declare function fold-left(
  $input  as item()*,
  $zero   as item()*,
  $action as function(item()*, item(), xs:integer) as item()*
) as item()* {
  let $numbered-input := for-each($input, fn($item, $pos) { 
    { 'item': $item, 'position': $pos }
  })
  return fold-left-2($numbered-input, fn($zero, $pair) {
    $action($zero, $pair?item, $pair?position)
  })
};

(: Note: a practical implementation can optimize for the case where the
   supplied $action function has arity 2 :)
Error Conditions

As a consequence of the function signature and the function calling rules, a type error occurs if the supplied function $action cannot be applied to two arguments, where the first argument is either the value of $zero or the result of a previous application of $action, and the second is any single item from the sequence $input.

Notes

This operation is often referred to in the functional programming literature as “folding” or “reducing” a sequence. It typically takes a function that operates on a pair of values, and applies it repeatedly, with an accumulated result as the first argument, and the next item in the sequence as the second argument. Optionally the $action function may take a third argument, which is set to the 1-based position of the current item in the input sequence. The accumulated result is initially set to the value of the $zero argument, which is conventionally a value (such as zero in the case of addition, one in the case of multiplication, or a zero-length string in the case of string concatenation) that causes the function to return the value of the other argument unchanged.

This operation is often referred to in the functional programming literature as “folding” or “reducing” a sequence. It typically takes a function that operates on a pair of values, and applies it repeatedly, with an accumulated result as the first argument, and the next item in the sequence as the second argument. Optionally the $action function may take a third argument, which is set to the 1-based position of the current item in the input sequence. The accumulated result is initially set to the value of the $zero argument, which is conventionally a value (such as zero in the case of addition, one in the case of multiplication, or a zero-length string in the case of string concatenation) that causes the function to return the value of the other argument unchanged.

Examples
Expression:
fold-left(
  1 to 5,
  0,
  fn($a, $b) { $a + $b }
)
Result:
15

(This returns the sum of the items in the sequence).

Expression:
fold-left(
  (2, 3, 5, 7),
  1,
  fn($a, $b) { $a * $b }
)
Result:
210

(This returns the product of the items in the sequence).

Expression:
fold-left(
  (true(), false(), false()),
  false(),
  fn($a, $b) { $a or $b }
)
Result:
true()

(This returns true if any item in the sequence has an effective boolean value of true).

Expression:
fold-left(
  (true(), false(), false()),
  false(),
  fn($a, $b) { $a and $b }
)
Result:
false()

(This returns true only if every item in the sequence has an effective boolean value of true).

Expression:
fold-left(
  1 to 5,
  (),
  fn($a, $b) { $b, $a }
)
Result:
5, 4, 3, 2, 1

(This reverses the order of the items in a sequence).

Expression:
fold-left(
  1 to 5,
  "",
  concat(?, ".", ?)
)
Result:
".1.2.3.4.5"
Expression:
fold-left(
  1 to 5,
  "$zero",
  concat("$f(", ?, ", ", ?, ")")
)
Result:
"$f($f($f($f($f($zero, 1), 2), 3), 4), 5)"
Expression:
fold-left(
  1 to 5,
  {},
  fn($map, $n) { map:put($map, $n, $n * 2) }
)
Result:
{ 1: 2, 2: 4, 3: 6, 4: 8, 5: 10 }
Expression:
let $input := (11 to 21, 21 to 31)
let $target := 21
return fold-left($input, (),
  fn($result, $curr, $pos) {
    $result, if ($curr = $target) { $pos }
  }
)
Result:
11, 12

16.2.7 fn:fold-right

Changes in 4.0  

  1. The $action callback function accepts an optional position argument.  [Issue 516 PR 828 14 November 2023]

Summary

Processes the supplied sequence from right to left, applying the supplied function repeatedly to each item in turn, together with an accumulated result value.

Signature
fn:fold-right(
$inputas item()*,
$zeroas item()*,
$actionas fn(item(), item()*, xs:integer) as item()*
) as item()*
Properties

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

Rules

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

Let $itemN be the last item in $input, and let $N be its 1-based ordinal position in $input (that is, the size of $input). The function starts by calling $action($itemN, $zero, $N).

If there is a previous item, $itemN-1, at position $N - 1, the function then calls $action($itemN-1, $zeroN, $N - 1), where $zeroN is the result of the previous call.

This continues in the same way until the start of the $input sequence is reached; the final result is the result of the last call on $action.

Formal Equivalent

The function delivers the same result as the following XQuery implementation.

declare %private function fold-right-2(
  $input  as item()*,
  $zero   as item()*,
  $action as function(item(), item()*) as item()*
) as item()* {
  if (empty($input))
  then $zero
  else $action(head($input), fold-right-2(tail($input), $zero, $action)
};

declare function fold-right (
  $input  as item()*,
  $zero   as item()*,
  $action as function(item()*, item(), xs:integer) as item()*
) as item()* {
  let $numbered-input := for-each($input, fn($item, $pos) {
    { 'item': $item, 'position': $pos }
  })
  return fold-right-2($numbered-input, fn($zero, $pair) {
    $action($pair?item, $zero, $pair?position)
  })   
};

(: Note: a practical implementation can optimize for the case where the
   supplied $action function has arity 2 :)
Error Conditions

As a consequence of the function signature and the function calling rules, a type error occurs if the supplied function $action cannot be applied to two arguments, where the first argument is any item in the sequence $input, and the second is either the value of $zero or the result of a previous application of $action.

Notes

This operation is often referred to in the functional programming literature as “folding” or “reducing” a sequence. It takes a function that operates on a pair of values, and applies it repeatedly, with the next item in the sequence as the first argument, and the result of processing the remainder of the sequence as the second argument. The accumulated result is initially set to the value of the $zero argument, which is conventionally a value (such as zero in the case of addition, one in the case of multiplication, or a zero-length string in the case of string concatenation) that causes the function to return the value of the other argument unchanged.

In cases where the function performs an associative operation on its two arguments (such as addition or multiplication), fn:fold-right produces the same result as fn:fold-left.

The value of the third argument of $action corresponds to the position of the item in the input sequence. Thus, in contrast to fn:fold-left, it is initally set to the number of items in the input sequence.

This operation is often referred to in the functional programming literature as “folding” or “reducing” a sequence. It takes a function that operates on a pair of values, and applies it repeatedly, with the next item in the sequence as the first argument, and the result of processing the remainder of the sequence as the second argument. The accumulated result is initially set to the value of the $zero argument, which is conventionally a value (such as zero in the case of addition, one in the case of multiplication, or a zero-length string in the case of string concatenation) that causes the function to return the value of the other argument unchanged.

In cases where the function performs an associative operation on its two arguments (such as addition or multiplication), fn:fold-right produces the same result as fn:fold-left.

The value of the third argument of $action corresponds to the position of the item in the input sequence. Thus, in contrast to fn:fold-left, it is initally set to the number of items in the input sequence.

Examples
Expression:
fold-right(
  1 to 5,
  0,
  fn($a, $b) { $a + $b }
)
Result:
15

(This returns the sum of the items in the sequence).

Expression:
fold-right(
  1 to 5,
  "",
  concat(?, ".", ?)
)
Result:
"1.2.3.4.5."
Expression:
fold-right(
  1 to 5,
  "$zero",
  concat("$f(", ?, ", ", ?, ")")
)
Result:
"$f(1, $f(2, $f(3, $f(4, $f(5, $zero)))))"
Expression:
let $input := (11 to 21, 21 to 31)
let $target := 21
return fold-right(
  $input,
  (),
  action := fn($current, $result, $pos) {
    $result, $pos[$current = $target]
  }
)
Result:
12, 11

16.2.9 fn:for-each-pair

Changes in 4.0  

  1. The $action callback function accepts an optional position argument.  [Issue 516 PR 828 14 November 2023]

Summary

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

Signature
fn:for-each-pair(
$input1as item()*,
$input2as item()*,
$actionas fn(item(), item(), xs:integer) as item()*
) as item()*
Properties

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

Rules

The function returns the value of the expression:

for $pos in 1 to min(count($input1), count($input2))
return $action($input1[$pos], $input2[$pos], $pos)
Notes

If one sequence is longer than the other, excess items in the longer sequence are ignored.

If one sequence is longer than the other, excess items in the longer sequence are ignored.

Examples
Expression:
for-each-pair(
  ("a", "b", "c"),
  ("x", "y", "z"),
  concat#2
)
Result:
"ax", "by", "cz"
Expression:
for-each-pair(
  1 to 5,
  1 to 5,
  fn($a, $b) { 10 * $a + $b }
)
Result:
11, 22, 33, 44, 55
Expression:
let $s := 1 to 8
return for-each-pair($s, tail($s), fn($a, $b) { $a * $b })
Result:
2, 6, 12, 20, 30, 42, 56
Expression:
for-each-pair(
  (1, 8, 2),
  (3, 4, 3),
  fn($item1, $item2, $pos) {
    $pos || ': ' || max(($item1, $item2))
  }
)
Result:
"1: 3", "2: 8", "3: 3"

16.2.13 fn:partition

Changes in 4.0  

  1. New in 4.0  [Issue 125 PR 507 19 May 2023]

Summary

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

Signature
fn:partition(
$inputas item()*,
$split-whenas fn(item()*, item(), xs:integer) as xs:boolean?
) as array(item())*
Properties

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

Rules

Informally, the function starts by creating a partition containing the first item in the input sequence, if any. For each remaining item J in the input sequence, other than the first, it calls the supplied $split-when function with three arguments: the contents of the current partition, the item J, and the current position in the input sequence.

Each partition is a sequence of items; the function result wraps each partition as an array, and returns the sequence of arrays.

If the $split-when function returns true, the current partition is wrapped as an array and added to the result, and a new current partition is created, initially containing the item J only. If the $split-when function returns false or (), the item J is added to the current partition.

Formal Equivalent

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

fold-left($input, (), fn($partitions, $next, $pos) {
  if (empty($partitions) or $split-when(foot($partitions)?*, $next, $pos))
  then ($partitions, [ $next ])
  else (trunk($partitions), array { foot($partitions)?*, $next })
})
Notes

The function enables a variety of positional grouping problems to be solved. For example:

The function enables a variety of positional grouping problems to be solved. For example:

  • partition($input, fn($a, $b) { count($a) eq 3 } partitions a sequence into fixed size groups of length 3.

  • partition($input, fn($a, $b) { boolean($b/self::h1) } starts a new group whenever an h1 element is encountered.

  • partition($input, fn($a, $b) { $b lt foot($a) } starts a new group whenever an item is encountered whose value is less than the value of the previous item.

The callback function is not called to process the first item in the input sequence, because this will always start a new partition. The first argument to the callback function (the current partition) is always a non-empty sequence.

The callback function is not called to process the first item in the input sequence, because this will always start a new partition. The first argument to the callback function (the current partition) is always a non-empty sequence.

Examples
Expression:
partition(
  ("Anita", "Anne", "Barbara", "Catherine", "Christine"), 
  fn($partition, $next) {
    substring(head($partition), 1, 1) ne substring($next, 1, 1)
  }
)
Result:
[ "Anita", "Anne" ], [ "Barbara" ], [ "Catherine", "Christine" ]
Expression:
partition(
  (1, 2, 3, 4, 5, 6, 7),
  fn($partition, $next) {
    count($partition) eq 2
  }
)
Result:
[ 1, 2 ], [ 3, 4 ], [ 5, 6 ], [ 7 ]
Expression:
partition(
  (1, 4, 6, 3, 1, 1),
  fn($partition, $next) {
    sum($partition) ge 5
  }
)
Result:
[ 1, 4 ], [ 6 ], [ 3, 1, 1 ]
Expression:
partition(
  tokenize("In the beginning was the word"), 
  fn($partition, $next) {
    sum(($partition, $next) ! string-length()) gt 10
  }
)
Result:
[ "In", "the" ], [ "beginning" ], [ "was", "the", "word" ]
Expression:
partition(
  (1, 2, 3, 6, 7, 9, 10),
  fn($partition, $next) { $next != foot($partition) + 1 }
)
Result:
[ 1, 2, 3 ], [ 6, 7 ], [ 9, 10 ]
Expression:
partition(
  ('a', 'b', 'c', 'd', 'e'),
  fn($all, $next, $p) { $p mod 2 = 1 }
)
Result:
[ "a", "b" ], [ "c", "d" ], [ "e" ]

16.2.16 fn:some

Changes in 4.0  

  1. New in 4.0  [  13 September 2022]

  2. The $predicate callback function may return an empty sequence (meaning false).  [Issue 1171 PR 1182 7 May 2024]

Summary

Returns true if at least one item in the input sequence matches a supplied predicate.

Signature
fn:some(
$inputas item()*,
$predicateas (fn(item(), xs:integer) as xs:boolean?)?:= fn:boolean#1
) as xs:boolean
Properties

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

Rules

The function returns true if (and only if) there is an item $item at position $pos in the input sequence such that $predicate($item, $pos) returns true.

Formal Equivalent

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

fold-left($input, false(), fn($result, $item, $pos) {
   $result or $predicate($item, $pos)
})
Error Conditions

An error is raised if the $predicate function raises an error. In particular, when the default predicate fn:boolean#1 is used, an error is raised if an item has no effective boolean value.

Notes

If the second argument is omitted or an empty sequence, the predicate defaults to fn:boolean#1, which takes the effective boolean value of each item.

It is possible for the supplied $predicate to be a function whose arity is less than two. The coercion rules mean that the additional parameters are effectively ignored. Frequently a predicate function will only consider the item itself, and disregard its position in the sequence.

The predicate is required to return either true, false, or an empty sequence (which is treated as false). A predicate such as fn{self::h1} results in a type error because it returns a node, not a boolean.

The implementation may deliver a result as soon as one item is found for which the predicate returns true; it is not required to evaluate the predicate for every item, nor is it required to examine items sequentially from left to right.

If the second argument is omitted or an empty sequence, the predicate defaults to fn:boolean#1, which takes the effective boolean value of each item.

It is possible for the supplied $predicate to be a function whose arity is less than two. The coercion rules mean that the additional parameters are effectively ignored. Frequently a predicate function will only consider the item itself, and disregard its position in the sequence.

The predicate is required to return either true, false, or an empty sequence (which is treated as false). A predicate such as fn{self::h1} results in a type error because it returns a node, not a boolean.

The implementation may deliver a result as soon as one item is found for which the predicate returns true; it is not required to evaluate the predicate for every item, nor is it required to examine items sequentially from left to right.

Examples
Expression:

some(())

Result:
false()
Expression:

some((1 = 1, 2 = 2, 3 = 4))

Result:
true()
Expression:

some((), boolean#1)

Result:
false()
Expression:

some((1, 3, 7), fn { . mod 2 = 1 })

Result:
true()
Expression:

some(-5 to +5, fn { . ge 0 })

Result:
true()
Expression:
some(
  ("January", "February", "March", "April",
   "September", "October", "November", "December"),
  contains(?, "z")
)
Result:
false()
Expression:
some(
  ("January", "February", "March", "April",
   "September", "October", "November", "December")
  =!> contains("r")
)
Result:
true()
Expression:

some(("", 0, number('NaN')))

Result:
false()

(The effective boolean value in each case is false.)

Expression:

some(reverse(1 to 5), fn($num, $pos) { $num = $pos })

Result:
true()

16.2.17 fn:sort

Changes in 4.0  

  1. Substantially revised to allow multiple sort key definitions.  [Issue 93 PR 623 19 July 2023]

Summary

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

Signature
fn:sort(
$inputas item()*,
$collationsas xs:string*:= fn:default-collation(),
$keysas (fn(item()) as xs:anyAtomicType*)*:= fn:data#1,
$ordersas enum('ascending', 'descending')*:= 'ascending'
) 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 has three parts:

  1. A sort key function, which is applied to each item in the input sequence to determine a sort key value.

  2. A collation, which is used when comparing sort key values that are of type xs:string or xs:untypedAtomic.

  3. An order direction, which is ascending or descending.

The number of sort key definitions is determined by the number of function items 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.

The $nth sort key definition (where $n counts from one (1)) is established as follows:

  1. The sort key function is $keys[$n] otherwise data#1.

  2. The collation is $collations[$n] otherwise $collations[last()] otherwise default-collation(). That is, it is the collation supplied in the corresponding item of the supplied $collations argument; or in its absence, the last entry in $collations; or if $collations is absent or empty, the default collation from the static context of the caller.

  3. The order direction is $orders[$n] otherwise $orders[last()] otherwise "ascending". That is, it is "ascending" or "descending" according to the value of the corresponding item in the supplied $orders argument; or in its absence, the last entry in $orders; or if $orders is absent or empty, then "ascending".

When comparing values of types other than xs:string or xs:untypedAtomic, the corresponding collation is ignored, and no error is reported if the supplied value is not a known or valid collation name. If it is necessary to supply such an ignored value (for example, in the case where a non-string sort key is followed by another sort key that requires a collation) the empty string can be supplied.

The result of the 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

XSLT and XQuery both provide native sorting capability, but earlier releases of XPath provided no sorting functionality for use in standalone environments.

In addition there are cases where this function may be more flexible than the built-in sorting capability for XQuery or XSLT, for example when the sort key or collation is chosen dynamically, or when the sort key is a sequence of items rather than a single item.

The results are compatible with the results of XSLT sorting (using xsl:sort) in the case where the sort key evaluates to a sequence of length zero or one, given the options stable="yes".

The results are compatible with the results of XQuery sorting (using the order by clause) in the case where the sort key evaluates to a sequence of length zero or one, given the options stable, ascending, and empty least.

The function has been enhanced in 4.0 to allow multiple sort keys to be defined, each potentially with a different collation, and to allow sorting in descending order.

The effect of the XQuery option empty least|greatest, which controls whether the empty sequence is sorted before or after all other values, can be achieved by adding an extra sort key definition that evaluates whether or not the actual sort key is empty (when sorting boolean values, false precedes true).

Supplying too many items in the $collations and/or $orders arguments is not an error; the excess values are ignored except for type-checking against the function signature.

XSLT and XQuery both provide native sorting capability, but earlier releases of XPath provided no sorting functionality for use in standalone environments.

In addition there are cases where this function may be more flexible than the built-in sorting capability for XQuery or XSLT, for example when the sort key or collation is chosen dynamically, or when the sort key is a sequence of items rather than a single item.

The results are compatible with the results of XSLT sorting (using xsl:sort) in the case where the sort key evaluates to a sequence of length zero or one, given the options stable="yes".

The results are compatible with the results of XQuery sorting (using the order by clause) in the case where the sort key evaluates to a sequence of length zero or one, given the options stable, ascending, and empty least.

The function has been enhanced in 4.0 to allow multiple sort keys to be defined, each potentially with a different collation, and to allow sorting in descending order.

The effect of the XQuery option empty least|greatest, which controls whether the empty sequence is sorted before or after all other values, can be achieved by adding an extra sort key definition that evaluates whether or not the actual sort key is empty (when sorting boolean values, false precedes true).

Supplying too many items in the $collations and/or $orders arguments is not an error; the excess values are ignored except for type-checking against the function signature.

Examples
Expression:

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

Result:
1, 3, 4, 5, 6
Expression:

sort((1, 4, 4e0, 6, 5, 3), orders := "descending")

Result:
6, 5, 4, 4e0, 3, 1
Expression:

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

Result:
1, -2, 5, 8, 10, -10, 10

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

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

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($employees, (), fn { name ! (last, first) })

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

sort(
  $employees, 
  collation({ 'lang': 'se' }),
  (fn { name/last }, fn { xs:decimal(salary) }), 
  ("ascending", "descending")
)

16.2.18 fn:sort-with

Changes in 4.0  

  1. New in 4.0  [Issue 655 PR 795 20 February 2024]

Summary

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

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

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

Rules

Informally, the items of the supplied $input are compared against each other, using the supplied $comparators. The result is a sorted sequence.

Each comparator function takes two items and returns an xs:integer that defines the relationship between these items, in accordance with the fn:compare function:

  • The comparators are evaluated one after the other, either completely or until the result is an integer other than 0.

  • If the last integer returned is negative or 0, the first item is returned before the second.

  • Otherwise, the second item is returned first.

Users are responsible for supplying transitive comparators; otherwise, the result might not be correctly sorted. An example for a non-transitive and thus unsuitable comparator is fn($a, $b) { if ($a mod 2 = 1) then 1 else -1 }, as it considers odd numbers to be greater than even numbers.

Sorting is stable, which means that the relative order of the input items is maintained.

More formally, assuming that the comparators raise no errors and are transitive, the effect of the function is equivalent to the following implementation in XQuery:

declare function sort-with(
  $input       as item()*,
  $comparators as (fn(item(), item()) as xs:integer)*
) as item()* {
  if (count($input) < 2) then (
    $input
  ) else (
    let $head := head($input), $sorted-tail := sort-with(tail($input), $comparators)
    let $diff := fold-left($comparators, 0, fn($df, $cmp) {
      if ($df != 0) then $df else $cmp($head, head($sorted-tail))
    })
    return if ($diff <= 0) then (
      $head, $sorted-tail
    ) else (
      head($sorted-tail), sort-with(($head, tail($sorted-tail)), $comparators)
    )
  )
};
Notes

An implementation is free to choose any sorting algorithm as long as the result returned is stable and matches the result of the implementation in XQuery.

An implementation is free to choose any sorting algorithm as long as the result returned is stable and matches the result of the implementation in XQuery.

Examples
Expression:

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

Result:
1, 3, 4, 5, 6
Expression:

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

Result:
1, 3, 4, 5, 6
Expression:

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

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

16.2.19 fn:subsequence-where

Changes in 4.0  

  1. New in 4.0  [Issue 878 PR 940 5 February 2024]

Summary

Returns a contiguous sequence of items from $input, with the start and end points located by applying predicates.

Signature
fn:subsequence-where(
$inputas item()*,
$fromas (fn(item(), xs:integer) as xs:boolean?)?:= true#0,
$toas (fn(item(), xs:integer) as xs:boolean?)?:= false#0
) as item()*
Properties

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

Rules

Informally, the function returns the subsequence of $input starting with the first item that matches the $from predicate, and ending with the first subsequent item that matches the $to predicate. If $from is not supplied, it defaults to the start of $input; if $to is not supplied, it defaults to the end of $input. If $from does not match any items in $input, the result is the empty sequence; if $to does not match any items, all items up to the last are included in the result.

Formal Equivalent

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

let $start := index-where($input, $from)[1] otherwise count($input) + 1
let   $end := index-where($input, $to)[. ge $start][1] otherwise count($input) + 1
return slice($input, $start, $end)
Notes

The result includes both the item that matches the $from condition and the item that matches the $to condition. To select a subsequence that starts after the $from item, apply the fn:tail function to the result. To select a subsequence that ends before the $to item, apply the fn:trunk function to the result.

The predicate functions supplied to the $from and $to parameters can include an integer position argument as well as the item itself. This position will always be 1-based, relative to the start of $input. This means it is possible to select items based on their absolute position in the $input sequence, but there is no mechanism to select an end position relative to the start position. If this is needed, the function can be combined with others: for example, to select a subsequence of four items starting with "Barbara", use $input => subsequence-where(fn {. eq "Barbara" }) => slice(end := 4).

If the requirement is to select all elements stopping before the first h2 element if it exists, or up to the end of the sequence otherwise, the simplest solution is perhaps to write:

slice($input, end:=index-where($input, fn { boolean(self::h2) })[1])

The result includes both the item that matches the $from condition and the item that matches the $to condition. To select a subsequence that starts after the $from item, apply the fn:tail function to the result. To select a subsequence that ends before the $to item, apply the fn:trunk function to the result.

The predicate functions supplied to the $from and $to parameters can include an integer position argument as well as the item itself. This position will always be 1-based, relative to the start of $input. This means it is possible to select items based on their absolute position in the $input sequence, but there is no mechanism to select an end position relative to the start position. If this is needed, the function can be combined with others: for example, to select a subsequence of four items starting with "Barbara", use $input => subsequence-where(fn {. eq "Barbara" }) => slice(end := 4).

If the requirement is to select all elements stopping before the first h2 element if it exists, or up to the end of the sequence otherwise, the simplest solution is perhaps to write:

slice($input, end:=index-where($input, fn { boolean(self::h2) })[1])

A return value of () from the $from or $to predicate is treated as false.

A return value of () from the $from or $to predicate is treated as false.

Examples
Variables
let $names := ("Anna", "Barbara", "Catherine", "Delia",  "Eliza", "Freda",
  "Gertrude", "Hilda")
Expression:

subsequence-where($names, starts-with(?, "E"))

Result:
"Eliza", "Freda", "Gertrude", "Hilda"
Expression:

subsequence-where($names, to := starts-with(?, "D"))

Result:
"Anna", "Barbara", "Catherine", "Delia"
Expression:

subsequence-where($names, to := starts-with(?, "D")) => trunk()

Result:
"Anna", "Barbara", "Catherine"
Expression:

subsequence-where($names, starts-with(?, "E"), starts-with(?, "G"))

Result:
"Eliza", "Freda", "Gertrude"
Expression:
subsequence-where(
  $names,
  starts-with(?, "D"), fn { string-length(.) gt 5 }
)
Result:
"Delia", "Eliza", "Freda", "Gertrude"
Expression:

subsequence-where($names, starts-with(?, "M"))

Result:
()
Expression:

subsequence-where($names, starts-with(?, "G"), starts-with(?, "Z"))

Result:
"Gertrude", "Hilda"
Expression:

subsequence-where($names)

Result:
"Anna", "Barbara", "Catherine", "Delia", "Eliza", "Freda",
  "Gertrude", "Hilda"
Expression:
subsequence-where(
  $names,
  fn($it, $pos) { ends-with($it, "a") and $pos gt 5 }
)
Result:
"Freda", "Gertrude", "Hilda"
Expression:
subsequence-where(
  $names, 
  to := fn($it, $pos) { ends-with($it, "a") and $pos ge 5 }
)
Result:
"Anna", "Barbara", "Catherine", "Delia", "Eliza"

16.2.20 fn:take-while

Changes in 4.0  

  1. New in 4.0  [Issues 1002 1038 PR 1046]

  2. The $predicate callback function may return an empty sequence (meaning false).  [Issue 1171 PR 1182 7 May 2024]

Summary

Returns items from the input sequence prior to the first one that fails to match a supplied predicate.

Signature
fn:take-while(
$inputas item()*,
$predicateas fn(item(), xs:integer) as xs:boolean?
) as item()*
Properties

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

Rules

The function returns all items in the sequence prior to the first one where the result of calling the supplied $predicate function, with the current item and its position as arguments, returns the value false or ().

If every item in the sequence satisfies the predicate, then $input is returned in its entirety.

Formal Equivalent

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

for $item at $pos in $input
while $predicate($item, $pos)
return $item
Notes

There is no analogous drop-while or skip-while function, as found in some functional programming languages. The effect of drop-while($input, $predicate) can be achieved by calling fn:subsequence-where($input, fn { not($predicate(.)) }).

There is no analogous drop-while or skip-while function, as found in some functional programming languages. The effect of drop-while($input, $predicate) can be achieved by calling fn:subsequence-where($input, fn { not($predicate(.)) }).

Examples
Expression:

take-while(10 to 20, fn {. le 12 })

Result:
10, 11, 12
Expression:

take-while(10 to 20, fn {. lt 100 })

Result:
10 to 20
Expression:

take-while((), boolean#1)

Result:
()
Expression:
take-while(
  ("A", "B", "C", " ", "E"), 
   fn { boolean(normalize-space()) }
 )
Result:
"A", "B", "C"
Expression:
parse-xml("<doc><p/><p/><h2/><img/><p/></doc>")/doc/*
=> take-while(fn { boolean(self::p) })
=> count()
Result:
2
Expression:
("Aardvark", "Antelope", "Bison", "Buffalo", "Camel", "Dingo")
=> take-while(starts-with(?, "A"))
Result:
"Aardvark", "Antelope"
Expression:
take-while(10 to 20, fn($num, $pos) { $num lt 18 and $pos lt 4 })
Result:
10, 11, 12
Expression:
take-while(
  characters("ABCD-123"), 
  fn($ch, $pos) { $pos lt 4 and $ch ne '-' }
) => string-join()
Result:
"ABC"
Expression:
take-while(
  ("A", "a", "B", "b", "C", "D", "d"),
   fn($ch, $pos) {
     matches($ch, if ($pos mod 2 eq 1) then "\p{Lu}" else "\p{Ll}")
   }
 )
Result:
"A", "a", "B", "b", "C"

16.2.21 fn:transitive-closure

Changes in 4.0  

  1. New in 4.0  [Issues 518 554 754 PRs 521 761 18 October 2023]

Summary

Returns all the nodes reachable from a given start node by applying a supplied function repeatedly.

Signature
fn:transitive-closure(
$nodeas node()?,
$stepas fn(node()) as node()*
) as node()*
Properties

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

Rules

The value of $node is a node from which navigation starts. If $node is an empty sequence, the function returns an empty sequence.

The value of $step is a function that takes a single node as input, and returns a set of nodes as its result.

The result of the fn:transitive-closure function is the set of nodes that are reachable from $node by applying the $step function one or more times.

Although $step may return any sequence of nodes, the result is treated as a set: the order of nodes in the sequence is ignored, and duplicates are ignored. The result of of the transitive-closure function will always be a sequence of nodes in document order with no duplicates.

Formal Equivalent

The function delivers the same result as the following XQuery implementation.

declare %private function tc-inclusive(
  $nodes as node()*,
  $step  as fn(node()) as node()*
) as node()* {
  let $nextStep := $nodes/$step(.)
  let $newNodes := $nextStep except $nodes
  return if (exists($newNodes))
         then $nodes union tc-inclusive($newNodes, $step)
         else $nodes
};

declare function transitive-closure (
  $node as node(),
  $step as fn(node()) as node()*
) as node()* {
  tc-inclusive($node/$step(.), $step)
};

(: Explanation:

   The private helper function tc-inclusive takes a set of nodes as input,
   and calls the $step function on each one of those nodes; if the result 
   includes nodes that are not already present in the input, then it makes 
   a recursive call to find nodes reachable from these new nodes, and returns
   the union of the supplied nodes and the nodes returned from the recursive
   call (which will always include the new nodes selected in the first step).
   
   If there are no new nodes, the recursion ends, returning the nodes that 
   have been found up to this point.
   
   The main function fn:transitive-closure finds the nodes that are reachable 
   from the start node in a single step, and then invokes the helper function 
   tc-inclusive to add nodes that are reachable in multiple steps.
:)
Notes

Cycles in the data are not a problem; the function stops searching when it finds no new nodes.

The function may fail to terminate if the supplied $step function constructs and returns new nodes. A processor may detect this condition but is not required to do so.

The $node node is not included in the result, unless it is reachable by applying the $step function one or more times. If a result is required that does include $node, it can be readily added to the result using the union operator: $node | transitive-closure($node, $step).

Cycles in the data are not a problem; the function stops searching when it finds no new nodes.

The function may fail to terminate if the supplied $step function constructs and returns new nodes. A processor may detect this condition but is not required to do so.

The $node node is not included in the result, unless it is reachable by applying the $step function one or more times. If a result is required that does include $node, it can be readily added to the result using the union operator: $node | transitive-closure($node, $step).

Examples
Variables
let $data := document { <doc>
  <person id="0"/>
  <person id="1" manager="0"/>
  <person id="2" manager="0"/>
  <person id="3" manager="2"/>
  <person id="4" manager="2"/>
  <person id="5" manager="1"/>
  <person id="6" manager="3"/>
  <person id="7" manager="6"/>
  <person id="8" manager="6"/>
</doc> }
let $direct-reports := fn($p as element(person)) as element(person)* {
  $p/../person[@manager = $p/@id]
}
Expression:
transitive-closure(
  $data//person[@id = "2"],
  $direct-reports
)/string(@id)
Result:
"3", "4", "6", "7", "8"
Expression:
transitive-closure(
  $data, 
  function { child::* }
)/@id ! string()
Result:
"0", "1", "2", "3", "4", "5", "6", "7", "8"

The following example, given $root as the root of an XSLT stylesheet module, returns the URIs of all stylesheet modules reachable using xsl:import and xsl:include declarations:

transitive-closure($root, fn { document(//(xsl:import|xsl:include)/@href) }) 
=!> document-uri()

This example uses the XSLT-defined document() function.

16.2.22 fn:while-do

Changes in 4.0  

  1. New in 4.0  [Issue 946 PR 962]

  2. The $predicate callback function may return an empty sequence (meaning false).  [Issue 1171 PR 1182 7 May 2024]

Summary

Processes a supplied value repeatedly, continuing while some condition remains true, and returning the first value that does not satisfy the condition.

Signature
fn:while-do(
$inputas item()*,
$predicateas fn(item()*, xs:integer) as xs:boolean?,
$actionas fn(item()*, xs:integer) as item()*
) as item()*
Properties

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

Rules

Informally, the function behaves as follows:

  1. $pos is initially set to 1.

  2. $predicate($input, $pos) is evaluated. If the result is false or (), the function returns the value of $input.

  3. Otherwise, $action($input, $pos) is evaluated, the resulting value is used as a new $input, and the process repeats from step 2 with $pos incremented by 1.

Formal Equivalent

The function delivers the same result as the following XQuery implementation.

declare %private function while-do-helper(
  $input     as item()*,
  $predicate as fn(item()*, xs:integer) as xs:boolean?,
  $action    as fn(item()*, xs:integer) as item()*,
  $pos       as xs:integer
) as item()* {
  if ($predicate($input, $pos))
  then while-do-helper($action($input, $pos), $predicate, $action, $pos + 1)
  else $input
};

declare function while-do(
  $input     as item()*,
  $predicate as fn(item()*, xs:integer) as xs:boolean?,
  $action    as fn(item()*, xs:integer) as item()*
) as item()* {
  while-do-helper($input, $predicate, $action, 1)
};
Notes

While-do loops are very common in procedural programming languages, and this function provides a way to write functionally clean and interruptible iterations without side-effects. As long as a given condition is met, an new value is computed and tested again. Depending on the use case, the value can be a simple atomic item or an arbitrarily complex data structure.

The function fn:do-until can be used to perform the action before the first predicate test.

Note that, just as when writing recursive functions, it is easy to construct infinite loops.

While-do loops are very common in procedural programming languages, and this function provides a way to write functionally clean and interruptible iterations without side-effects. As long as a given condition is met, an new value is computed and tested again. Depending on the use case, the value can be a simple atomic item or an arbitrarily complex data structure.

The function fn:do-until can be used to perform the action before the first predicate test.

Note that, just as when writing recursive functions, it is easy to construct infinite loops.

Examples
Expression:
while-do(2, fn { . <= 100 }, fn { . * . })
Result:
256

(The loop is interrupted as soon as the computed product is greater than 100.)

Expression:
while-do(
  1,
  fn($num, $pos) { $pos <= 10 },
  fn($num, $pos) { $num * $pos }
)
Result:
3628800

(This returns the factorial of 10, i.e., the product of all integers from 1 to 10.)

Expression:
let $input := (0 to 4, 6 to 10)
return while-do(
  0,
  fn($n) { $n = $input },
  fn($n) { $n + 1 }
)
Result:
5

(This returns the first positive number missing in a sequence.)

Expression:
while-do(
  1 to 9,
  fn($value) { head($value) < 5 },
  fn($value) { tail($value) }
)
Result:
5, 6, 7, 8, 9

(The first number of a sequence is removed as long as it is smaller than 5.)

Expression:
let $input := 3936256
return while-do(
  $input,
  fn($result) { abs($result * $result - $input) >= 0.0000000001 },
  fn($guess) { ($guess + $input div $guess) div 2 }
) => round(5)
Result:
1984

(This computes the square root of a number.)

The following example generates random doubles. It is interrupted once a number exceeds a given limit:

let $result := while-do(
  random-number-generator(),
  fn($random) {
    $random?number < 0.8
  },
  fn($random) {
    map:put($random?next(), 'numbers', ($random?numbers, $random?number))
  }
)
return $result?numbers

16.3 Dynamic Evaluation

The following functions allow dynamic loading and evaluation of XQuery queries, XSLT stylesheets, and XPath binary operators.

FunctionMeaning
fn:load-xquery-moduleProvides access to the public functions and global variables of a dynamically loaded XQuery library module.
fn:transformInvokes a transformation using a dynamically loaded XSLT stylesheet.
fn:opReturns a function whose effect is to apply a supplied binary operator to two arguments.

16.3.2 fn:load-xquery-module

Changes in 4.0  

  1. It has been clarified that loading a module has no effect on the static or dynamic context of the caller.  [Issue 725 PR 727 10 October 2023]

  2. The return type is now specified more precisely.  [Issue 883 PR 1072 19 March 2024]

  3. A new option is provided to allow the content of the loaded module to be supplied as a string.  [Issue 1329 PR 1333 22 July 2024]

Summary

Provides access to the public functions and global variables of a dynamically loaded XQuery library module.

Signature
fn:load-xquery-module(
$module-urias xs:string,
$optionsas map(*)?:= {}
) as load-xquery-module-record
Properties

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

Rules

The function loads an implementation-defined set of modules having the target namespace $module-uri.

If the second argument is omitted or an empty sequence, the result is the same as calling the two-argument form with an empty map as the value of the $options argument.

The $options argument can be used to control the way in which the function operates. The ·option parameter conventions· apply.

record(
xquery-version?as xs:decimal,
location-hints?as xs:string*,
content?as xs:string?,
context-item?as item()?,
variables?as map(xs:QName, item()*),
vendor-options?as map(xs:QName, item()*)
)
KeyMeaning

xquery-version?

The minimum level of the XQuery language that the processor must support.

location-hints?

A sequence of URIs (in the form of xs:string values) which may be used or ignored in an ·implementation-defined· way.
  • Type: xs:string*

  • Default: Empty sequence

content?

The content of the query module as a string. When this option is used, the location-hints option is ignored. The static base URI of the dynamically loaded module is the same as the static base URI of the caller.
  • Type: xs:string?

  • Default: Empty sequence

context-item?

The item to be used as the initial context item when evaluating global variables in the library module. Supplying an empty sequence is equivalent to omitting the entry from the map, and indicates the absence of a context item. If the library module specifies a required type for the context item, then the supplied value must conform to this type, without conversion.
  • Type: item()?

  • Default: Absent

variables?

Values for external variables defined in the library module. Values must be supplied for external variables that have no default value, and may be supplied for external variables that do have a default value. The supplied value must conform to the required type of the variable, without conversion. The map contains one entry for each external variable: the key is the variable’s name, and the associated value is the variable’s value. The ·option parameter conventions· do not apply to this contained map.
  • Type: map(xs:QName, item()*)

  • Default: An empty map

vendor-options?

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.
  • Type: map(xs:QName, item()*)

  • Default: An empty map

The result of the function is a map R with two entries, as defined in 16.3.1 Record fn:load-xquery-module-record.

The static and dynamic context of the library module are established according to the rules in Section C Context Components XQ31.

It is ·implementation-defined· whether constructs in the library module are evaluated in the same ·execution scope· as the calling module.

The library module that is loaded may import other modules using an import module declaration. The result of fn:load-xquery-module does not include global variables or functions declared in such a transitively imported module. However, the options map supplied in the function call may (and if no default is defined, must) supply values for external variables declared in transitively loaded library modules.

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 Section 2.2.5 Consistency Constraints XQ31.

Where nodes are passed to or from the dynamically loaded module, for example as an argument or result of a function, they should if possible retain their node identity, their base URI, their type annotations, and their relationships to all other nodes in the containing tree (including ancestors and siblings). If this is not possible, for example because the only way of passing nodes to the chosen XQuery implementation is by serializing and re-parsing, then a node may be passed in the form of a deep copy, which may lose information about the identity of the node, about its ancestors and siblings, about its base URI, about its type annotations, and about its relationships to other nodes passed across the interface.

Error Conditions

If $module-uri is a zero length string, a dynamic error is raised [err:FOQM0001].

If the implementation is not able to find a library module with the specified target namespace, an error is raised [err:FOQM0002].

If a static error (including a statically detected type error) is encountered when processing the library module, a dynamic error is raised [err:FOQM0003].

If a value is supplied for the initial context item or for an external variable and the value does not conform to the required type declared in the dynamically loaded module, a dynamic error is raised [err:FOQM0005].

If no suitable XQuery processor is available, a dynamic error is raised [err:FOQM0006]. This includes (but is not limited to) the following cases:

  1. No XQuery processor is available;

  2. Use of the function has been disabled;

  3. No XQuery processor supporting the requested version of XQuery is available;

  4. No XQuery processor supporting the optional Module Feature is available.

If a dynamic error (including a dynamically detected type error) is encountered when processing the module (for example, when evaluating its global variables), the dynamic error is returned as is.

Notes

If a function declaration F in the loaded module declares (say) four parameters of which one is optional, its arity range will be from 3 to 4, so the result will include two function items corresponding to F#3 and F#4. In the lower-arity function item, F#3, the fourth parameter will take its default value. If the expression that initializes the default value is context sensitive, the static and dynamic context for its evaluation are the static and dynamic contexts of the fn:load-xquery-module function call itself.

As with all other functions in this specification, conformance requirements depend on the host language. For example, a host language might specify that provision of this function is optional, or that it is excluded entirely, or that implementations are required to support XQuery modules using a specified version of XQuery.

Even where support for this function is mandatory, it is recommended for security reasons that implementations should provide a user option to disable its use, or to disable aspects of its functionality.

The load-xquery-module function does not modify the static or dynamic context. Functions and variables from the loaded module become available within the result returned by the function, but they are not added to the static or dynamic context of the caller. This means, for example, that function-lookup will not locate functions from the loaded module.

If a function declaration F in the loaded module declares (say) four parameters of which one is optional, its arity range will be from 3 to 4, so the result will include two function items corresponding to F#3 and F#4. In the lower-arity function item, F#3, the fourth parameter will take its default value. If the expression that initializes the default value is context sensitive, the static and dynamic context for its evaluation are the static and dynamic contexts of the fn:load-xquery-module function call itself.

As with all other functions in this specification, conformance requirements depend on the host language. For example, a host language might specify that provision of this function is optional, or that it is excluded entirely, or that implementations are required to support XQuery modules using a specified version of XQuery.

Even where support for this function is mandatory, it is recommended for security reasons that implementations should provide a user option to disable its use, or to disable aspects of its functionality.

The load-xquery-module function does not modify the static or dynamic context. Functions and variables from the loaded module become available within the result returned by the function, but they are not added to the static or dynamic context of the caller. This means, for example, that function-lookup will not locate functions from the loaded module.

Examples
Expression:
let $expr := "2 + 2"
let $module := `
  xquery version "4.0"; 
  module namespace dyn="http://example.com/dyn";
  declare %public variable $dyn:value := { $expr };
`
let $exec := load-xquery-module(
  "http://example.com/dyn",
  { 'content':$module }
)
let $variables := $exec?variables
return $variables(QName("http://example.com/dyn", "value"))
Result:
4

16.3.3 fn:transform

Summary

Invokes a transformation using a dynamically loaded XSLT stylesheet.

Signature
fn:transform(
$optionsas map(*)
) as map(*)
Properties

This function is ·nondeterministic·, ·context-dependent·, and ·focus-independent·.

Rules

This function loads an XSLT stylesheet and invokes it to perform a transformation.

The inputs to the transformation are supplied in the form of a map. The ·option parameter conventions· apply to this map; they do not apply to any nested map unless otherwise specified.

The function first identifies the requested XSLT version, as follows:

  • If the xslt-version option is present, the requested XSLT version is the value of that option.

  • Otherwise, the requested XSLT version is the value of the [xsl:]version attribute of the outermost element in the supplied stylesheet or package.

The function then attempts to locate an XSLT processor that implements the requested XSLT version.

  • If a processor that implements the requested XSLT version is available, then it is used.

  • Otherwise, if a processor that implements a version later than the requested version is available, then it is used.

  • Otherwise, the function fails indicating that no suitable XSLT processor is available.

Note:

The phrase locate an XSLT processor includes the possibility of locating a software product and configuring it to act as an XSLT processor that implements the requested XSLT version.

If more than one XSLT processor is available under the above rules, then the one that is chosen may be selected according to the availability of requested features: see below.

Once an XSLT processor has been selected that implements a given version of XSLT, the processor follows the rules of that version of the XSLT specification. This includes any decision to operate in backwards or forwards compatibility mode. For example, if an XSLT 2.0 processor is selected, and the stylesheet specifies version="1.0", then the processor will operate in backwards compatibility mode; if the same processor is selected and the stylesheet specifies version="3.0", the processor will operate in forwards compatibility mode.

The combinations of options that are relevant to each version of XSLT, other than xslt-version itself, are listed below. This is followed by a table giving the meaning of each option.

  1. For invocation of an XSLT 1.0 processor (see [XSL Transformations (XSLT) Version 1.0]), the supplied options must include all of the following (if anything else is present, it is ignored):

    1. The stylesheet, provided by supplying exactly one of the following:

      stylesheet-location
      stylesheet-node
      stylesheet-text

    2. The source tree, provided as the value of the source-node option.

    3. Zero or more of the following additional options:

      stylesheet-base-uri
      stylesheet-params (defaults to an empty map)
      initial-mode (defaults to the stylesheet’s default mode)
      delivery-format (defaults to document)
      serialization-params (defaults to an empty map)
      enable-messages (default is implementation-defined)
      requested-properties (default is an empty map)
      vendor-options (defaults to an empty map)
      cache (default is implementation-defined)

  2. For invocation of an XSLT 2.0 processor (see [XSL Transformations (XSLT) Version 2.0]), the supplied options must include all of the following (if anything else is present, it is ignored):

    1. The stylesheet, provided by supplying exactly one of the following:

      stylesheet-location
      stylesheet-node
      stylesheet-text

    2. Invocation details, as exactly one of the following:

      1. For apply-templates invocation, all of the following:

        source-node

        Optionally, initial-mode (defaults to the stylesheet’s default mode)

      2. For call-template invocation, all of the following:

        initial-template

        Optionally, source-node

    3. Zero or more of the following additional options:

      stylesheet-base-uri
      stylesheet-params (defaults to an empty map)
      base-output-uri (defaults to absent)
      delivery-format (defaults to document)
      serialization-params (defaults to an empty map)
      enable-messages (default is implementation-defined)
      enable-trace (default is implementation-defined)
      requested-properties (default is an empty map)
      vendor-options (defaults to an empty map)
      cache (default is implementation-defined)

  3. For invocation of an XSLT 3.0 processor (see [XSL Transformations (XSLT) Version 4.0]), the supplied options must include all of the following (if anything else is present, it is ignored):

    1. The stylesheet, provided either by supplying exactly one of the following:

      stylesheet-location
      stylesheet-node
      stylesheet-text

      Or by supplying exactly one of the following:

      package-location
      package-node
      package-text
      package-name plus optionally package-version

    2. Invocation details, as exactly one of the following combinations:

      1. For apply-templates invocation, all of the following:

        Exactly one of source-node or initial-match-selection

        Optionally, initial-mode

        Optionally, template-params

        Optionally, tunnel-params

      2. For call-template invocation using an explicit template name, all of the following:

        initial-template

        Optionally, template-params

        Optionally, tunnel-params

        Optionally, source-node

      3. For call-template invocation using the defaulted template name xsl:initial-template, all of the following:

        Optionally, template-params

        Optionally, tunnel-params

        Note:

        If the source-node option is present and initial-template is absent, then apply-templates invocation will be used. To use call-template invocation on the template named xsl:initial-template while also supplying a context item for use when evaluating global variables, either (a) supply the context item using the global-context-item option, or (b) supply source-node, and set the initial-template option explicitly to the QName xsl:initial-template

      4. For call-function invocation, all of the following:

        initial-function

        function-params

      Note:

      The invocation method can be determined as the first of the following which applies:

      • If initial-function is present, then call-function invocation.

      • If initial-template is present, then call-template invocation.

      • If source-node or initial-match-selection is present, then apply-templates invocation.

      • Otherwise, call-template invocation using the default entry point xsl:initial-template.

    3. Zero or more of the following additional options:

      stylesheet-base-uri
      static-params (defaults to an empty map)
      stylesheet-params (defaults to an empty map)
      global-context-item (defaults to absent)
      base-output-uri (defaults to absent)
      delivery-format
      serialization-params (defaults to an empty map)
      enable-assertions (default is false)
      enable-messages (default is implementation-defined)
      enable-trace (default is implementation-defined)
      requested-properties (default is an empty map)
      vendor-options (defaults to an empty map)
      cache (default is implementation-defined)

The meanings of each option are defined in the table below.

record(
base-output-uri?as xs:string,
cache?as xs:boolean,
delivery-format?as xs:string,
enable-assertions?as xs:boolean,
enable-messages?as xs:boolean,
enable-trace?as xs:boolean,
function-params?as array(item()*),
global-context-item?as item(),
initial-function?as xs:QName,
initial-match-selection?as item()*,
initial-mode?as xs:QName,
initial-template?as xs:QName,
package-name?as xs:string,
package-location?as xs:string,
package-node?as node(),
package-text?as xs:string,
package-version?as xs:string,
post-process?as fn(xs:string, item()*) as item()*,
requested-properties?as map(xs:QName, xs:anyAtomicType),
serialization-params?as map(xs:anyAtomicType, item()*),
source-node?as node(),
static-params?as map(xs:QName, item()*),
stylesheet-base-uri?as xs:string,
stylesheet-location?as xs:string,
stylesheet-node?as node(),
stylesheet-params?as map(xs:QName, item()*),
stylesheet-text?as xs:string,
template-params?as map(xs:QName, item()*),
tunnel-params?as map(xs:QName, item()*),
vendor-options?as { xs:QName, item()* },
xslt-version?as xs:decimal
)
KeyApplies toValueMeaning

base-output-uri?

1.0, 2.0, 3.0The URI of the principal result document; also used as the base URI for resolving relative URIs of secondary result documents. If the value is a relative reference, it is resolved against the static base URI of the fn:transform function call.
  • Type: xs:string

  • Default: The effect of not supplying a base output URI is defined by the XSLT specification; the implementation may supply a default, for example the directory containing the stylesheet, or the current working directory.

cache?

1.0, 2.0, 3.0This option has no effect on the result of the transformation but may affect efficiency. The value true indicates an expectation that the same stylesheet is likely to be used for more than one transformation; the value false indicates an expectation that the stylesheet will be used once only.
  • Type: xs:boolean

  • Default: true()

delivery-format?

1.0, 2.0, 3.0The manner in which the transformation results should be delivered. Applies both to the principal result document and to secondary result documents created using xsl:result-document.
  • Type: xs:string

  • Default: document

    If the relevant xsl:output or xsl:result-document element specifies build-tree="no" (applies to XSLT 3.0 only), then the default is raw.

documentThe result is delivered as a document node.
serializedThe result is delivered as a string, representing the results of serialization. Note that (as with the fn:serialize function) the final encoding stage of serialization (which turns a sequence of characters into a sequence of octets) is either skipped, or reversed by decoding the octet stream back into a character stream.
rawThe result of the initial template or function is returned as an arbitrary XDM value (after conversion to the declared type, but without wrapping in a document node, and without serialization): when this option is chosen, the returned map contains the raw result.

enable-assertions?

3.0Indicates whether any xsl:assert instructions in the stylesheet are to be evaluated.
  • Type: xs:boolean

  • Default: false()

enable-messages?

1.0, 2.0, 3.0Indicates whether any xsl:message instructions in the stylesheet are to be evaluated. The destination and formatting of any such messages is implementation-defined.

enable-trace?

2.0, 3.0Indicates whether any fn:trace functions in the stylesheet are to generate diagnostic messages. The destination and formatting of any such messages is implementation-defined.

function-params?

3.0An array of values to be used as the arguments to the initial function call. The value is converted to the required type of the declared parameter using the function conversion rules.
  • Type: array(item()*)

  • Default: Empty array

global-context-item?

3.0The value of the global context item, as defined in XSLT 3.0
  • Type: item()

  • Default: The value of source-node

initial-function?

3.0The name of the initial function to be called for call-function invocation. The arity of the function is inferred from the length of function-params.
  • Type: xs:QName

  • Default: n/a

initial-match-selection?

3.0The value of the initial match selection, as defined in XSLT 3.0
  • Type: item()*

  • Default: The value of source-node

initial-mode?

1.0, 2.0, 3.0The name of the initial processing mode.
  • Type: xs:QName

  • Default: none

initial-template?

2.0, 3.0The name of a named template in the stylesheet to act as the initial entry point.
  • Type: xs:QName

  • Default: xsl:initial-template

package-name?

3.0The name of the top-level stylesheet package to be invoked (an absolute URI)
  • Type: xs:string

  • Default: n/a

package-location?

3.0The location of the top-level stylesheet package, as a relative or absolute URI
  • Type: xs:string

  • Default: n/a

package-node?

3.0A document or element node containing the top-level stylesheet package
  • Type: node()

  • Default: n/a

package-text?

3.0The top-level stylesheet package in the form of unparsed lexical XML.
  • Type: xs:string

  • Default: n/a

package-version?

3.0The version of the top-level stylesheet package to be invoked.
  • Type: xs:string

  • Default: "*" (any version)

post-process?

1.0 2.0 3.0A function that is used to post-process each result document of the transformation (both the principal result and secondary results), in whatever form it would otherwise be delivered (document, serialized, or raw). The first argument of the function is the key used to identify the result in the map return by the fn:transform function (for example, this will be the supplied base output URI in the case of the principal result, or the string “output” if no base output URI was supplied). The second argument is the actual value. The value that is returned in the result of the fn:transform function is the result of applying this post-processing.

Note:

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

If the primary purpose of the post-processing function is achieved by means of such side-effects, and if the actual results are not needed by the caller of the fn:transform function, then it does not matter what the post-processing function actually returns (it could be an empty sequence, for example).

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

  • Type: fn(xs:string, item()*) as item()*

  • Default: fn($a, $b) { $b }

requested-properties?

1.0, 2.0, 3.0The keys in the map are QNames that could legitimately be supplied in a call to the XSLT system-property function; the values in the map are the requested settings of the corresponding property. The boolean values true() and false() are equivalent to the string values yes and no. As a special case, setting a value for xsl:version has no effect, because of the potential for conflict with other options. For example:
  • Setting xsl:product-name to a particular value requests a particular XSLT software product.

  • Setting xsl:product-version requests a specific version of that product.

  • Setting xsl:is-schema-aware to true() requests a schema-aware processor.

  • Setting xsl:xsd-version to "1.1" requests a processor that supports XML Schema version 1.1.

Setting a boolean property such as xsl:supports-dynamic-evaluation to false() is interpreted as an explicit request for a processor in which the value of the property is false. The effect if the requests cannot be precisely met is implementation-defined. In some cases it may be appropriate to ignore the request or to provide an alternative (for example, a later version of the product than the one requested); in other cases it may be more appropriate to raise an error [err:FOXT0001] indicating that no suitable XSLT processor is available.
  • Type: map(xs:QName, xs:anyAtomicType)

  • Default: Empty map

serialization-params?

1.0, 2.0, 3.0Serialization parameters for the principal result document. The supplied map follows the same rules that apply to a map supplied as the second argument of fn:serialize.
  • When a parameter is supplied, the corresponding value overrides or augments the value specified in the unnamed xsl:output declaration (or its default), following the same rules as when one xsl:output declaration overrides another with lower import precedence.

  • When a parameter is supplied and the corresponding value is an empty sequence (for example, { "standalone": () }), any value specified in the unnamed xsl:output declaration is overridden by the default value.

  • When a parameter is not supplied in serialization-params (that is, when the key is absent) the value that applies is the value appearing in the unnamed xsl:output declaration, or its default.

  • Type: map(xs:anyAtomicType, item()*)

  • Default: Empty map

source-node?

1.0, 2.0, 3.0When source-node is supplied then the global-context-item (the context item for evaluating global variables) is the root of the tree containing the supplied node. In addition, for apply-templates invocation, the source-node acts as the initial-match-selection, that is, stylesheet execution starts by applying templates to this node.
  • Type: node()

  • Default: n/a

static-params?

3.0The values of static parameters defined in the stylesheet; the keys are the names of the parameters, and the associated values are their values. The value is converted to the required type of the declared parameter using the coercion rules.
  • Type: map(xs:QName, item()*)

  • Default: Empty map

stylesheet-base-uri?

1.0, 2.0, 3.0A 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 static base URI of the fn:transform function call.
  • Type: xs:string

  • Default: n/a

stylesheet-location?

1.0, 2.0, 3.0URI that can be used to locate the principal stylesheet module. If relative, it is resolved against the static base URI of the fn:transform function call. The value also acts as the default for stylesheet-base-uri.
  • Type: xs:string

  • Default: n/a

stylesheet-node?

1.0, 2.0, 3.0Root of the tree containing the principal stylesheet module, as a document or element node. The base URI of the node acts as the default for stylesheet-base-uri.
  • Type: node()

  • Default: n/a

stylesheet-params?

1.0, 2.0, 3.0A map holding values to be supplied for stylesheet parameters. The keys are the parameter names; the values are the corresponding parameter values. The values are converted if necessary to the required type using the coercion rules. The default is an empty map.
  • Type: map(xs:QName, item()*)

  • Default: Empty map

stylesheet-text?

1.0, 2.0, 3.0The principal stylesheet module in the form of unparsed lexical XML.
  • Type: xs:string

  • Default: n/a

template-params?

3.0The values of non-tunnel parameters to be supplied to the initial template, used with both apply-templates and call-template invocation. Each value is converted to the required type of the declared parameter using the coercion rules.
  • Type: map(xs:QName, item()*)

  • Default: none

tunnel-params?

3.0The values of tunnel parameters to be supplied to the initial template, used with both apply-templates and call-template invocation. Each value is converted to the required type of the declared parameter using the coercion rules.
  • Type: map(xs:QName, item()*)

  • Default: Empty map

vendor-options?

1.0, 2.0, 3.0Values 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 an empty map.
  • Type: { xs:QName, item()* }

  • Default: Empty map

xslt-version?

1.0, 2.0, 3.0The minimum level of the XSLT language that the processor must support.
  • Type: xs:decimal

  • Default: The [xsl:]version attribute at the outermost level of the stylesheet.

The result of the transformation is returned as a map. There is one entry in the map for the principal result document, and one for each secondary result document. The key is a URI in the form of an xs:string value. The key for the principal result document is the base output URI if specified, or the string "output" otherwise. The key for secondary result documents is the URI of the document, as an absolute URI. The associated value in each entry depends on the requested delivery format. If the delivery format is document, the value is a document node. If the delivery format is serialized, the value is a string containing the serialized result.

Where nodes are passed to or from the transformation, for example as the value of a stylesheet parameter or the result of a function, they should if possible retain their node identity, their base URI, their type annotations, and their relationships to all other nodes in the containing tree (including ancestors and siblings). If this is not possible, for example because the only way of passing nodes to the chosen XSLT implementation is by serializing and re-parsing, then a node may be passed in the form of a deep copy, which may lose information about the identity of the node, about its ancestors and siblings, about its base URI, about its type annotation, and about its relationships to other nodes passed across the interface.

It is ·implementation-defined· whether the XSLT transformation is executed within the same ·execution scope· as the calling code.

The function is ·nondeterministic· in that it is ·implementation-dependent· whether running the function twice against the same inputs produces identical results. The results of two invocations may differ in the identity of any returned nodes; they may also differ in other respects, for example because the value of fn:current-dateTime is different for the two invocations, or because the contents of external documents accessed using fn:doc or xsl:source-document change between one invocation and the next.

Error Conditions

A dynamic error is raised [err:FOXT0001] if the transformation cannot be invoked because no suitable XSLT processor is available. This includes (but is not limited to) the following cases:

  1. No XSLT processor is available;

  2. No XSLT processor supporting the requested version of XSLT is available;

  3. The XSLT processor API does not support some requested feature (for example, the ability to supply tunnel parameters externally);

A dynamic error is raised [err:FOXT0002] if an error is detected in the supplied parameters (for example if two mutually exclusive parameters are supplied).

If a static or dynamic error is reported by the XSLT processor, this function fails with a dynamic error, retaining the XSLT error code.

A dynamic error is raised [err:FOXT0003] if the XSLT transformation invoked by a call on fn:transform fails with a static or dynamic error, and no more specific error code is available.

Note:

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.

A dynamic error is raised [err:FOXT0004] if the use of this function (or of selected options) has been externally disabled, for example for security reasons.

A dynamic error is raised [err:FOXT0006] if the transformation produces output containing characters available only in XML 1.1, and the calling processor cannot handle such characters.

Recursive use of the fn:transform function may lead to catastrophic failures such as non-termination or stack overflow. No error code is assigned to such conditions, since they cannot necessarily be detected by the processor.

Notes

As with all other functions in this specification, conformance requirements depend on the host language. For example, a host language might specify that provision of this function is optional, or that it is excluded entirely, or that implementations are required to support a particular set of values for the xslt-version parameter.

Even where support for this function is mandatory, it is recommended for security reasons that implementations should provide a user option to disable its use, or to disable aspects of its functionality such as the ability to write to persistent resources.

As with all other functions in this specification, conformance requirements depend on the host language. For example, a host language might specify that provision of this function is optional, or that it is excluded entirely, or that implementations are required to support a particular set of values for the xslt-version parameter.

Even where support for this function is mandatory, it is recommended for security reasons that implementations should provide a user option to disable its use, or to disable aspects of its functionality such as the ability to write to persistent resources.

Examples

The following example loads a stylesheet from the location render.xsl, applies it to a document loaded from test.xml, and uses an XPath expression to examine the result:

let $result := transform({
  "stylesheet-location": "render.xsl",
  "source-node": doc('test.xml')
})
return $result?output//body

16.3.4 fn:op

Changes in 4.0  

  1. New in 4.0  [Issue 83 PR 173 11 October 2022]

Summary

Returns a function whose effect is to apply a supplied binary operator to two arguments.

Signature
fn:op(
$operatoras xs:string
) as fn(item()*, item()*) as item()*
Properties

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

Rules

The supplied operator must be one of:

",", "and", "or", "+", "-", "*", "div", "idiv", "mod", "=", "<", "<=", ">", ">=", "!=", "eq", "lt", "le", "gt", "ge", "ne", "<<", ">>", "is", "||", "|", "union", "except", "intersect", "to", "otherwise"

The result of calling fn:op("⊙"), where is one of the above operators, is the function represented by the XPath expression:

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

For example, op("+") returns fn($x, $y) { $x + $y }.

Error Conditions

A type error is raised [err:XPTY0004]XP if the supplied argument is not one of the supported operators.

Notes

The function is useful in contexts where an arity-2 callback function needs to be supplied, and a standard operator meets the requirement.

For example, the XSLT xsl:map instruction has an on-duplicates attribute that expects such a function. Specifying on-duplicates="op(',')" is equivalent to specifying on-duplicates="fn($x, $y) { $x, $y }

The function is also useful in cases where the choice of operator to apply is made dynamically.

The function is useful in contexts where an arity-2 callback function needs to be supplied, and a standard operator meets the requirement.

For example, the XSLT xsl:map instruction has an on-duplicates attribute that expects such a function. Specifying on-duplicates="op(',')" is equivalent to specifying on-duplicates="fn($x, $y) { $x, $y }

The function is also useful in cases where the choice of operator to apply is made dynamically.

Examples
ExpressionResult
for-each-pair(21 to 25, 1 to 5, op("+"))
22, 24, 26, 28, 30
for-each-pair(21 to 25, 1 to 5, op("-"))
20, 20, 20, 20, 20

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

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

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 ·singleton map·.
map:entryReturns a ·singleton 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:of-pairsReturns a map that combines data from a sequence of ·key-value pair maps·.
map:pairReturns a ·key-value pair map· that represents a single key-value pair.
map:pairsReturns a sequence containing all the key-value pairs present in a map, each represented as a ·key-value pair map·.
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:replaceReturns a map based on the contents of an existing map, computing a new value to be associated with a supplied key.
map:sizeReturns the number of entries in the supplied map.

17.4.1 map:build

Changes in 4.0  

  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()*,
$keysas (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 $keys 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 calls the combine function in the $options argument to combine the existing value for the key with the new value, and replaces the entry with this combined value.

    The key of the combined entry is taken from one of the duplicate entries: it is ·implementation-defined· which one is used. (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 with different timezones.)

    The position of the combined entry in the entry orderDM of the result map is based on the position of the first entry having that key in the input sequence (that is, the order of keys in the result is the order of first appearance in the input.

The $options argument can be used to control the and 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(
combine?as (fn($existing-value as item()*, $new-value as item()*) as item()*)?
)
KeyValueMeaning

combine?

A function that is used to combine two different values that are supplied for the same key. The default is to combine the two values using sequence concatenationXP, retaining their order in the input sequence.
  • Type: (fn($existing-value as item()*, $new-value as item()*) as item()*)?

  • Default: fn:op(',')

User-supplied function The function is called for any entry in an input map 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.
Formal Equivalent

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

fold-left($input, {}, fn($map, $item, $pos) {
  let $v := $value($item, $pos)
  return fold-left($keys($item, $pos), $map, fn($m, $k) {
    if (map:contains($m, $k)) then (
      map:put($m, $k, $combine($m($k), $v))
    ) else (
      map:put($m, $k, $v)
    )
  })
})
Notes

The default function for both $keys 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.

The default action for combining entries with duplicate keys is to perform a sequence concatenationXP of the corresponding values, equivalent to the duplicates: combine option on map:merge. Other potentially useful functions for combining duplicates include:

The default function for both $keys 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.

The default action for combining entries with duplicate keys is to perform a sequence concatenationXP of the corresponding values, equivalent to the duplicates: combine option on map:merge. Other potentially useful functions for combining duplicates include:

  • fn($a, $b) { $a } Use the first value and discard the remainder

  • fn($a, $b) { $b } Use the last value and discard the remainder

  • fn:concat(?, ",", ?) Form the string-concatenation of the values, comma-separated

  • fn:op('+') Compute the sum of the values

The order of entriesDM in the result reflects the order of the items in $input from which they were derived. In the event that two entries have duplicate keys, the position of the combined entry in the result reflects the position of the first input item with that key.

The order of entriesDM in the result reflects the order of the items in $input from which they were derived. In the event that two entries have duplicate keys, the position of the combined entry in the result reflects the position of the first input item with that key.

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(
  ("apple", "apricot", "banana", "blueberry", "cherry"), 
  substring(?, 1, 1),
  string-length#1,
  { "combine": 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'),
  keys := 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>
  )
}

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 })

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.

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

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:

map:build(
  //employee,
  keys := fn { @location }, 
  combine := fn($a, $b) { highest(($a, $b), fn { xs:decimal(@salary) }) }
)

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

map:build(//*, generate-id#1)

17.4.5 map:entry

Summary

Returns a ·singleton map· that represents a single key-value pair.

Signature
map:entry(
$keyas xs:anyAtomicType,
$valueas item()*
) as map(*)
Properties

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

Rules

The function map:entry returns a ·map· which contains a single entry. The key of the entry in the new map is $key, and its associated value is $value.

Formal Equivalent

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

map:put({}, $key, $value)
Notes

The function map:entry is intended primarily for use in conjunction with the function map:merge. For example, a map containing seven entries may be constructed like this:

map:merge((
  map:entry("Su", "Sunday"),
  map:entry("Mo", "Monday"),
  map:entry("Tu", "Tuesday"),
  map:entry("We", "Wednesday"),
  map:entry("Th", "Thursday"),
  map:entry("Fr", "Friday"),
  map:entry("Sa", "Saturday")
))

The function map:entry is intended primarily for use in conjunction with the function map:merge. For example, a map containing seven entries may be constructed like this:

map:merge((
  map:entry("Su", "Sunday"),
  map:entry("Mo", "Monday"),
  map:entry("Tu", "Tuesday"),
  map:entry("We", "Wednesday"),
  map:entry("Th", "Thursday"),
  map:entry("Fr", "Friday"),
  map:entry("Sa", "Saturday")
))

The map:merge function can be used to construct a map with a variable number of entries, for example:

map:merge(//book ! map:entry(isbn, .))

The map:merge function can be used to construct a map with a variable number of entries, for example:

map:merge(//book ! map:entry(isbn, .))
Examples
ExpressionResult
map:entry("M", "Monday")
{ "M": "Monday" }

17.4.7 map:find

Changes in 4.0  

  1. Enhanced to allow for ordered maps.  [Issue 1651 PR 1703 14 January 2025]

Summary

Searches the supplied input sequence and any contained maps and arrays for a map entry with the supplied key, and returns the corresponding values.

Signature
map:find(
$inputas item()*,
$keyas xs:anyAtomicType
) as array(*)
Properties

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

Rules

The function map:find searches the sequence supplied as $input looking for map entries whose key is the ·same key· as $key. The associated value in any such map entry (each being in general a sequence) is returned as a member of the result array.

The search processes the $input sequence using the following recursively defined rules (any equivalent algorithm may be used provided it delivers the same result, respecting those rules that constrain the order of the result):

  1. To process a sequence, process each of its items in order.

  2. To process an item that is an array, process each of its members in order (each member is, in general, a sequence).

  3. To process an item that is a map, then for each key-value entry (K, V) in the map (in entry orderDM) perform both of the following steps, in order:

    1. If K is the ·same key· as $key, then add V as a new member to the end of the result array.

    2. Process V (which is, in general, a sequence).

  4. To process an item that is neither a map nor an array, do nothing. (Such items are ignored).

Notes

If $input is an empty sequence, map, or array, or if the requested $key is not found, the result will be a zero-length array.

If $input is an empty sequence, map, or array, or if the requested $key is not found, the result will be a zero-length array.

Examples
Variables
let $responses := [
  { 0: 'no', 1: 'yes' },
  { 0: 'non', 1: 'oui' },
  { 0: 'nein', 1: ('ja', 'doch') }
]
let $inventory := {
  "name": "car",
  "id": "QZ123", 
  "parts": [ { "name": "engine", "id": "YW678", "parts": [] } ]
}
Expression:

map:find($responses, 0)

Result:
[ 'no', 'non', 'nein' ]
Expression:

map:find($responses, 1)

Result:
[ 'yes', 'oui', ('ja', 'doch') ]
Expression:

map:find($responses, 2)

Result:
[]
Expression:

map:find($inventory, "parts")

Result:
[
  [ { "name": "engine", "id": "YW678", "parts": [] } ],
  []
]

17.4.9 map:get

Changes in 4.0  

  1. A third argument is added, allowing user control of how absent keys should be handled.

Summary

Returns the value associated with a supplied key in a given map.

Signature
map:get(
$mapas map(*),
$keyas xs:anyAtomicType,
$fallbackas (fn($key as xs:anyAtomicType) as item()*)?:= void#1
) as item()*
Properties

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

Rules

The function map:get attempts to find an entry within the ·map· supplied as $map that has the ·same key· as $key. If there is such an entry, it returns the associated value; if not, it invokes the supplied $fallback function, supplying the requested $key value as the argument, and returns the result of this call. The default $fallback function always returns an empty sequence.

Formal Equivalent

The function is defined as follows, making use of primitive constructors and accessors defined in [XQuery and XPath Data Model (XDM) 4.0].

let $entry := dm:iterate-map($map, fn($k, $v) {
  if (atomic-equal($k, $key)) {
    map:entry($k, $v)
  }
})
return (
  if (exists($entry))
  then map:items($entry)
  else $fallback($key)
)
Notes

A return value of () from map:get could indicate that the key is present in the map with an associated value of (), or it could indicate that the key is not present in the map. The two cases can be distinguished by calling map:contains, or by using a $fallback function to return a value known never to appear in the map.

The $fallback function can be used in a number of ways:

A return value of () from map:get could indicate that the key is present in the map with an associated value of (), or it could indicate that the key is not present in the map. The two cases can be distinguished by calling map:contains, or by using a $fallback function to return a value known never to appear in the map.

The $fallback function can be used in a number of ways:

  • It might return a conventional value such as NaN to indicate that no matching key was found.

  • It might raise a dynamic error, by means of a call on fn:error.

  • It might compute a result algorithmically. For example, if the map holds a table of abbreviations, such as { 'CA': 'Canada', 'UK': 'United Kingdom', 'US': 'United States' }, then specifying fallback := fn:identity#1 has the effect that the key value is returned unchanged if it is not found in the map.

Invoking the ·map· as a function item has the same effect as calling getwith no $fallback function: that is, when $map is a map, the expression $map($K) is equivalent to map:get($map, $K). Similarly, the expression map:get(map:get(map:get($map, 'employee'), 'name'), 'first') can be written as $map('employee')('name')('first').

Invoking the ·map· as a function item has the same effect as calling getwith no $fallback function: that is, when $map is a map, the expression $map($K) is equivalent to map:get($map, $K). Similarly, the expression map:get(map:get(map:get($map, 'employee'), 'name'), 'first') can be written as $map('employee')('name')('first').

Examples
Variables
let $week := {
  0: "Sonntag", 1: "Montag", 2: "Dienstag", 3: "Mittwoch",
  4: "Donnerstag", 5: "Freitag", 6: "Samstag"
}
Expression:

map:get($week, 4)

Result:
"Donnerstag"
Expression:

map:get($week, 9)

Result:
()

(When the key is not present, the function returns an empty sequence.)

Expression:

map:get(map:entry(7,()), 7)

Result:
()

(An empty sequence as the result can also signify that the key is present and the associated value is an empty sequence.)

Expression:
{ 1: "single", 2: "double", 3: "triple" }
=> map:get(10, fn { . || "-fold" })
Result:
"10-fold"

(The map holds special cases; the fallback function handles other cases.)

17.4.11 map:keys

Summary

Returns a sequence containing all the keys present in a map.

Signature
map:keys(
$mapas map(*)
) as xs:anyAtomicType*
Properties

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

Rules

Informally, the function map:keys takes any ·map· as its $map argument and returns the keys that are present in the map as a sequence of atomic items, in entry orderDM.

Formal Equivalent

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

map:for-each($map, fn($key, $value) { $key })
Notes

The number of items in the result will be the same as the number of entries in the map, and the result sequence will contain no duplicate values.

The number of items in the result will be the same as the number of entries in the map, and the result sequence will contain no duplicate values.

Examples
ExpressionResult
map:keys({ 1: "yes", 0: "no" })
(1, 0)
map:keys(map:merge(({"red": 0}, {"blue": 1}, {"green": 2})))
("red", "blue", "green")

17.4.13 map:merge

Changes in 4.0  

  1. For consistency with the new functions map:build and map:of-pairs, the handling of duplicates may now be controlled by the combine option as an alternative to the existing duplicates option.  [Issue 1725 ]

Summary

Returns a map that combines the entries from a number of existing maps.

Signature
map:merge(
$mapsas map(*)*,
$optionsas map(*)?:= {}
) as map(*)
Properties

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

Rules

The function map:mergereturns a map that is formed by combining the contents of the maps supplied in the $maps argument.

Informally, the supplied maps are combined as follows:

  1. There is one entry in the returned map for each distinct key present in the union of the input maps, where two keys are distinct if they are not the ·same key·.

  2. If there are duplicate keys, that is, if two or more maps contain entries having the ·same key·, then the way this is handled is controlled by the $options argument.

The definitive specification is as follows.

  1. If the second argument is omitted or an empty sequence, the effect is the same as calling the two-argument function with an empty map as the value of $options.

  2. The $options argument can be used to control the way in which duplicate keys are handled. The ·option parameter conventions· apply.

  3. In the event that two or more entries in the input maps have the ·same key·:

    1. A single entry is created by combining the values of the duplicates, in a way determined by the supplied $options.

    2. The key of the combined entry is one of the duplicate keys: which one is chosen is ·implementation-defined·. (Two keys that are deemed duplicates may differ: for example they may have different type annotations, or they may be xs:dateTime values with different timezones.)

    3. The position of the combined entry in the entry orderDM of the result map corresponds to the position of the first appearance of the corresponding key value in the input.

  4. The entries that may appear in the $options map are as follows:

    record(
    duplicates?as xs:string,
    combine?as (fn($existing-value as item()*, $new-value as item()*) as item()*)?
    )
    KeyValueMeaning

    duplicates?

    Determines the policy for handling duplicate keys: specifically, the action to be taken if two maps in the input sequence $maps contain entries with key values K1 and K2 where K1 and K2 are the ·same key·. This option and the combine option are mutually exclusive.
    • Type: xs:string

    • Default: use-first

    reject Equivalent to specifying "combine": fn(){error(xs:QName("err:FOJS0003"), ...) (the remaining arguments to fn:error being ·implementation-defined·).
    use-firstEquivalent to specifying "combine": fn($a, $b){ $a }.
    use-lastEquivalent to specifying "combine": fn($a, $b){ $b }.
    use-anyEquivalent to specifying "combine": fn($a, $b){ one-of($a, $b) } where one-of chooses either $a or $b in an ·implementation-defined· way.
    combineEquivalent to specifying "combine": fn($a, $b){ $a, $b }.

    combine?

    Supplies a function for handling duplicate keys: specifically, the action to be taken if two maps in the input sequence $maps contain entries with key values K1 and K2 where K1 and K2 are the ·same key·. This option and the duplicates option are mutually exclusive.
    • Type: (fn($existing-value as item()*, $new-value as item()*) as item()*)?

    • Default: fn($a, $b){ $a }

    User-supplied function A function with signature fn(item()*, item()*) as item()*. The function is called for any entry in an input map 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.
Formal Equivalent

The effect of the function is equivalent to the result of the following XPath expression, except in error cases.

let $FOJS0003 := QName("http://www.w3.org/2005/xqt-errors", "FOJS0003")
let $combiner := $options?combine
  otherwise {
      "use-first": fn($a, $b) { $a },
      "use-last":  fn($a, $b) { $b },
      "combine":   fn($a, $b) { $a, $b },
      "reject":    fn($a, $b) { fn:error($FOJS0003) },
      "use-any":   fn($a, $b) { fn:random-number-generator()?permute(($a, $b))[1] }
    } ($options?duplicates)
  otherwise        fn($a, $b) { $a }
  
return map:of-pairs($maps =!> map:pairs(), { "combine": $combiner });
Error Conditions

An error is raised [err:FORG0013] if both the combine and duplicates options are present.

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

Note:

By way of explanation, the function first reduces the sequence of input maps to a sequence of key-value pairs, retaining order of both the maps and of the entries within each map. It then combines key-value pairs having the ·same key· by applying the $combine function successively to pairs of duplicates. The position in the entry orderDM of the result map of an entry formed by combining duplicates corresponds to the position of the first occurrence of the key in the input sequence. This is true even whien the option use-last is used: the value of the resulting entry corresponds to the last entry with a given key, but the position of the entry in the result map corresponds to the position of the first entry with that key.

The use of fn:random-number-generator represents one possible conformant implementation for "duplicates": "use-any", but it is not the only conformant implementation and is not intended to be a realistic implementation. The purpose of this option is to allow the implementation to use whatever strategy is most efficient; for example, if the input maps are processed in parallel, then specifying "duplicates": "use-any" means that the implementation does not need to keep track of the original order of the sequence of input maps.

Note:

By way of explanation, the function first reduces the sequence of input maps to a sequence of key-value pairs, retaining order of both the maps and of the entries within each map. It then combines key-value pairs having the ·same key· by applying the $combine function successively to pairs of duplicates. The position in the entry orderDM of the result map of an entry formed by combining duplicates corresponds to the position of the first occurrence of the key in the input sequence. This is true even whien the option use-last is used: the value of the resulting entry corresponds to the last entry with a given key, but the position of the entry in the result map corresponds to the position of the first entry with that key.

The use of fn:random-number-generator represents one possible conformant implementation for "duplicates": "use-any", but it is not the only conformant implementation and is not intended to be a realistic implementation. The purpose of this option is to allow the implementation to use whatever strategy is most efficient; for example, if the input maps are processed in parallel, then specifying "duplicates": "use-any" means that the implementation does not need to keep track of the original order of the sequence of input maps.

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

If the input is a sequence of length one, the result map is indistinguishable from the supplied map.

There is no requirement that the supplied input maps should have the same or compatible types. The type of a map (for example map(xs:integer, xs:string)) is descriptive of the entries it currently contains, but is not a constraint on how the map may be combined with other maps.

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

If the input is a sequence of length one, the result map is indistinguishable from the supplied map.

There is no requirement that the supplied input maps should have the same or compatible types. The type of a map (for example map(xs:integer, xs:string)) is descriptive of the entries it currently contains, but is not a constraint on how the map may be combined with other maps.

Examples
Variables
let $week := {
  0: "Sonntag", 1: "Montag", 2: "Dienstag", 3: "Mittwoch",
  4: "Donnerstag", 5: "Freitag", 6: "Samstag"
}
Expression:

map:merge(())

Result:
{}

(Returns an empty map).

Expression:
map:merge((
  map:entry(0, "no"),
  map:entry(1, "yes")
))
Result:
{ 0: "no", 1: "yes" }

(Returns a map with two entries).

Expression:
map:merge(
  ($week, { 7: "Unbekannt" })
)
Result:
{ 0: "Sonntag", 1: "Montag", 2: "Dienstag", 3: "Mittwoch",
  4: "Donnerstag", 5: "Freitag", 6: "Samstag", 7: "Unbekannt" }

(The value of the existing map is unchanged; the returned map contains all the entries from $week, supplemented with an additional entry.)

Expression:
map:merge(
  ($week, { 6: "Sonnabend" }),
  { "duplicates": "use-last" }
)
Result:
{ 0: "Sonntag", 1: "Montag", 2: "Dienstag", 3: "Mittwoch",
  4: "Donnerstag", 5: "Freitag", 6: "Sonnabend" }

(The value of the existing map is unchanged; the returned map contains all the entries from $week, with one entry replaced by a new entry. Both input maps contain an entry with the key 6; the one used in the result is the one that comes last in the input sequence.)

Expression:
map:merge(
  ($week, { 6: "Sonnabend" }),
  { "duplicates": "use-first" }
)
Result:
{ 0: "Sonntag", 1: "Montag", 2: "Dienstag", 3: "Mittwoch",
  4: "Donnerstag", 5: "Freitag", 6: "Samstag" }

(The value of the existing map is unchanged; the returned map contains all the entries from $week, with one entry replaced by a new entry. Both input maps contain an entry with the key 6; the one used in the result is the one that comes first in the input sequence.)

Expression:
map:merge(
  ($week, { 6: "Sonnabend" }),
  { "duplicates": "combine" }
)
Result:
{ 0: "Sonntag", 1: "Montag", 2: "Dienstag", 3: "Mittwoch",
  4: "Donnerstag", 5: "Freitag", 6: ("Samstag", "Sonnabend") }

(The value of the existing map is unchanged; the returned map contains all the entries from $week, with one entry replaced by a new entry. Both input maps contain an entry with the key 6; the entry that appears in the result is the sequence concatenationXP of the entries in the input maps, retaining order.)

Expression:
map:merge(({ "red": 0 }, { "green": 1}, { "blue": 2 })) 
                  => map:keys()
Result:
"red", "green", "blue"

17.4.14 map:of-pairs

Changes in 4.0  

  1. New in 4.0

Summary

Returns a map that combines data from a sequence of ·key-value pair maps·.

Signature
map:of-pairs(
$inputas key-value-pair*,
$optionsas map(*):= {}
) as map(*)
Properties

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

Rules

The function map:of-pairsreturns a map that is formed by combining ·key-value pair maps· supplied in the $input argument.

The $options argument can be used to control the way in which duplicate keys are handled. The ·option parameter conventions· apply. The handling of duplicates is defined to be the same as in an equivalent call of the map:build function: see the formal equivalent below.

The entries that may appear in the $options map are as follows:

record(
combine?as (fn($existing-value as item()*, $new-value as item()*) as item()*)?
)
KeyValueMeaning

combine?

A function that is used to combine two different values that are supplied for the same key. The default is to combine the two values using sequence concatenationXP, retaining their order in the input sequence.
  • Type: (fn($existing-value as item()*, $new-value as item()*) as item()*)?

  • Default: fn:op(',')

User-supplied function The function is called for any entry in an input map 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.
Formal Equivalent

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

map:build($input, map:get(?, 'key'), map:get(?, 'value'), $combine)
Error Conditions

The function can be made to fail with a dynamic error in the event that duplicate keys are present in the input sequence by supplying a $combine function that invokes the fn:error function.

Notes

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

There is no requirement that the supplied key-value pairs should have the same or compatible types. The type of a map (for example map(xs:integer, xs:string)) is descriptive of the entries it currently contains, but is not a constraint on how the map may be combined with other maps.

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

There is no requirement that the supplied key-value pairs should have the same or compatible types. The type of a map (for example map(xs:integer, xs:string)) is descriptive of the entries it currently contains, but is not a constraint on how the map may be combined with other maps.

Examples
Variables
let $week := {
  0: "Sonntag", 1: "Montag", 2: "Dienstag", 3: "Mittwoch",
  4: "Donnerstag", 5: "Freitag", 6: "Samstag"
}
Expression:

map:of-pairs(())

Result:
{}

(Returns an empty map).

Expression:

map:of-pairs(map:pairs($week))

Result:
{
  0: "Sonntag",
  1: "Montag", 
  2: "Dienstag",
  3: "Mittwoch", 
  4: "Donnerstag",
  5: "Freitag", 
  6: "Samstag"
}

(The function map:of-pairs is the inverse of map:pairs.)

Expression:
map:of-pairs((
  { "key": 0, "value": "no" },
  { "key": 1, "value": "yes" }
))
Result:
{ 0: "no", 1: "yes" }

(Returns a map with two entries).

Expression:
map:of-pairs((
  map:pairs($week),
  { "key": 7, "value": "Unbekannt" }
))
Result:
{ 0: "Sonntag", 1: "Montag", 2: "Dienstag", 3: "Mittwoch",
  4: "Donnerstag", 5: "Freitag", 6: "Samstag", 7: "Unbekannt" }

(The value of the existing map is unchanged; the returned map contains all the entries from $week, supplemented with an additional entry.)

Expression:
map:of-pairs((
  map:pairs($week),
  { "key": 6, "value": "Sonnabend" }
))
Result:
{ 0: "Sonntag", 1: "Montag", 2: "Dienstag", 3: "Mittwoch",
  4: "Donnerstag", 5: "Freitag", 6: ("Samstag", "Sonnabend") }

(The value of the existing map is unchanged; the returned map contains all the entries from $week, with one entry replaced by a new entry. Both input maps contain an entry with the key 6; the one used in the result combines the two supplied values into a single sequence.)

Expression:
map:of-pairs(
  (map:pairs($week), { "key": 6, "value": "Sonnabend" }),
  fn($old, $new) { $new }
)
Result:
{ 0: "Sonntag", 1: "Montag", 2: "Dienstag", 3: "Mittwoch",
  4: "Donnerstag", 5: "Freitag", 6: "Sonnabend" }

(The value of the existing map is unchanged; the returned map contains all the entries from $week, with one entry replaced by a new entry. Both input maps contain an entry with the key 6; the supplied $combine function ensures that the one used in the result is the one that comes last in the input sequence.)

Expression:
map:of-pairs(
  (map:pairs($week), { "key": 6, "value": "Sonnabend" }),
  fn($old, $new) { `{ $old }|{ $new }` }
)
Result:
{ 0: "Sonntag", 1: "Montag", 2: "Dienstag", 3: "Mittwoch",
  4: "Donnerstag", 5: "Freitag", 6: "Samstag|Sonnabend" }

(In the result map, the value for key 6 is obtained by concatenating the values from the two input maps, with a separator character.)

Expression:
map:of-pairs((map:pair("red": 0), map:pair("green": 1), map:pair("blue": 2 )) 
        => map:keys()
Result:
"red", "green", "blue"

(The keys are returned in the order supplied.)

Expression:
{ "red": 0, "green": 1, "blue": 2 }
                  => map:pairs() => sort(keys := fn{ ?key }) => map:of-pairs()) 
        => map:keys()
Result:
"blue", "green", "red"

(Takes any map and produces a map with the same entries, but sorted by key.)

Expression:
map:of-pairs((map:pair("red": 0), map:pair("green": 1), map:pair("blue": 2 )) 
        => map:put("yellow": -1) => map:keys()
Result:
"red", "green", "blue", "yellow"

(New entries are added at the end.)

The following expression takes an existing map and sorts its entries into key order:

map:of-pairs(map:pairs($M) => sort(keys:=fn{?key}))

17.4.15 map:pair

Changes in 4.0  

  1. New in 4.0

Summary

Returns a ·key-value pair map· that represents a single key-value pair.

Signature
map:pair(
$keyas xs:anyAtomicType,
$valueas item()*
) as key-value-pair
Properties

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

Rules

The function map:pair returns a ·map· which contains two entries, one (with the key "key") containing $key and the other (with the key "value") containing $value.

Formal Equivalent

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

{}
=> map:put("key", $key)
=> map:put("value", $value)
Notes

The function call map:pair(K, V) produces the same result as the expression { "key": K, "value": V }.

The function map:pair is intended primarily for use in conjunction with the function map:of-pairs. A map may be constructed like this:

map:of-pairs((
  map:pair("Su", "Sunday"),
  map:pair("Mo", "Monday"),
  map:pair("Tu", "Tuesday"),
  map:pair("We", "Wednesday"),
  map:pair("Th", "Thursday"),
  map:pair("Fr", "Friday"),
  map:pair("Sa", "Saturday")
))

The function call map:pair(K, V) produces the same result as the expression { "key": K, "value": V }.

The function map:pair is intended primarily for use in conjunction with the function map:of-pairs. A map may be constructed like this:

map:of-pairs((
  map:pair("Su", "Sunday"),
  map:pair("Mo", "Monday"),
  map:pair("Tu", "Tuesday"),
  map:pair("We", "Wednesday"),
  map:pair("Th", "Thursday"),
  map:pair("Fr", "Friday"),
  map:pair("Sa", "Saturday")
))

The map:of-pairs function can be used to construct a map with a variable number of entries, for example:

map:of-pairs(//book ! map:pair(./isbn, .))

The map:of-pairs function can be used to construct a map with a variable number of entries, for example:

map:of-pairs(//book ! map:pair(./isbn, .))
Examples
ExpressionResult
map:pair("M", "Monday")
{ "key": "M", "value": "Monday" }

17.4.17 map:put

Changes in 4.0  

  1. Enhanced to allow for ordered maps.  [Issue 1651 PR 1703 14 January 2025]

Summary

Returns a map containing all the contents of the supplied map, but with an additional entry, which replaces any existing entry for the same key.

Signature
map:put(
$mapas map(*),
$keyas xs:anyAtomicType,
$valueas item()*
) as map(*)
Properties

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

Rules

The function map:put returns a ·map· that contains all entries from the supplied $map, with the exception of any entry whose key is the ·same key· as $key, together with a new entry whose key is $key and whose associated value is $value.

The entry orderDM of the entries in the returned map is as follows: if $map contains an entry whose key is $key, then the new value replaces the old value and the position of the entry is not changed; otherwise, the new entry is added after all existing entries.

Formal Equivalent

The function is defined as follows, making use of primitive constructors and accessors defined in [XQuery and XPath Data Model (XDM) 4.0].

dm:map-put($map, $key, $value)
Notes

There is no requirement that the type of $key and $value be consistent with the types of any existing keys and values in the supplied map.

It is possible to force the new entry to go at the end of the sequence by calling map:remove before calling map:put.

There is no requirement that the type of $key and $value be consistent with the types of any existing keys and values in the supplied map.

It is possible to force the new entry to go at the end of the sequence by calling map:remove before calling map:put.

Examples
Variables
let $week := {
  0: "Sonntag", 1: "Montag", 2: "Dienstag", 3: "Mittwoch",
  4: "Donnerstag", 5: "Freitag", 6: "Samstag"
}
Expression:

map:put($week, 6, "Sonnabend")

Result:
{ 0: "Sonntag", 1: "Montag", 2: "Dienstag", 3: "Mittwoch",
  4: "Donnerstag", 5: "Freitag", 6: "Sonnabend" }
Expression:

map:put($week, -1, "Unbekannt")

Result:
{ 0: "Sonntag", 1: "Montag", 2: "Dienstag", 3: "Mittwoch",
  4: "Donnerstag", 5: "Freitag", 6: "Samstag", -1: "Unbekannt" }
Expression:
parse-json('{ "red": 0, "green": 1, "blue" 2 }')
  => map:put("yellow", -1) 
  => map:keys()
Result:
"red", "green", "blue", "yellow"

(The new entry is added at the end of the list.)

Expression:
parse-json('{ "red": 0, "green": 1, "blue" 2 }')
  => map:put("red", -1) 
  => map:keys()
Result:
"red", "green", "blue"

(Changing the value for an existing key does not change the order of the keys.)

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

18.2 Functions that Operate on Arrays

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

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

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

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

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

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

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

18.2.2 array:build

Changes in 4.0  

  1. New in 4.0  [Issue 97 PR 250]

Summary

Returns an array obtained by evaluating the supplied function once for each item in the input sequence.

Signature
array:build(
$inputas item()*,
$actionas (fn(item(), xs:integer) as item()*)?:= fn:identity#1
) as array(*)
Properties

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

Rules

If the function is called with one argument, the effect is the same as calling the two-argument function with fn:identity#1 as the second argument.

Informally, array:build#2 applies the supplied function to each item in the input sequence, and the resulting sequence becomes one member of the returned array.

Formal Equivalent

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

fold-left($input, [], fn($array, $next, $pos) {
   array:append($array, $action($next, $pos))
})
Notes

The single-argument function array:build($input) is equivalent to the XPath expression array { $input }, but it is useful to have this available as a function.

The two-argument form facilitates the construction of arrays whose members are arbitrary sequences.

The single-argument function array:build($input) is equivalent to the XPath expression array { $input }, but it is useful to have this available as a function.

The two-argument form facilitates the construction of arrays whose members are arbitrary sequences.

Examples
Expression:

array:build(1 to 5)

Result:
[ 1, 2, 3, 4, 5 ]
Expression:
array:build(1 to 5, fn { 2 * . })
Result:
[ 2, 4, 6, 8, 10 ]
Expression:
array:build(1 to 5, fn { 1 to . })
Result:
[ 1, (1, 2), (1, 2, 3), (1, 2, 3, 4), (1, 2, 3, 4, 5) ]
Expression:
array:build(("red", "green", "blue"), characters#1)
Result:
[ ("r", "e", "d"), ("g", "r", "e", "e", "n"), ("b", "l", "u", "e") ]
Expression:
array:build(1 to 5, fn { array { 1 to . } })
Result:
[ [ 1 ], [ 1, 2 ], [ 1, 2, 3 ], [ 1, 2, 3, 4 ], [ 1, 2, 3, 4, 5 ] ]
Expression:
array:build(
  (0x41 to 0x48) ! char(.),
  fn($char, $pos) {
    if($pos mod 2 = 0) then lower-case($char) else $char
  }
)
Result:
[ "A", "b", "C", "d", "E", "f", "G", "h" ]

18.2.3 array:empty

Changes in 4.0  

  1. New in 4.0

Summary

Returns true if the supplied array contains no members.

Signature
array:empty(
$arrayas array(*)
) as xs:boolean
Properties

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

Rules

The function returns true if and only if $array contains no members.

Formal Equivalent

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

array:size($array) eq 0
Notes

The test for emptiness is not the same as the test used by the xsl:on-empty instruction in XSLT. For example, an array is not considered empty by this function if it contains a single member that is itself an empty array.

The test for emptiness is not the same as the test used by the xsl:on-empty instruction in XSLT. For example, an array is not considered empty by this function if it contains a single member that is itself an empty array.

Examples
ExpressionResult
array:empty([ "a", "b", "c" ])
false()
array:empty([])
true()
array:empty([ [] ])
false()
array:empty([ () ])
false()

18.2.5 array:flatten

Summary

Replaces any array appearing in a supplied sequence with the members of the array, recursively.

Signature
array:flatten(
$inputas item()*
) as item()*
Properties

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

Rules

The function processes the items in the supplied sequence $input as follows:

  • An item that is an array is replaced by its members, retaining order.

  • Any other item is retained unchanged.

The process is then repeated so long as the sequence contains an array among its items.

Formal Equivalent

The function delivers the same result as the following XQuery implementation.

declare function array:flatten(
  $input as item()*
) as item()* {
  for $item in $input
  return (
    if ($item instance of array(*)) 
    then array:flatten(array:items($item)) 
    else $item
  )
};
Notes

The argument to the function will often be a single array item, but this is not essential.

Unlike atomization, this function retains any nodes contained in the array.

The argument to the function will often be a single array item, but this is not essential.

Unlike atomization, this function retains any nodes contained in the array.

Examples
ExpressionResult
array:flatten([ 1, 4, 6, 5, 3 ])
1, 4, 6, 5, 3
array:flatten(([ 1, 2 ], [ [ 10, 11 ], 12 ], [], 13))
1, 2, 10, 11, 12, 13
array:flatten([ (1, 0), (1, 1), (0, 1), (0, 0) ])
1, 0, 1, 1, 0, 1, 0, 0

18.2.6 array:fold-left

Changes in 4.0  

  1. The $action callback function now accepts an optional position argument.  [Issue 516 PR 828 14 November 2023]

Summary

Evaluates the supplied function cumulatively on successive members of the supplied array.

Signature
array:fold-left(
$arrayas array(*),
$zeroas item()*,
$actionas fn(item()*, item()*, xs:integer) as item()*
) as item()*
Properties

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

Rules

The function is defined formally below, in terms of the equivalent fn:fold-left function for sequences.

Formal Equivalent

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

fold-left(
  array:members($array),
  $zero,
  fn($result, $member, $pos) { $action($result, map:get($member, 'value'), $pos) }
)
Notes

If the supplied array is empty, the function returns $zero.

If the supplied array contains a single member $m, the function returns $zero => $action($m).

If the supplied array contains two members $m and $n, the function returns $zero => $action($m) => $action($n); and similarly for an input array with more than two members.

The value of the third argument of $action corresponds to the position of the member in the input array. It is initally set to 1.

If the supplied array is empty, the function returns $zero.

If the supplied array contains a single member $m, the function returns $zero => $action($m).

If the supplied array contains two members $m and $n, the function returns $zero => $action($m) => $action($n); and similarly for an input array with more than two members.

The value of the third argument of $action corresponds to the position of the member in the input array. It is initally set to 1.

Examples
Expression:
array:fold-left(
  [ true(), true(), false() ],
  true(),
  fn($x, $y) { $x and $y }
)
Result:
false()

(Returns true if every member of the input array has an effective boolean value of true().)

Expression:
array:fold-left(
  [ true(), true(), false() ],
  false(), 
  fn($x, $y) { $x or $y }
)
Result:
true()

(Returns true if at least one member of the input array has an effective boolean value of true().)

Expression:
array:fold-left(
  [ 1, 2, 3 ],
  [],
  fn($x, $y) { [ $x, $y ] }
)
Result:
[[[[], 1], 2], 3]
Expression:
let $input := array { 11 to 21, 21 to 31 }
let $target := 21
return array:fold-left($input, (),
  fn($result, $curr, $pos) {
    $result, if ($curr = $target) { $pos }
  }
)
Result:
11, 12

18.2.7 array:fold-right

Changes in 4.0  

  1. The $action callback function now accepts an optional position argument.  [Issue 516 PR 828 14 November 2023]

Summary

Evaluates the supplied function cumulatively on successive values of the supplied array.

Signature
array:fold-right(
$arrayas array(*),
$zeroas item()*,
$actionas fn(item()*, item()*, xs:integer) as item()*
) as item()*
Properties

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

Rules

The function is defined formally below, in terms of the equivalent fn:fold-right function for sequences.

Formal Equivalent

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

fold-right(
  array:members($array),
  $zero,
  fn($member, $result, $pos) { $action(map:get($member, 'value'), $result, $pos) }
)
Notes

If the supplied array is empty, the function returns $zero.

If the supplied array contains a single member $m, the function returns $action($m, $zero).

If the supplied array contains two members $m and $n, the function returns $action($m, $action($n, $zero)); and similarly for an input array with more than two members.

The value of the third argument of $action corresponds to the position of the member in the input array. Thus, in contrast to array:fold-left, it is initally set to the number of members in the input array.

If the supplied array is empty, the function returns $zero.

If the supplied array contains a single member $m, the function returns $action($m, $zero).

If the supplied array contains two members $m and $n, the function returns $action($m, $action($n, $zero)); and similarly for an input array with more than two members.

The value of the third argument of $action corresponds to the position of the member in the input array. Thus, in contrast to array:fold-left, it is initally set to the number of members in the input array.

Examples
Expression:
array:fold-right(
  [ true(), true(), false() ],
  true(),
  fn($x, $y) { $x and $y }
)
Result:
false()

(Returns true if every member of the input array has an effective boolean value of true().)

Expression:
array:fold-right(
  [ true(), true(), false() ],
  false(),
  fn($x, $y) { $x or $y }
)
Result:
true()

(Returns true if at least one member of the input array has an effective boolean value of true().)

Expression:
array:fold-right(
  [ 1, 2, 3 ],
  [],
  fn($x, $y) { [ $x, $y ] }
)
Result:
[ 1, [ 2, [ 3, [] ] ] ]
Expression:
let $input := array { 11 to 21, 21 to 31 }
let $target := 21
return array:fold-right(
  $input, (),
  action := fn($curr, $result, $pos) {
    $result, if ($curr = $target) { $pos }
  }
)
Result:
12, 11

18.2.10 array:for-each-pair

Changes in 4.0  

  1. The $action callback function now accepts an optional position argument.  [Issue 516 PR 828 14 November 2023]

Summary

Returns an array obtained by evaluating the supplied function once for each pair of members at the same position in the two supplied arrays.

Signature
array:for-each-pair(
$array1as array(*),
$array2as array(*),
$actionas fn(item()*, item()*, xs:integer) as item()*
) as array(*)
Properties

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

Rules

Informally, the function applies $action to each pair of values in corresponding positions within $array1 and $array2, ignoring any excess values if one array is longer than the other. The results are then assembed into a new array whose size is equal to the shorter of the two input arrays.

Formal Equivalent

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

array:of-members(
  for $pos in 1 to min((array:size($array1), array:size($array2)))
  return map:entry('value', $action($array1($pos), $array2($pos), $pos))
)
Notes

If the arrays have different size, excess members in the longer array are ignored.

If the arrays have different size, excess members in the longer array are ignored.

Examples
Expression:
array:for-each-pair(
  [ "A", "B", "C" ],
  [ 1, 2, 3 ],
  fn($x, $y) { array { $x, $y }}
)
Result:
[ [ "A", 1 ], [ "B", 2 ], [ "C", 3 ] ]
Expression:
let $array := [ "A", "B", "C", "D" ]
return array:for-each-pair(
  $array,
  array:tail($array),
  concat#2
)
Result:
[ "AB", "BC", "CD" ]
Expression:
array:for-each-pair(
  [ 1, 8, 2 ],
  [ 3, 4, 3 ],
  fn($member1, $member2, $pos) {
    $pos || ': ' || max(($member1, $member2))
  }
)
Result:
[ "1: 3", "2: 8", "3: 3" ]

18.2.13 array:index-of

Changes in 4.0  

  1. New in 4.0  [Issues 260 1096 PRs 968 1295 6 February 2024]

Summary

Returns a sequence of positive integers giving the positions within the array $array of members that are equal to $target.

Signature
array:index-of(
$arrayas array(*),
$targetas item()*,
$collationas xs:string?:= fn:default-collation()
) as xs:integer*
Properties

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

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

Rules

Informally, all members of $array are compared with $target. An array member is compared to the target value using the rules of the fn:deep-equal function, with the specified (or defaulted) collation. The index position of the member is included in the result sequence if the comparison returns true.

The collation used by this function is determined according to the rules in 5.3.6 Choosing a collation. This collation is used when string comparison is required.

The first member in an array is at position 1, not position 0.

The result sequence is in ascending numeric order.

Formal Equivalent

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

array:index-where($array, deep-equal(?, $target, $collation))
Notes

If $array is the empty array, or if no member in $array matches $target, then the function returns the empty sequence.

If $array is the empty array, or if no member in $array matches $target, then the function returns the empty sequence.

Examples
Expression:

array:index-of([ 10, 20, 30, 30, 20, 10 ], 20)

Result:
2, 5
Expression:

array:index-of([ (), 1, (5, 6), (6, 7) ], (6, 7))

Result:
4
Expression:
array:index-of(
  [ "a", ("b", "C"), "d" ],
  ("B", "c"),
  "http://www.w3.org/2005/xpath-functions/collation/html-ascii-case-insensitive"
)
Result:
2
Expression:
array:index-of(
  [ '1', xs:untypedAtomic('1'), 1, current-date() ],
  '1'
)
Result:
1, 2

18.2.15 array:insert-before

Summary

Returns an array containing all the members of the supplied array, with one additional member at a specified position.

Signature
array:insert-before(
$arrayas array(*),
$positionas xs:integer,
$memberas item()*
) as array(*)
Properties

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

Rules

Informally, the function returns an array of size array:size($array) + 1 containing all members from $array whose position is less than $position, then a new member given by $member, and then all members from $array whose position is greater than or equal to $position. Positions are counted from 1.

Formal Equivalent

The effect of the function is equivalent to the result of the following XPath expression, except in error cases.

$array 
=> array:members() 
=> insert-before($position, map:entry('value', $member )) 
=> array:of-members()
Error Conditions

A dynamic error occurs [err:FOAY0001] if $position is not in the range 1 to array:size($array) + 1 inclusive.

Notes

Setting $position to 1 has the effect of prepending the new member at the start of the array. Setting $position to the value array:size($array) + 1 delivers the same result as array:append($array, $member).

Setting $position to 1 has the effect of prepending the new member at the start of the array. Setting $position to the value array:size($array) + 1 delivers the same result as array:append($array, $member).

Examples
ExpressionResult
array:insert-before(
  [ "a", "b", "c", "d" ],
  3,
  ("x", "y")
)
[ "a", "b", ("x", "y"), "c", "d" ]
array:insert-before(
  [ "a", "b", "c", "d" ],
  5,
  ("x", "y")
)
[ "a", "b", "c", "d", ("x", "y") ]
array:insert-before(
  [ "a", "b", "c", "d" ],
  3,
  [ "x", "y" ]
)
[ "a", "b", [ "x", "y" ], "c", "d" ]

18.2.16 array:items

Changes in 4.0  

  1. New in 4.0  [Issues 29 1086 PRs 476 1087 5 September 2023]

Summary

Returns the sequence concatenation of the members of an array.

Signature
array:items(
$arrayas array(*)
) as item()*
Properties

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

Rules

The function returns the sequence concatenationXP of the members of $array, retaining order.

Formal Equivalent

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

for-each(array:members($array), map:get(?, 'value'))
Notes

Unlike array:flatten, the function does not apply recursively to nested arrays.

If $A is a single array item, then array:items($A) returns the same result as $A?*.

Unlike array:flatten, the function does not apply recursively to nested arrays.

If $A is a single array item, then array:items($A) returns the same result as $A?*.

Examples
ExpressionResult
array:items(["one", "two", "three"])
"one", "two", "three"
array:items(["one", ("two", "three")])
"one", "two", "three"
array:items(["one", ("two", "three"), ()])
"one", "two", "three"
array:items(["one", ["two", "three"]])
"one", ["two", "three"]
array:items([ (), 1, (2 to 4), [ 5 ] ])
1, 2, 3, 4, [ 5 ]

18.2.18 array:members

Changes in 4.0  

  1. New in 4.0  [Issues 29 113 314 PRs 360 476]

Summary

Delivers the contents of an array as a sequence of value records.

Signature
array:members(
$arrayas array(*)
) as record(value as item()*)*
Properties

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

Rules

The members of the array are delivered as a sequence of value records. A value record is an item that encapsulates an arbitrary sequence $S: specifically it is a map comprising a single entry whose key is the xs:string value "value" and whose corresponding value is $S. The content encapsulated by a value record $V can be obtained using the expression $V?value.

Formal Equivalent

The function is defined as follows, making use of primitive constructors and accessors defined in [XQuery and XPath Data Model (XDM) 4.0].

dm:iterate-array($array, map:entry('value', ?))
Notes

This function is the inverse of array:of-members.

This function is the inverse of array:of-members.

Examples
Expression:

array:members([])

Result:
()
Expression:

array:members([ 1 to 5 ])?value

Result:
1, 2, 3, 4, 5
Expression:
array:members([ (1, 1), (2, 4), (3, 9), (4, 16), (5, 25) ])
! sum(?value)
Result:
2, 6, 12, 20, 30
Expression:
let $array := [ "any array" ]
return deep-equal(
  $array,
  array:of-members(array:members($array))
)
Result:
true()

18.2.19 array:of-members

Changes in 4.0  

  1. New in 4.0  [Issues 29 113 314 PRs 360 476]

Summary

Constructs an array from the contents of a sequence of value records.

Signature
array:of-members(
$inputas record(value as item()*)*
) as array(*)
Properties

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

Rules

The input items must be value records, as defined in the type signature. A value record is an item that encapsulates an arbitrary sequence $S: specifically it is a map comprising a single entry whose key is the xs:string value "value" and whose corresponding value is $S. The content encapsulated by a value record $V can be obtained using the expression $V?value.

Formal Equivalent

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

fold-left($input, [], fn($array, $record) { 
  array:append($array, map:get($record, 'value'))
})
Notes

This function is the inverse of array:members.

This function is the inverse of array:members.

Examples
ExpressionResult
array:of-members(())
[]
array:of-members({ 'value': (1 to 5) })
[ (1, 2, 3, 4, 5) ]
array:of-members((1 to 5) ! { 'value': . })
[ 1, 2, 3, 4, 5 ]
array:of-members((1 to 3) ! { 'value': (., . * .) })
[ (1, 1), (2, 4), (3, 9) ]

18.2.24 array:size

Summary

Returns the number of members in the supplied array.

Signature
array:size(
$arrayas array(*)
) as xs:integer
Properties

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

Rules

The function returns the number of members in the array.

Formal Equivalent

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

count(array:members($array))
Notes

Note that because an array is an item, the fn:count function when applied to an array always returns 1.

Note that because an array is an item, the fn:count function when applied to an array always returns 1.

Examples
ExpressionResult
array:size([ "a", "b", "c" ])
3
array:size([ "a", [ "b", "c" ] ])
2
array:size([])
0
array:size([ [] ])
1

18.2.25 array:slice

Changes in 4.0  

  1. New in 4.0

Summary

Returns an array containing selected members of a supplied input array based on their position.

Signature
array:slice(
$arrayas array(*),
$startas xs:integer?:= (),
$endas xs:integer?:= (),
$stepas xs:integer?:= ()
) as array(*)
Properties

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

Rules

Informally, the array is converted to a sequence, the function fn:slice is applied to this sequence, and the resulting sequence is converted back to an array.

Formal Equivalent

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

$array 
=> array:members() 
=> slice($start, $end, $step) 
=> array:of-members()
Notes

Note that unlike other operations on arrays, there are no out-of-bounds errors for inappropriate values of $start, $end, or $step.

Note that unlike other operations on arrays, there are no out-of-bounds errors for inappropriate values of $start, $end, or $step.

Examples
Variables
let $in := [ 'a', 'b', 'c', 'd', 'e' ]
ExpressionResult
array:slice($in, start := 2, end := 4)
[ "b", "c", "d" ]
array:slice($in, start := 2)
[ "b", "c", "d", "e" ]
array:slice($in, end := 2)
[ "a", "b" ]
array:slice($in, start := 3, end := 3)
[ "c" ]
array:slice($in, start := 4, end := 3)
[ "d", "c" ]
array:slice($in, start := 2, end := 5, step := 2)
[ "b", "d" ]
array:slice($in, start := 5, end := 2, step := -2)
[ "e", "c" ]
array:slice($in, start := 2, end := 5, step := -2)
[]
array:slice($in, start := 5, end := 2, step := 2)
[]
array:slice($in)
[ "a", "b", "c", "d", "e" ]
array:slice($in, start := -1)
[ "e" ]
array:slice($in, start := -3)
[ "c", "d", "e" ]
array:slice($in, end := -2)
[ "a", "b", "c", "d" ]
array:slice($in, start := 2, end := -2)
[ "b", "c", "d" ]
array:slice($in, start := -2, end := 2)
[ "d", "c", "b" ]
array:slice($in, start := -4, end := -2)
[ "b", "c", "d" ]
array:slice($in, start := -2, end := -4)
[ "d", "c", "b" ]
array:slice($in, start := -4, end := -2, step := 2)
[ "b", "d" ]
array:slice($in, start := -2, end := -4, step := -2)
[ "d", "b" ]
array:slice([ "a", "b", "c", "d" ], 0)
[ "a", "b", "c", "d" ]

18.2.27 array:split

Changes in 4.0  

  1. New in 4.0

Summary

Delivers the contents of an array as a sequence of singleton arrays.

Signature
array:split(
$arrayas array(*)
) as array(*)*
Properties

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

Rules

The members of the array are delivered as a sequence of arrays. Each returned array encapsulates the value of a single array member.

Formal Equivalent

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

array:for-each($array, fn($member) { [] => array:append($member) })
=> array:items()
Notes

The function call array:split($array) produces the same result as the expression for member $m in $array return [ $m ].

This function is the inverse of array:join.

The function call array:split($array) produces the same result as the expression for member $m in $array return [ $m ].

This function is the inverse of array:join.

Examples
Expression:

array:split([])

Result:
()
Expression:

array:split([ () ])

Result:
[ () ]
Expression:

array:split([ 1 to 5 ])

Result:
[ (1, 2, 3, 4, 5) ]
Expression:
array:split(
  array { 1 to 5 }
)
Result:
[ 1 ], [ 2 ], [ 3 ], [ 4 ], [ 5 ]
Expression:
array:split(
  [ (1, 1), (2, 4), (3, 9), (4, 16), (5, 25) ]
) ! sum(.)
Result:
2, 6, 12, 20, 30
Expression:
let $array := [ "any array" ]
return deep-equal(
  $array,
  array:join(array:split($array))
)
Result:
true()

18.2.28 array:subarray

Changes in 4.0  

  1. Supplying an empty sequence as the value of an optional argument is equivalent to omitting the argument.

Summary

Returns an array containing all members from a supplied array starting at a supplied position, up to a specified length.

Signature
array:subarray(
$arrayas array(*),
$startas xs:integer,
$lengthas xs:integer?:= ()
) as array(*)
Properties

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

Rules

Except in error cases, the two-argument version of the function returns the same result as the three-argument version when called with $length equal to the value of array:size($array) - $start + 1.

Setting the third argument to the empty sequence has the same effect as omitting the argument.

Formal Equivalent

The effect of the function is equivalent to the result of the following XPath expression, except in error cases.

$array
=> array:members()
=> subsequence($start, $length)
=> array:of-members()
Error Conditions

A dynamic error is raised [err:FOAY0001] if $start is less than one or greater than array:size($array) + 1.

For the three-argument version of the function:

  • A dynamic error is raised [err:FOAY0002] if $length is less than zero.

  • A dynamic error is raised [err:FOAY0001] if $start + $length is greater than array:size($array) + 1.

Notes

The value of $start can be equal to array:size($array) + 1 provided that $length is either equal to zero or omitted. In this case the result will be an empty array.

The value of $start can be equal to array:size($array) + 1 provided that $length is either equal to zero or omitted. In this case the result will be an empty array.

Examples
ExpressionResult
array:subarray([ "a", "b", "c", "d" ], 2)
[ "b", "c", "d" ]
array:subarray([ "a", "b", "c", "d" ], 5)
[]
array:subarray([ "a", "b", "c", "d" ], 2, 0)
[]
array:subarray([ "a", "b", "c", "d" ], 2, 1)
[ "b" ]
array:subarray([ "a", "b", "c", "d" ], 2, 2)
[ "b", "c" ]
array:subarray([ "a", "b", "c", "d" ], 5, 0)
[]
array:subarray([], 1, 0)
[]

18.2.29 array:tail

Summary

Returns an array containing all members except the first from a supplied array.

Signature
array:tail(
$arrayas array(*)
) as array(*)
Properties

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

Rules

The function returns an array containing all members of the supplied array except the first.

Formal Equivalent

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

array:remove($array, 1)
Error Conditions

A dynamic error occurs [err:FOAY0001] if $array is empty.

Notes

If the supplied array contains exactly one member, the result will be an empty array.

If the supplied array contains exactly one member, the result will be an empty array.

Examples
ExpressionResult
array:tail([ 5, 6, 7, 8 ])
[ 6, 7, 8 ]
array:tail([ 5 ])
[]

18.2.30 array:trunk

Changes in 4.0  

  1. New in 4.0  [Issue 97 PR 250]

Summary

Returns an array containing all members except the last from a supplied array.

Signature
array:trunk(
$arrayas array(*)
) as array(*)
Properties

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

Rules

The function returns an array containing all members of the supplied array except the last.

Formal Equivalent

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

array:remove($array, array:size($array))
Error Conditions

A dynamic error occurs [err:FOAY0001] if $array is empty.

Notes

If the supplied array contains exactly one member, the result will be an empty array.

If the supplied array contains exactly one member, the result will be an empty array.

Examples
ExpressionResult
array:trunk([ 5, 6, 7, 8 ])
[ 5, 6, 7 ]
array:trunk([ 5 ])
[]

19 Functions on types

Changes in 4.0  

  1. New functions are provided to obtain information about built-in types and types defined in an imported schema.   [Issue 148 ]

The functions in this section deliver information about schema types (including simple types and complex types). These may represent built-in types (such as xs:dateTime), user-defined types found in the static context (typically because they appear in an imported schema), or types used as type annotations on schema-validated nodes.

For more information on schema types, see 1.8.2 Schema Type Hierarchy. The properties of a schema type are described in terms of the properties of a Simple Type Definition or Complex Type Definition component as described in Section 3.16.1 The Simple Type Definition Schema Component XS11-1 and Section 3.4.1 The Complex Type Definition Schema Component XS11-1 respectively. Not all properties are exposed.

The structured representation of a schema type is described in 19.1.1 Record fn:schema-type-record.

Note:

Simple properties of a schema type that can be expressed as strings or booleans are represented in this record structure directly as atomic field values, while complex properties whose values are themselves types (for example, base-type and primitive-type) are represented as functions. This is done partly to make it easier for implementations to compute complex properties on demand rather than in advance, and partly to ensure that the overall structure is always acyclic. For example, the primitive type of xs:decimal is itself xs:decimal, and if this were represented as a field value without a guarding function, serialization of the map using the JSON output method would not terminate.

19.1 Functions returning type information

FunctionMeaning
fn:schema-typeReturns a record containing information about a named schema type in the static context.
fn:type-ofReturns information about the type of a value, as a string.
fn:atomic-type-annotationReturns a record containing information about the type annotation of an atomic value.
fn:node-type-annotationReturns a record containing information about the type annotation of an element or attribute node.

19.1.3 fn:type-of

Changes in 4.0  

  1. New in 4.0  [Issue 1550 PR 1570 12 November 2024]

Summary

Returns information about the type of a value, as a string.

Signature
fn:type-of(
$valueas item()*
) as xs:string
Properties

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

Rules

The function returns a string, whose lexical form will always match the grammar of SequenceTypeXP, representing a sequence type that matches $value.

If $value is the empty sequence, the function returns the string "empty-sequence()".

Otherwise, the returned string is the concatenation of:

  1. A string representing the distinct item types that are present in $value, formed as follows:

    1. For each item in $value, construct a string representing its item type as described below.

    2. Eliminate duplicate strings from this list by applying the fn:distinct-values function, forming a sequence of strings $ss.

    3. If $ss contains only one string, use that string.

    4. Otherwise, return the result of the expression `({fn:string-join($ss, "|")})`.

  2. An occurrence indicator: absent if $value contains exactly one item, or "+" if it contains more than one item.

The string representing the type of an individual item J is constructed as follows:

  1. If J is a node, the result is one of the following strings, determined by the node kind of the node (see Section 4.9 node-kind AccessorDM):

    "document-node()"
    "element()"
    "attribute()"
    "text()"
    "processing-instruction()"
    "comment()"
    "namespace-node()"

  2. If J is an atomic item, the result is a string chosen as follows:

    1. Let T be the type denoted by the type annotation of J.

    2. If T is an anonymous type, set T to the base type of T, and repeat until a type is reached that is not anonymous.

    3. If the name of T is in the namespace http://www.w3.org/2001/XMLSchema, return the string "xs:local" where local is the local part of the name of T.

    4. Otherwise, return the name of T in the form of a URIQualifiedNameXP (that is, "Q{uri}local", or "Q{}local" if the name is in no namespace).

  3. If J is a function item:

    1. If J is an array, return "array(*)".

    2. If J is a map, return "map(*)".

    3. Otherwise, return "function(*)".

Error Conditions

If the $value argument is omitted and the context value is absentDM, the function raises type error [err:XPDY0002]XP.

Notes

In general, an item matches more than one type, and there are cases where there is no single matching type that is more specific than all the others. This is especially true with functions, maps, and arrays. This function therefore selects one of the types that matches the item, which is not necessarily the most specific type.

This function should not be used as a substitute for an instance of test. The precise type annotation of the result of an expression is not always predictable, because processors are free to deliver a more specific type than is mandated by the specification. For example, if $n is of type xs:positiveInteger, then the result of abs($n) is guaranteed to be an instance of xs:integer, but an implementation might reasonably return the supplied value unchanged: that is, a value whose actual type annotation is xs:positiveInteger. Similarly the type annotation of the value returned by position() might be xs:long rather than xs:integer.

Implementations should, however, refrain from exposing types that are purely internal. For example, an implementation might have an optimized internal representation for strings consisting entirely of ASCII characters, or for single-character strings; if this is the case then the type annotation returned by this function should be a user-visible supertype such as xs:string.

In general, an item matches more than one type, and there are cases where there is no single matching type that is more specific than all the others. This is especially true with functions, maps, and arrays. This function therefore selects one of the types that matches the item, which is not necessarily the most specific type.

This function should not be used as a substitute for an instance of test. The precise type annotation of the result of an expression is not always predictable, because processors are free to deliver a more specific type than is mandated by the specification. For example, if $n is of type xs:positiveInteger, then the result of abs($n) is guaranteed to be an instance of xs:integer, but an implementation might reasonably return the supplied value unchanged: that is, a value whose actual type annotation is xs:positiveInteger. Similarly the type annotation of the value returned by position() might be xs:long rather than xs:integer.

Implementations should, however, refrain from exposing types that are purely internal. For example, an implementation might have an optimized internal representation for strings consisting entirely of ASCII characters, or for single-character strings; if this is the case then the type annotation returned by this function should be a user-visible supertype such as xs:string.

Examples
Variables
let $e := <doc>
  <p id="alpha" xml:id="beta">One</p>
  <p id="gamma" xmlns="http://example.com/ns">Two</p>
  <ex:p id="delta" xmlns:ex="http://example.com/ns">Three</ex:p>
  <?pi 3.14159?>
</doc>
ExpressionResult
type-of($e//*[@id = 'alpha'])
"element()"
type-of($e//*)
"element()+"
type-of($e//@id[. = 'gamma'])
"attribute()"
type-of($e//node()[.='3.14159'])
"processing-instruction()"
type-of($e//no-such-node)
"empty-sequence()"
type-of($e/child::node())
"(element()|processing-instruction())+"
type-of(1)
"xs:integer"
type-of(1 to 5)
"xs:integer+"
type-of((1, 1.2, 2))
"(xs:integer|xs:decimal)+"
type-of([1, 2, 3])
"array(*)"
type-of({ 'a':1 })
"map(*)"
type-of(type-of#1)
"function(*)"

19.1.4 fn:atomic-type-annotation

Changes in 4.0  

  1. New in 4.0  [Issue 148 PR 1523 22 October 2024]

Summary

Returns a record containing information about the type annotation of an atomic value.

Signature
fn:atomic-type-annotation(
$valueas xs:anyAtomicType
) as schema-type-record
Properties

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

Rules

Given an atomic value, the function returns a schema-type-record containing information about the atomic type represented by its type annotationDM.

Notes

The result will always have ?is-simple = true() and ?variety = "atomic". In a non-schema-aware environment the type will always be a built-in atomic type in the xs namespace: see 1.8.3 Atomic Type Hierarchy. Where a schema is in use, however, the result may be an atomic type defined in the schema, which may be an anonymous type.

Note that under the function coercion rules, it is possible to supply a node as the argument, which will then be atomized. In simple cases the type annotation on the atomized value will be the same as the type annotation on the node. But this is not always true: for example the type annotation on the node might be a complex type with simple content, while the type annotation on its atomized value is the corresponding simple content type. To get the type annotation on the node, use the function fn:node-type-annotation.

This function should not be used as a substitute for an instance of test. The precise type annotation of the result of an expression is not always predictable, because processors are free to deliver a more specific type than is mandated by the specification. For example, if $n is of type xs:positiveInteger, then the result of abs($n) is guaranteed to be an instance of xs:integer, but an implementation might reasonably return the supplied value unchanged: that is, a value whose actual type annotation is xs:positiveInteger. Similarly the type annotation of the value returned by position() might be xs:long rather than xs:integer.

Implementations should, however, refrain from exposing types that are purely internal. For example, an implementation might have an optimized internal representation for strings consisting entirely of ASCII characters, or for single-character strings; if this is the case then the type annotation returned by this function should be a user-visible supertype such as xs:string.

The result will always have ?is-simple = true() and ?variety = "atomic". In a non-schema-aware environment the type will always be a built-in atomic type in the xs namespace: see 1.8.3 Atomic Type Hierarchy. Where a schema is in use, however, the result may be an atomic type defined in the schema, which may be an anonymous type.

Note that under the function coercion rules, it is possible to supply a node as the argument, which will then be atomized. In simple cases the type annotation on the atomized value will be the same as the type annotation on the node. But this is not always true: for example the type annotation on the node might be a complex type with simple content, while the type annotation on its atomized value is the corresponding simple content type. To get the type annotation on the node, use the function fn:node-type-annotation.

This function should not be used as a substitute for an instance of test. The precise type annotation of the result of an expression is not always predictable, because processors are free to deliver a more specific type than is mandated by the specification. For example, if $n is of type xs:positiveInteger, then the result of abs($n) is guaranteed to be an instance of xs:integer, but an implementation might reasonably return the supplied value unchanged: that is, a value whose actual type annotation is xs:positiveInteger. Similarly the type annotation of the value returned by position() might be xs:long rather than xs:integer.

Implementations should, however, refrain from exposing types that are purely internal. For example, an implementation might have an optimized internal representation for strings consisting entirely of ASCII characters, or for single-character strings; if this is the case then the type annotation returned by this function should be a user-visible supertype such as xs:string.

Examples
Expression:
atomic-type-annotation(23) ? name
Result:
xs:QName('xs:integer')
Expression:
let $x := 23, $y := 93.7 
return atomic-type-annotation($x) ? matches($y)
Result:
false()
Expression:
atomic-type-annotation(xs:numeric('23.2')) ? name
Result:
xs:QName('xs:double')

19.1.5 fn:node-type-annotation

Changes in 4.0  

  1. New in 4.0  [Issue 148 PR 1523 22 October 2024]

Summary

Returns a record containing information about the type annotation of an element or attribute node.

Signature
fn:node-type-annotation(
$nodeas (element() | attribute())
) as schema-type-record
Properties

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

Rules

Given an element or attribute node, the function returns a schema-type-record containing information about the schema type represented by its type annotationDM.

Notes

For an element that has not been schema-validated, the type annotation is always xs:untyped.

For an attribute that has not been schema-validated, the type annotation is always xs:untypedAtomic.

The type annotation of an attribute node is always a simple type; the type annotation of an element node may be simple or complex.

For an element that has not been schema-validated, the type annotation is always xs:untyped.

For an attribute that has not been schema-validated, the type annotation is always xs:untypedAtomic.

The type annotation of an attribute node is always a simple type; the type annotation of an element node may be simple or complex.

Examples
Expression:
let $e := parse-xml("<e/>")/*
return node-type-annotation($e) ? name
Result:
xs:QName('xs:untyped')
Expression:
let $a := parse-xml("<e a='3'/>")//@a
return node-type-annotation($a) ? name
Result:
xs:QName('xs:untypedAtomic')
Expression:
let $x := json-to-xml('[23, 24]', { 'validate': true() })
return node-type-annotation($x/*) ? name
Result:
xs:QName('fn:arrayType')
Expression:
let $x := json-to-xml('[23, 24]', { 'validate': true() })
let $n23 := $x//fn:number[. = 23]                  
let $type := node-type-annotation($n23)
return ($type ? name, 
        $type ? base-type() ? name, 
        $type ? base-type() ? base-type() ? name)
Result:
xs:QName('fn:numberType'), 
xs:QName('fn:finiteNumberType'), 
xs:QName('xs:double')