Appendix A. Built-in Function Reference

This appendix describes the functions that are built into XQuery. Table A-1 lists all the built-in functions by subject for easy reference. In addition to a brief sentence explaining the purpose of the function, each function is described by the following characteristics:

  • “Signature” lists the parameters and their types, and the return type of the function.

  • “Usage Notes” covers the function in more detail.

  • “Special Cases” lists error conditions and other unusual situations.

  • “Example(s)” provides one or more example function calls with their return values.

  • “Related Functions” lists names of related functions.

Most of the built-in functions are in the XPath Functions Namespace, http://www.w3.org/2005/xpath-functions. These do not need to be prefixed when called in a query, so they are listed in this appendix without a prefix. Some people prefer to use the prefix fn with these functions, which works because the XPath Functions namespace is predeclared with the prefix fn.

Other functions in this appendix are shown with the prefixes math, array, and map. These three namespace prefixes are not predeclared. To use functions in these namespaces, declare the namespaces in your query prolog, for example:

declare namespace math = "http://www.w3.org/2005/xpath-functions/math";
declare namespace array = "http://www.w3.org/2005/xpath-functions/array";
declare namespace map = "http://www.w3.org/2005/xpath-functions/map";

Many of the built-in functions have more than one signature. For example, adjust-date-to-timezone has a signature with just $arg, and another with two arguments—$arg and $timezone:

adjust-date-to-timezone($arg as xs:date?) as xs:date?
adjust-date-to-timezone($arg as xs:date?,
                        $timezone as xs:dayTimeDuration?) as xs:date?

For simplicity, this appendix only shows one signature for each function name, with the “required” arguments in constant width bold, and the “optional” ones in constant width italic. For example:

adjust-date-to-timezone($arg as xs:date?,
                        $timezone as xs:dayTimeDuration?) as xs:date?

This convention indicates that the function can be called with or without the $timezone argument. Don’t forget that passing the empty sequence or a zero-length string for an argument is not the same as omitting an argument.

It is possible to use this convention because the built-in functions (listed in Table A-1) have been designed so that in cases where there are several versions of a function with different numbers of arguments, the common arguments have the same type and meaning in each case. User-defined functions don’t have to follow this design pattern, but it’s good practice.

Table A-1. Function finder
Numeric functions (general)
abs, avg, ceiling, floor, format-integer, format-number, max, min, number, random-number-generator, round, round-half-to-even, sum
Numeric functions (trigonometric and exponential)
math:acos, math:asin, math:atan, math:atan2, math:cos, math:exp, math:exp10, math:log, math:log10, math:pi, math:pow, math:sin, math:sqrt, math:tan
String functions
analyze-string, codepoint-equal, codepoints-to-string, collation-key, compare, concat, contains, contains-token, default-collation, default-language, ends-with, lang, lower-case, matches, normalize-space, normalize-unicode, replace, starts-with, string-join, string-length, string-to-codepoints, substring, substring-after, substring-before, tokenize, translate, upper-case
Date functions (general)
adjust-date-to-timezone, adjust-dateTime-to-timezone, adjust-time-to-timezone, current-date, current-dateTime, current-time, dateTime, format-date, format-dateTime, format-time, implicit-timezone, parse-ietf-date
Date functions (component extraction)
day-from-date, day-from-dateTime, days-from-duration, hours-from-dateTime, hours-from-duration, hours-from-time, minutes-from-dateTime, minutes-from-duration, minutes-from-time, month-from-date, month-from-dateTime, months-from-duration, seconds-from-dateTime, seconds-from-duration, seconds-from-time, timezone-from-date, timezone-from-dateTime, timezone-from-time, year-from-date, year-from-dateTime, years-from-duration
Boolean functions
boolean, false, not, true
Document and URI functions
base-uri, collection, doc, doc-available, document-uri, encode-for-uri, escape-html-uri, iri-to-uri, json-doc, json-to-xml, parse-json, parse-xml, parse-xml-fragment, resolve-uri, root, serialize, static-base-uri, unparsed-text, unparsed-text-available, unparsed-text-lines, uri-collection, xml-to-json
Name and namespace functions
in-scope-prefixes, local-name, local-name-from-QName, name, namespace-uri, namespace-uri-for-prefix, namespace-uri-from-QName, node-name, prefix-from-QName, QName, resolve-QName
Node-related functions
data, deep-equal, element-with-id, empty, exists, generate-id, has-children, id, idref, innermost, nilled, outermost, path, string
Sequence-related functions
count, distinct-values, head, index-of, insert-before, last, position, remove, reverse, sort, subsequence, tail, unordered
Higher-order functions
apply, filter, fold-left, fold-right, for-each, for-each-pair, function-arity, function-lookup, function-name
Array functions
array:append, array:filter, array:flatten, array:fold-left, array:fold-right, array:for-each, array:for-each-pair, array:get, array:head, array:insert-before, array:join, array:put, array:remove, array:reverse, array:size, array:sort, array:subarray, array:tail
Map functions
map:contains, map:entry, map:find, map:for-each, map:get, map:keys, map:merge, map:put, map:remove, map:size
Processing and error handling functions
available-environment-variables, environment-variable, error, exactly-one, load-xquery-module, one-or-more, trace, transform, zero-or-one

abs

Finds the absolute value of a number

Signature
abs($arg as xs:numeric?) as xs:numeric?
Usage Notes

This function accepts any numeric value and returns its absolute value. It returns a numeric value whose type depends on the type of the argument. If $arg is untyped, it is cast to xs:double.

Special Cases
  • If $arg is the empty sequence, the function returns the empty sequence.

  • If $arg is INF or -INF, the function returns INF.

  • If $arg is NaN, the function returns NaN.

Examples
ExampleReturn value
abs(3.5) 3.5
abs(-4) 4
abs(xs:float("-INF")) INF

math:acos

Returns the arc cosine of the argument

Signature
math:acos($arg as xs:double?) as xs:double?
Usage Notes

This function returns the arc cosine of $arg. The result is an angle in radians, in the range zero to +π, inclusive.

Special Cases
  • If $arg is the empty sequence, the function returns the empty sequence.

  • If the absolute value of $arg is greater than one or NaN, the function returns NaN.

  • This function is new in XQuery 3.0.

Examples
ExampleReturn value
math:acos(0) 1.570796326794 (approximately)
math:acos(-1.0e0) 3.14159265 (approximately)
math:acos(2) NaN
math:acos( () ) ()

adjust-date-to-timezone

Adjusts the time zone of a date

Signature
adjust-date-to-timezone($arg as xs:date?,
                        $timezone as xs:dayTimeDuration?) as xs:date?
Usage Notes

The behavior of this function depends on whether $arg already has a time zone and on the value of the time zone provided. Table A-2 shows the possible combinations.

Table A-2. Behavior of the adjust-xxx-to-timezone functions
Does $arg have a time zone?Value of $timezoneExplanation of result
NoAn xs:dayTimeDuration$arg, now associated with the time zone $timezone (but has the same date)
YesAn xs:dayTimeDuration$arg, adjusted to the time zone $timezone
NoThe empty sequence$arg, unchanged
YesThe empty sequence$arg with no associated time zone (but has the same date)
NoNot provided$arg, now associated with the implicit time zone (but has the same date)
YesNot provided$arg, adjusted to the implicit time zone

The $timezone is expressed as an xs:dayTimeDuration, for example, -PT5H for US Eastern Standard Time. If $timezone is the empty sequence, it is assumed that the desired result is a date value that is in no time zone. If $timezone is omitted from the function call (as opposed to being the empty sequence) it is assumed to be the implicit time zone.

The $arg date is assumed for the sake of time zone calculation to be just like an xs:dateTime value whose time is midnight (00:00:00). If $arg does not already have a time zone, its date part stays the same, but it is now associated with the specified time zone.

If $arg already has a time zone, the value is adjusted to that time zone. This may change the actual date in some cases. For example, if $arg is 2015-02-15-05:00, and $timezone is -PT8H, the resulting date is 2015-02-14-08:00, which is the day before. This is because $arg is considered to be 2015-02-15T00:00:00-05:00, which is equivalent to 2015-02-14T21:00:00-08:00. In other words, midnight in the U.S. Eastern time zone is equal to 9 P.M. the day before in the U.S. Pacific time zone.

For more information on time zones in XQuery, see “Time Zones”.

Special Cases
  • If $arg is the empty sequence, the function returns the empty sequence.

  • If the value of $timezone is not between -PT14H and PT14H, inclusive, or if it does not have an integral number of minutes (i.e., the number of seconds is not 0), error FODT0003 is raised.

Examples

These six examples represent the six scenarios described in Table A-2. They assume an implicit time zone of -05:00.

ExampleReturn value
adjust-date-to-timezone(xs:date("2015-02-15"), xs:dayTimeDuration("-PT8H")) 2015-02-15-08:00
adjust-date-to-timezone(xs:date("2015-02-15-03:00"), xs:dayTimeDuration("-PT8H")) 2015-02-14-08:00
adjust-date-to-timezone(xs:date("2015-02-15"), ()) 2015-02-15
adjust-date-to-timezone(xs:date("2015-02-15-03:00"), ()) 2015-02-15
adjust-date-to-timezone(xs:date("2015-02-15")) 2015-02-15-05:00
adjust-date-to-timezone(xs:date("2015-02-15-03:00")) 2015-02-14-05:00

adjust-dateTime-to-timezone

Adjusts the time zone of a date/time

Signature
adjust-dateTime-to-timezone($arg as xs:dateTime?,
                            $timezone as xs:dayTimeDuration?) as xs:dateTime?
Usage Notes

The behavior of this function is identical to that of adjust-date-to-timezone, described in Table A-2, except that the actual time, not midnight, is used.

Special Cases
  • If $arg is the empty sequence, the function returns the empty sequence.

  • If the value of $timezone is not between -PT14H and PT14H, inclusive, or if it does not have an integral number of minutes (i.e., the number of seconds is not 0), error FODT0003 is raised.

Examples

These examples represent the scenarios described in Table A-2. They assume an implicit time zone of -05:00.

ExampleReturn value
adjust-dateTime-to-timezone(
xs:dateTime("2015-02-15T17:00:00"),
xs:dayTimeDuration("-PT7H"))
2015-02-15T17:00:00-07:00
adjust-dateTime-to-timezone(
xs:dateTime("2015-02-15T17:00:00-03:00"),
xs:dayTimeDuration("-PT7H"))
2015-02-15T13:00:00-07:00
adjust-dateTime-to-timezone(
xs:dateTime("2015-02-15T17:00:00"), () )
2015-02-15T17:00:00
adjust-dateTime-to-timezone(
xs:dateTime("2015-02-15T17:00:00-03:00"), () )
2015-02-15T17:00:00
adjust-dateTime-to-timezone(
xs:dateTime("2015-02-15T17:00:00"))
2015-02-15T17:00:00-05:00
adjust-dateTime-to-timezone(
xs:dateTime("2015-02-15T17:00:00-03:00"))
2015-02-15T15:00:00-05:00
adjust-dateTime-to-timezone(
xs:dateTime("2015-02-15T01:00:00-03:00"),
xs:dayTimeDuration("-PT7H"))
2015-02-14T21:00:00-07:00

adjust-time-to-timezone

Adjusts the time zone of a time

Signature
adjust-time-to-timezone($arg as xs:time?,
                        $timezone as xs:dayTimeDuration?) as xs:time?
Usage Notes

The behavior of this function is identical to that of adjust-date-to-timezone, described in Table A-2, except that the actual time, not midnight, is used.

Special Cases
  • If $arg is the empty sequence, the function returns the empty sequence.

  • If the value of $timezone is not between -PT14H and PT14H, inclusive, or if it does not have an integral number of minutes (i.e., the number of seconds is not 0), error FODT0003 is raised.

Examples

The first six examples represent the six scenarios described in Table A-2. They assume an implicit time zone of -05:00.

ExampleReturn value
adjust-time-to-timezone(xs:time("17:00:00"),
xs:dayTimeDuration("-PT7H"))
17:00:00-07:00
adjust-time-to-timezone(xs:time("17:00:00-03:00"),
xs:dayTimeDuration("-PT7H"))
13:00:00-07:00
adjust-time-to-timezone(xs:time("17:00:00"), () ) 17:00:00
adjust-time-to-timezone(xs:time("17:00:00-03:00"), () ) 17:00:00
adjust-time-to-timezone(xs:time("17:00:00")) 17:00:00-05:00
adjust-time-to-timezone(xs:time("17:00:00-03:00")) 15:00:00-05:00
adjust-time-to-timezone(xs:time("22:00:00-08:00")) 01:00:00-05:00
adjust-time-to-timezone(xs:time("01:00:00-02:00")) 22:00:00-05:00
adjust-time-to-timezone(xs:time("17:00:00"),
xs:dayTimeDuration("-PT20H"))
Error FODT0003

analyze-string

Splits a string into parts that match and do not match a regular expression

Signature
analyze-string($input as xs:string?, $pattern as xs:string, 
               $flags as xs:string) as element(fn:analyze-string-result)
Usage Notes

This function captures parts of a string $input that do and do not match a regular expression $pattern. The result is an XML element named fn:analyze-string-result that contains elements called fn:match for each part of a string that matches the regular expression, and fn:non-match for each part that does not match.

This function is useful if you need to keep both the matching and non-matching parts of a string. If you want to discard the matching parts (e.g., because they represent a delimiter), it is simpler to use the tokenize function instead.

The fn:match element can contain fn:group elements in the case that parentheses are used in the regular expression. This allows you to query which parts of the matching string matched specific parts of the regular expression. fn:group elements can themselves contain other fn:group elements, in the case where there are parentheses within parentheses in the regular expression. Each fn:group has an nr attribute that indicates which group it is, based on its starting position in the regular expression, starting with 1. The fn:non-match, on the other hand, will always contain only text with no child elements.

The $flags parameter allows for additional options in the interpretation of the regular expression. It is discussed in detail in “Using Flags”.

Special Cases
  • If $pattern is not a valid regular expression, error FORX0002 is raised.

  • If $flags contains unsupported options, error FORX0001 is raised.

  • If the entire $pattern matches a zero-length string, for example, q?, error FORX0003 is raised.

  • If $input is the empty sequence or a zero-length string, the function returns an empty fn:analyze-string-result element.

  • This function is new in XQuery 3.0.

Examples

Indentation is added to the example results for clarity. In reality, the whitespace would not be included.

ExampleReturn value
analyze-string('abc123def', 'd+') <fn:analyze-string-result> <fn:non-match>abc</fn:non-match> <fn:match>123</fn:match> <fn:non-match>def</fn:non-match> </fn:analyze-string-result>
analyze-string('abc123def', 'd') <fn:analyze-string-result> <fn:non-match>abc</fn:non-match> <fn:match>1</fn:match> <fn:match>2</fn:match> <fn:match>3</fn:match> <fn:non-match>def</fn:non-match> </fn:analyze-string-result>
analyze-string("2015-04-03", "^(d+)-(d+)-(d+)$") <fn:analyze-string-result> <fn:match><fn:group nr="1">2015</fn:group>-<fn:group nr="2">04</fn:group>-<fn:group nr="3">03</fn:group></fn:match> </fn:analyze-string-result>
Related Functions

tokenize, matches

array:append

Appends a member to an array

Signature
array:append($array as array(*), $appendage as item()*) as array(*)
Usage Notes

This function returns a new array with all the members of $array, plus an additional member at the end whose value is $appendage. If $appendage is a sequence of multiple items, each item does not become a member, but rather a single member is added whose value is the sequence of all the items in $appendage.

Special Cases
  • If $appendage is an array, the entire array becomes a single member of the outer array; the two arrays are not merged. The array:join function can be used to merge two arrays.

  • If $appendage is the empty sequence, a member is still added to the array, whose value is the empty sequence.

  • This function is new in XQuery 3.1.

Examples

The examples assume this variable declaration:

declare variable $array1 := ["abc", "def", "ghi"];
ExampleReturn value
array:append($array1, "jkl") ["abc", "def", "ghi", "jkl"]
array:append($array1, ("jkl", "mno") ) ["abc", "def", "ghi", ("jkl", "mno")]
array:append(array:append($array1, "jkl"), "mno") ["abc", "def", "ghi", "jkl", "mno"]
array:append($array1, ["jkl", "mno"]) ["abc", "def", "ghi", ["jkl", "mno"]]
array:append($array1, () ) ["abc", "def", "ghi", ()]

apply

Calls a supplied function by using an argument list

Signature
apply($function as function(*), $array as array(*)) as item()*
Usage Notes

This function calls the function $function, using the members of the $array as arguments, in order. Calling the apply function is the same as making a dynamic function call. For example:

let $f := upper-case#1
return apply($f, ["a"])

is equivalent to:

let $f := upper-case#1
return $f("a")

Therefore, this function is most useful for dynamic programming, when the arity of the function is not known in advance.

Special Cases
  • If the arity of the function in $function is not the same as the size of the array $array, error FOAP0001 is raised.

  • This function is new in XQuery 3.1, and only supported by implementations that support higher-order functions. If the function is called by a 3.1 processor but is not supported, error XPST0017 is raised.

Examples
ExampleReturn value
apply(substring#3, ["sometext", 2, 4]) omet
apply(max#1, [(1, 2, 3)]) 3
apply(concat#3, ["a", "b", "c"]) abc
apply(upper-case#1, ['a', 'b']) Error FOAP0001

math:asin

Returns the arc sine

Signature
math:asin($arg as xs:double?) as xs:double?
Usage Notes

This function returns the arc sine of $arg. The result is an angle in radians, in the range -π/2 to +π/2, inclusive.

Special Cases
  • If $arg is the empty sequence, the function returns the empty sequence.

  • If $arg is zero (positive or negative), the function returns $arg.

  • If $arg is NaN, or if its absolute value is greater than one, the function returns NaN.

  • This function is new in XQuery 3.0.

Examples
ExampleReturn value
math:asin(0) 0
math:asin(-0) -0
math:asin(1.0) 1.570796326 (approximately)
math:asin(2) NaN

math:atan

Returns the arc tangent

Signature
math:atan($arg as xs:double?) as xs:double?
Usage Notes

This function returns the arc tangent of $arg. The result is an angle in radians, is in the range -π/2 to +π/2, inclusive.

Special Cases
  • If $arg is the empty sequence, the function returns the empty sequence.

  • If $arg is zero (positive or negative), the function returns $arg.

  • If $arg is NaN, the function returns NaN.

  • This function is new in XQuery 3.0.

Examples
ExampleReturn value
math:atan(0) 0
math:atan(-0) -0
math:atan(1) 0.785398163 (approximately)

math:atan2

Returns the arc tangent based on two arguments

Signature
math:atan2($y as xs:double, $x as xs:double) as xs:double
Usage Notes

This function returns the angle, in radians, subtended at the origin by the point on a plane with coordinates ($x, $y) and the positive x-axis. The result is in the range -π to +π, inclusive.

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

Special Cases
  • If either argument is NaN, the function returns NaN.

  • This function is new in XQuery 3.0.

Examples
ExampleReturn value
math:atan2(+0, 0) 0
math:atan2(-0, 0) -0
math:atan2(-1, 0.0e0) -1.5707963 (approximately)

available-environment-variables

Returns the names of available environment variables

Signature
available-environment-variables() as xs:string*
Usage Notes

This function returns a list of the names of the environment variables that are available in the dynamic context. The result is a list of strings, in an implementation-dependent order, with no duplicates. Each name in the returned list can be passed to the environment-variable function to return its value. The definition of environment variable is processor- and platform-dependent.

Special Cases
  • If access to environment variables has been disabled by the processor, for example, for security reasons, the function will return the empty sequence.

  • This function is new in XQuery 3.0.

Example

When evaluating the function call available-environment-variables() in a Windows environment, a standalone XQuery processor might return a list of Windows environment variable names such as JAVA_HOME, COMPUTERNAME, and CLASSPATH.

Related Function

environment-variable

avg

Finds the average value of the items in a sequence

Signature
avg($arg as xs:anyAtomicType*) as xs:anyAtomicType?
Usage Notes

This function finds the average of the items in $arg, which can contain a mixture of numeric and untyped values. Numeric values are promoted as necessary to make them all the same type. Untyped values are cast as numeric xs:double values.

The function can also be used on duration values, so the $arg sequence can contain all xs:yearMonthDuration values or all xs:dayTimeDuration values (but not a mixture of the two). The $arg sequence cannot contain a mixture of duration and numeric values.

Special care should be taken with any “missing” values when using the avg function. This is described further in “Counting “Missing” Values”.

Special Cases
  • If $arg is the empty sequence, the function returns the empty sequence.

  • If $arg contains untyped values that cannot be cast to numbers, error FORG0001 is raised.

  • If $arg contains typed values that are not numeric or duration values, or values that have a variety of types, error FORG0006 is raised.

  • If $arg contains values that are NaN, the function returns NaN.

Examples
ExampleReturn value
avg( (1, 2, 3, 4, 5) ) 3
avg( (1, 2, 3, (), 4, 5) ) 3
avg( (xs:yearMonthDuration("P4M"),
xs:yearMonthDuration("P6M") ) )
P5M
avg(doc("order.xml")//item/@quantity) 1.166667 (with implementation-defined precision)
avg( () ) ()
avg(doc("order.xml")//item/@dept) Error FORG0001
Related Functions

sum, count

base-uri

Gets the base URI of a node

Signature
base-uri($arg as node()?) as xs:anyURI?
Usage Notes

This function returns the base URI of a node. The essential purpose of a base URI is to establish a baseline for resolving any relative URIs in the content.

$arg may be any kind of node. If $arg is a document node, this function usually returns the URI from which the document was retrieved, if it is known. This can also be achieved by using the document-uri function.

An example where the base URI might not be known is where the document is created by parsing an anonymous input stream. Check your processor’s documentation for details of how to supply a base URI in such cases. An example of where the base URI might be different from the URI used to retrieve it is in the case of a multipart MIME message.

If $arg is an element, the function returns the value of its xml:base attribute, if any, or the xml:base attribute of its nearest ancestor. If no xml:base attributes appear among its ancestors, it defaults to the base URI of the document node. If the original document consisted of multiple external entities (files), the base URI would be the URI of the containing entity.

If $arg is any other kind of node, the function returns the same value as if the argument were its parent element or document.

For more information on URIs, see “Working with URIs”.

Special Cases
  • If $arg is the empty sequence, the function returns the empty sequence.

  • If $arg is not provided, the function returns the base URI of the current context item. Note that this is not the same as the base URI from the static context, which is retrieved using the static-base-uri function. In this case, it is an error if the context item is absent (XPDY0002) or not a node (XPTY0004).

  • If no base URI can be found, for example because the element node has no base URI and does not have a document node as its root, the function returns the empty sequence.

Examples

These examples assume that the variable $cats is bound to the input document http://datypic.com/input/cats.xml shown in Example A-1, as follows:

declare variable $cats := doc("http://datypic.com/input/cats.xml");
ExampleReturn value
base-uri($cats//catalog[1]) http://datypic.com/ACC/
base-uri($cats//catalog[2]/product) http://datypic.com/WMN/
base-uri($cats//catalog[2]/product/@href) http://datypic.com/WMN/
base-uri($cats) http://datypic.com/input/cats.xml
base-uri($cats/catalogs) http://datypic.com/input/cats.xml
Example A-1. Using xml:base (http://datypic.com/input/cats.xml)
<catalogs>
  <catalog name="ACC" xml:base="http://datypic.com/ACC/">
    <product number="443" href="prod443.html"/>
    <product number="563" href="prod563.html"/>
  </catalog>
  <catalog name="WMN" xml:base="http://datypic.com/WMN/">
    <product number="557" href="prod557.html"/>
  </catalog>
</catalogs>

boolean

Finds the effective boolean value

Signature
boolean($arg as item()*) as xs:boolean
Usage Notes

This function calculates the effective boolean value of a sequence (that is, any value). For more information, see “Effective Boolean Value”.

In most cases, it is unnecessary to call this function because the effective boolean value is calculated automatically in many expressions, including conditional and logical expressions, where clauses, and predicates.

This boolean function, which can also be written as fn:boolean, should not be confused with the xs:boolean constructor, which casts a value to xs:boolean. In some cases, they return different results, namely when $arg is:

  • A single node that contains the value false (xs:boolean returns false because it atomizes the node, while fn:boolean returns true)

  • The string value false (xs:boolean returns false, fn:boolean returns true)

  • A zero-length string, or any string other than true, false, 0, or 1 (xs:boolean raises an error, fn:boolean returns false if it’s a zero-length string; otherwise, true)

  • A sequence of more than one node (xs:boolean raises an error, fn:boolean returns true)

Special Case
  • If the effective boolean value of $arg cannot be determined, for example because $arg is a sequence of multiple atomic values or an array, error FORG0006 is raised.

Examples
ExampleReturn value
boolean( () ) false
boolean("") false
boolean(0) false
boolean("0") true
boolean(false()) false
boolean("false") true
boolean(xs:float("NaN")) false
boolean( (false(), false(), false()) ) Error FORG0006
boolean(doc("order.xml")/order[1]) true
boolean(doc("order.xml")/noSuchChild) false
boolean(<a>false</a>) true
Related Functions

true, false, empty, exists

ceiling

Rounds a number up to the nearest higher integer

Signature
ceiling($arg as xs:numeric?) as xs:numeric?
Usage Notes

This function returns the smallest whole number that is not less than $arg. It returns a numeric value of type xs:float, xs:double, xs:decimal, or xs:integer, depending on which type the argument is derived from. If $arg is untyped, it is cast to xs:double.

Special Cases
  • If $arg is the empty sequence, the function returns the empty sequence.

  • If $arg is greater than -1 but less than zero, the function may return 0 or -0 (it is implementation-dependent).

  • If $arg is one of the values 0, -0, NaN, INF, or -INF, the function returns this same value.

Examples
ExampleReturn value
ceiling(5) 5
ceiling(5.1) 6
ceiling(5.5) 6
ceiling(-5.5) -5
ceiling(-5.51) -5
ceiling( () ) ()

codepoint-equal

Determines whether two strings contain the same codepoints

Signature
codepoint-equal($comparand1 as xs:string?,
                $comparand2 as xs:string?) as xs:boolean?
Usage Notes

This function determines whether $comparand1 and $comparand2 have the same Unicode codepoints, in the same order. This is similar to calling the compare function with the simple collation http://www.w3.org/2005/xpath-functions/collation/codepoint, except that the result is a Boolean value. It is also possible to compare strings using comparison operators = or eq.

Special Case
  • If either argument is the empty sequence, the function returns the empty sequence.

Examples
ExampleReturn value
codepoint-equal("abc", "abc") true
codepoint-equal("abc", "ab c") false
codepoint-equal("abc", ()) ()
Related Function

compare

codepoints-to-string

Constructs a string from Unicode codepoint values

Signature
codepoints-to-string($arg as xs:integer*) as xs:string
Usage Notes

This function accepts a sequence of integers $arg that represent Unicode codepoint values. It converts each integer to a character, then concatenates all the characters into a single string.

Special Cases
  • If one or more of the $arg integers does not refer to a valid XML character, error FOCH0001 is raised.

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

Examples
ExampleReturn value
codepoints-to-string( (97, 32, 98, 32, 99) ) a b c
codepoints-to-string(97) a
codepoints-to-string( () ) A zero-length string
Related Function

string-to-codepoints

collation-key

Returns a collation key for a string, that allows it to be matched and ordered

Signature
collation-key($key as xs:string, $collation as xs:string) as xs:base64Binary
Usage Notes

Collations are used to specify the order in which characters should be compared and sorted. The collation-key function applies a collation to a string, generating an identifier for that string so that it can be compared or sorted with other strings. How (and even whether) a collation key is generated is implementation-dependent. The key is a binary value. A collation key will always be generated in such a way that two strings that are equal according to the collation will have the same collation key returned by this function, and two strings that are not equal will have different collation keys.

This function is most useful for comparing keys in maps. If your intent is to compare strings according to a collation, you may find it more convenient to use the compare function with its third $collation argument. If you are sorting strings, you can specify a predetermined collation in an order by clause of a FLWOR expression. If you need to dynamically choose a collation, the collation-key function may be helpful. More information can be found in “Collations”.

Special Cases
  • If $collation is a relative URI, it is resolved against the static base URI.

  • If $collation is omitted, the default collation is used.

  • If the collation does not support the generation of collation keys, error FOCH0004 is raised.

  • This function is new in XQuery 3.1.

Example

Given a hypothetical collation http://datypic.com/collation/custom that collapses whitespace when comparing strings, you could write the following query:

let $coll := "http://datypic.com/collation/custom"
let $m := map{collation-key("A", $coll): "first", 
              collation-key("B", $coll): "second"}
return $m(collation-key(" A ", $coll))

which would return the value "first". It would compare "A" with " A " and find them equal according to the specified collation. The collation-key function would need to be called both when creating the map and when retrieving entries.

collection

Gets the items that make up a collection

Signature
collection($arg as xs:string?) as item()*
Usage Notes

This function returns a collection, which is a sequence of items, identified by a URI. In practice, a collection is most often a sequence of documents that are organized so that they can be queried or managed together.

Exactly how the collection URI ($arg) is associated with the items is defined by the implementation. Most XML database implementations allow you to define collections (and add documents to them) using the product’s user interface or implementation-specific functions. Saxon, on the other hand, allows you to specify a directory where the input documents reside, optionally with parameters. For example:

collection("file:///C:/Users/PW/My%20Documents/?select=*.xml;recurse=yes")

returns the collection of documents in the directory C:/Users/PW/My Documents/ whose file extension is .xml, including subdirectories.

If $arg is a relative URI, it is resolved based on the static base URI. The static base URI may be set by the processor outside the scope of the query, or it may be declared in the query prolog.

By default, the collection function is deterministic. This means that if you call it more than once with the same argument, within the same query, the result is the same, even if somehow the resources associated with the URI have changed. Implementations may, however, offer users a way to indicate that determinism is not important, for performance reasons.

Special Cases
  • If $arg is not a collection URI known to the processor, error FODC0002 is raised.

  • If $arg is a collection URI known to the processor, but it is empty, the empty sequence is returned.

  • If a resource in the collection cannot be retrieved or parsed, for example, because it does not reference a resource, or the resource is not well-formed XML, error FODC0002 is raised.

  • If $arg is a relative URI and there is no static base URI to use to resolve the relative URI, error FODC0002 is raised.

  • If $arg is not provided or is the empty sequence, the function returns the default collection. If the default collection is absent, error FODC0002 is raised.

  • If $arg is not a lexically valid URI, error FODC0004 may be raised.

  • If the processor cannot return deterministic results, error FODC0003 is raised.

Example

The expression collection("myXMLdocs") might return all the document nodes of the XML documents associated with the collection myXMLdocs.

Related Functions

doc , uri-collection

compare

Compares strings, optionally with an explicit collation

Signature
compare($comparand1 as xs:string?, $comparand2 as xs:string?,
        $collation as xs:string) as xs:integer?
Usage Notes

This function returns one of the values:

  • -1 if $comparand1 is less than $comparand2

  • 0 if $comparand1 is equal to $comparand2

  • 1 if $comparand1 is greater than $comparand2

A comparand is greater than the other comparand if it starts with the other comparand and has additional characters. For example, abc is greater than ab.

Comparison operators (=, !=, <, <=, >, and >=) can also be used to compare strings, and you may find the syntax more convenient. However, compare is also useful if you want to take different action in each of the three result cases. Also, if you need to use a specific collation other than the default, you must use the compare function. More information can be found in “Collations”.

Special Cases
  • If either comparand is the empty sequence, the function returns the empty sequence.

  • If $collation is provided, the comparison uses that collation; otherwise, it uses the default collation. For more information, see “Collations”.

Examples

These examples assume that no default collation is specified.

ExampleReturn value
compare("a", "b") -1
compare("a", "a") 0
compare("b", "a") 1
compare("ab", "abc") -1
compare("a", "B") 1
compare(upper-case("a"), upper-case("B")) -1
compare("a", ()) ()
compare('Strasse', 'Stra&#223;e',
'http://datypic.com/german')
0 if the collation equates the &#223; character with two s’s.
compare("a", "b", "FOO") Error FOCH0002

The fifth example in the table shows that when using the simple codepoint collation, a lowercase a comes after an uppercase B. If you do not want case to be taken into account when comparing strings, convert the strings to uppercase first, as shown in the sixth example. Alternatively, you could use a case-insensitive collation.

Related Function

codepoint-equal

concat

Concatenates two or more strings together

Signature
concat($arg1 as xs:anyAtomicType?,
       $arg2 as xs:anyAtomicType?, ...) as xs:string
Usage Notes

This function requires at least two arguments (which can be the empty sequence) and accepts an unlimited number of additional arguments. This is the only XQuery function that has a flexible number of arguments, for compatibility with XPath 1.0. The function is also unusual in that arguments that are not of type xs:string will be cast to xs:string.

The function does not accept a sequence of multiple values, just individual atomic values (or nodes) passed as separate arguments. To concatenate a sequence of multiple values, use the string-join function instead.

Another alternative to the concat function, starting in version 3.0, is the string concatenation operator ||, described in “Concatenating Strings”.

Special Case
  • If an argument is the empty sequence, it is treated as a zero-length string.

Examples
ExampleReturn value
concat("a") Error XPST0017
concat("a", "b") ab
concat("a", "b", "c") abc
concat("a", (), "b", "", "c") abc
concat( ("a", "b", "c") ) Error XPST0017 (use string-join instead)
concat(doc("catalog.xml")//name) Error XPST0017 (use string-join instead)
concat("a", <x>b</x>, <x>c</x>) abc
Related Function

string-join

contains

Determines whether one string contains another

Signature
contains($arg1 as xs:string?, $arg2 as xs:string?,
         $collation as xs:string) as xs:boolean
Usage Notes

This function returns true if $arg1 contains the characters of $arg2 anywhere in its contents, including at the beginning or end. Note that contains does not test whether a sequence of multiple strings contains a given value. For that, use the = operator.

Special Cases
  • If $arg2 is a zero-length string or the empty sequence, the function returns true.

  • If $arg1 is a zero-length string or the empty sequence, but $arg2 is not, the function returns false.

  • If $collation is provided, the comparison uses that collation; otherwise, it uses the default collation. For more information, see “Collations”.

Examples
ExampleReturn value
contains("query", "e") true
contains("query", "ery") true
contains("query", "query") true
contains("query", "x") false
contains("query", "") true
contains("query", ()) true
contains( (), "q") false
contains("", "") true
contains("", "query") false

map:contains

Determines whether a map contains a specified key

Signature
map:contains($map as map(*), $key as xs:anyAtomicType) as xs:boolean
Usage Notes

This function returns true if $map contains an entry whose key is $key. The $key value is compared to the map’s keys in a type-aware manner, e.g., the string “1” and the integer 1 are not considered the same value.

Special Cases
  • If $key has a type that is not comparable to the types of the keys of the map, for example $key is a string but the keys of $map are integers, the function returns false rather than returning an error.

  • If $key is untyped, it is compared to the keys of the map as a string value.

  • When strings are compared, they are compared as Unicode codepoints only; the default collation is not used.

  • This function is new in XQuery 3.1.

Examples

The examples assume these variable declarations:

declare variable $map1 := map {1:"first", 2:"second", 3:"third", 4:()};
declare variable $map2 := map {};
ExampleReturn value
map:contains($map1, 1) true
map:contains($map1, 4) true, even though the value associated with key 4 is the empty sequence, the key still exists in the map
map:contains($map1, 9) false
map:contains($map1, "1") false, because the string "1" and the integer 1 are not the same
map:contains($map2, 1) false

contains-token

Determines whether one string contains another with whitespace boundaries around it

Signature
contains-token($input as xs:string*, $token as xs:string,
               $collation as xs:string) as xs:boolean
Usage Notes

This function returns true if at least one of the strings in $input contains the characters of $token surrounded by whitespace (or the beginning or ending of the string). If $token has leading or trailing whitespace, it is trimmed before doing the evaluation.

Special Cases
  • The function returns false if $input is the empty sequence, a zero-length string, an all-whitespace string, or a string that contains interior whitespace.

  • If $collation is provided, the comparison uses that collation; otherwise, it uses the default collation. For more information, see “Collations”.

  • This function is new in XQuery 3.1.

Examples
ExampleReturn value
contains-token("a b c", "b") true
contains-token("a b c", "c") true
contains-token("a b c", " c ") true
contains-token( ("a b c", "d e f"), "c") true
contains-token( "a, b, c", "b") false
contains-token( "a b c", "b c") false

math:cos

Returns the cosine

Signature
math:cos($θ as xs:double?) as xs:double?
Usage Notes

This function finds the cosine of , which is an angle in radians. The result is in the range -1.0e0 to +1.0e0, inclusive.

Special Cases
  • If is the empty sequence, the function returns the empty sequence.

  • If is INF, -INF, or NaN, the function returns NaN.

  • This function is new in XQuery 3.0.

Examples
ExampleReturn value
math:cos(0) 1
math:cos(math:pi() div 2) 0 (approximately)
math:cos(math:pi()) -1 (approximately)

count

Counts the number of items in a sequence

Signature
count($arg as item()*) as xs:integer
Usage Notes

This function returns the number of items in a sequence as an xs:integer.

To test whether or not the number of items in a sequence is zero, use the exists or empty function instead. Depending on your processor’s optimizer, exists($x) may be more efficient than count($x) = 0.

Special Case
  • If $arg is the empty sequence, the function returns 0.

Examples
ExampleReturn value
count( (1, 2, 3) ) 3
count(doc("order.xml")//item) 6
count(distinct-values(doc("order.xml")//item/@num)) 4
count( (1, 2, 3, () ) ) 3
count( () ) 0

The third example shows that the count function can be combined with the distinct-values function to count only distinct values.

current-date

Gets the current date

Signature
current-date() as xs:date
Usage Notes

This function takes no parameters and returns the current date, with the implicit time zone. To eliminate the time zone from the value, you can call adjust-date-to-timezone with the empty sequence as the second argument, as in:

adjust-date-to-timezone(current-date(), ())
Example

current-date() might return the xs:date value 2015-04-10-05:00, which is April 10, 2015 in the -05:00 time zone.

current-dateTime

Gets the current date and time

Signature
current-dateTime() as xs:dateTimeStamp
Usage Notes

This function takes no parameters and returns the current date and time, with the implicit time zone. If the function is called multiple times within the same query, it returns the same value every time. To eliminate the time zone from the value, you can call adjust-dateTime-to-timezone with the empty sequence as the second argument, as in:

adjust-dateTime-to-timezone(current-dateTime(), ())

This function is deterministic, which means that multiple calls to current-dateTime in the same query execution will return the same value.

Example

current-dateTime() might return the xs:dateTime value 2015-04-10T13:40:23.83-05:00.

Related Functions

current-date, current-time

current-time

Gets the current time

Signature
current-time() as xs:time
Usage Notes

This function takes no parameters and returns the current time, with the implicit time zone. If the function is called multiple times within the same query, it returns the same value every time. To eliminate the time zone from the value, you can call adjust-time-to-timezone with the empty sequence as the second argument, as in:

adjust-time-to-timezone(current-time(), ())

This function is deterministic, which means that multiple calls to current-time in the same query execution will return the same value.

Example

current-time() might return the xs:time value 13:40:23.83-05:00.

data

Extracts the typed value of one or more items

Signature
data($arg as item()*) as xs:anyAtomicType*
Usage Notes

This function accepts a sequence of items and returns their typed values. For atomic values, this simply means returning the value itself, unchanged. For nodes, this means extracting the typed value of the node.

It is also possible to pass arrays to this function. Arrays are flattened (recursively) and the function returns the typed values of the members of the array, whether they are nodes or atomic values.

Calling this function is usually unnecessary because the typed value of a node is extracted automatically (in a process known as atomization) for many XQuery expressions, including comparisons, arithmetic operations, function calls, and sorting in FLWORs. The most common use case for the data function is in element constructors. For example, the expression:

for $prod in doc("catalog.xml")//product
return <newEl>{data($prod/name)}</newEl>

uses the data function to extract the typed value of the name element, in order to put it in the content of newEl. If it had not used the data function, the resulting newEl elements would each have a name child instead of just character data content.

In most cases, the typed value of an element or attribute is simply its string value, cast to the type of the element or attribute. For example, if the number element has the type xs:integer, the string value of the element is 784 (type xs:string), while the typed value is 784 (type xs:integer). If the number element is untyped, its typed value is 784 (type xs:untypedAtomic).

The typed value of an element will not be the empty sequence just because the element has no content. For example, the typed value of <name></name> is the value "" (type xs:untypedAtomic) if name is untyped, not the empty sequence.

There are some additional subtleties for schema-validated elements that are described in “Nodes and Typed Values”.

Other kinds of nodes have typed values as well, but they are less useful; they are described in the appropriate sections of Chapter 22.

Special Cases
  • If $arg is the empty sequence, the function returns the empty sequence.

  • If $arg contains an element whose type has element-only content, its typed value is considered absent and error FOTY0012 is raised.

  • If $arg contains a function item other than an array (including a map), error FOTY0013 is raised.

  • If $arg is not provided, the context item is used. In this case, if the context item is absent, error XPDY0002 is raised.

  • When using XQuery 1.0, the zero-argument version of this function is not available, so $arg must be provided.

Examples

Table A-3 shows some examples of the data function applied to untyped nodes. They assume the following variable declaration, and that catalog.xml has not been validated with a schema.

declare variable $cat := doc("catalog.xml");
Table A-3. Examples of the data function on untyped nodes
ExampleReturn valueReturn type
data($cat//product[1]/number) 557 xs:untypedAtomic
data($cat//number) (557, 563, 443, 784) xs:untypedAtomic*
data($cat//product[1]/@dept) WMN xs:untypedAtomic
data($cat//product[1]/colorChoices) navy black xs:untypedAtomic
data($cat//product[1]) 557 Fleece Pullover navy black xs:untypedAtomic
data($cat//product[4]/desc) Our favorite shirt! xs:untypedAtomic

Now suppose you have the schema shown in Example 14-1, and catalog.xml was validated using this schema. Table A-4 shows how the typed values of the nodes would then change, again assuming the following variable declaration:

declare variable $cat := doc("catalog.xml");
Table A-4. Examples of the data function on typed nodes
ExampleReturn valueReturn type
data($cat//product[1]/number) 557 xs:integer
data($cat//number) (557, 563, 443, 784) xs:integer*
data($cat//product[1]/@dept) WMN xs:string
data($cat//product[1]/colorChoices) (navy, black) xs:string*
data($cat//product[1]) Error FOTY0012N/A
data($cat//product[4]/desc) Our favorite shirt! xs:untypedAtomic

Table A-5 shows some examples of calling the data function with arguments that are not nodes.

Table A-5. Examples of the data function on non-nodes
ExampleReturn valueReturn type
data(1) 1 xs:integer
data( (1, 2, 3) ) (1, 2, 3) xs:integer*
data( [1, 2, 3] ) (1, 2, 3) xs:integer*
data( [1, 2, ['a', 'b', 'c']] ) (1, 2, 'a', 'b', 'c') xs:anyAtomicType*
data( () ) ()
data( concat#3 ) Error FOTY0013
Related Function

string

dateTime

Constructs a date/time value from separate date and time values

Signature
dateTime($arg1 as xs:date?, $arg2 as xs:time?) as xs:dateTime?
Usage Notes

This function constructs an xs:dateTime value from an xs:date value and an xs:time value. It should not be confused with the xs:dateTime constructor, which accepts a single argument that includes the date and time.

Time zone is taken into account when constructing the date/time. If neither the date nor the time has a time zone, the result has no time zone. If only one of the arguments has a time zone, or they both have the same time zone, the result has that time zone.

Special Cases
  • If the two arguments have different time zones, error FORG0008 is raised.

  • If either of the two arguments is the empty sequence, the function returns the empty sequence.

Example

dateTime(xs:date("2015-08-15"), xs:time("12:30:45-05:00")) returns the xs:dateTime value 2015-08-15T12:30:45-05:00.

day-from-date

Gets the day portion of a date

Signature
day-from-date($arg as xs:date?) as xs:integer?
Usage Notes

This function returns the day portion from an xs:date value as an integer between 1 and 31, inclusive.

Special Case
  • If $arg is the empty sequence, the function returns the empty sequence.

Example

day-from-date(xs:date("2015-08-15")) returns 15.

Related Function

day-from-dateTime

day-from-dateTime

Gets the day portion of a date/time

Signature
day-from-dateTime($arg as xs:dateTime?) as xs:integer?
Usage Notes

This function returns the day portion from an xs:dateTime value as an integer between 1 and 31, inclusive.

Special Case
  • If $arg is the empty sequence, the function returns the empty sequence.

Example

day-from-dateTime(xs:dateTime("2015-08-15T10:30:23")) returns 15.

Related Function

day-from-date

days-from-duration

Gets the number of days in a duration

Signature
days-from-duration($arg as xs:duration?) as xs:integer?
Usage Notes

This function calculates the number of whole days in an xs:duration value. This is not necessarily the same as the integer that appears before the D in the value. For example, if the duration is P1DT36H, the function returns 2 rather than 1. This is because 36 hours is equal to 1.5 days, and the canonical value is therefore P2DT12H.

The days-from-duration function does not round the number of days; if the duration is 2 days and 23 hours, it returns the integer 2.

Special Cases
  • If $arg is a negative duration, the function returns a negative value.

  • If $arg is the empty sequence, the function returns the empty sequence.

Examples
ExampleReturn value
days-from-duration(xs:duration("P5D")) 5
days-from-duration(xs:duration("-PT24H")) -1
days-from-duration(xs:duration("PT23H")) 0
days-from-duration(xs:duration("P1DT36H")) 2
days-from-duration(xs:duration("PT1440M")) 1
days-from-duration(xs:duration("P1Y")) 0

deep-equal

Determines whether the values of two sequences of items are equal (contain the same data)

Signature
deep-equal($parameter1 as item()*, $parameter2 as item()*,
           $collation as xs:string) as xs:boolean
Usage Notes

This function returns true if the $parameter1 and $parameter2 sequences contain the same values, in the same order.

Atomic values are compared based on their typed values, using the eq operator. If two atomic values cannot be compared (e.g., because one is a number and the other is a string), the function returns false rather than raising an error.

The comparison of nodes takes into account the descendants and attributes. In order to be considered deep-equal, two nodes must:

  • Have the same qualified name.

  • Have the same node kind.

  • If they are elements, have the exact same attributes with the same qualified names and the same values (possibly in a different order).

  • If they are attributes or elements with simple content (no children), their typed values must be equal. For example, 2 is considered the same as 02 if they are both typed as integers, but not if they are both strings.

  • If they are elements with children, have element children and text nodes in the same order, that are themselves deep-equal.

  • If they are document nodes, have element and text children in the same order, that are themselves deep-equal.

  • If they are processing-instruction nodes, have the same name (target) and the exact same string value.

  • If they are text or comment nodes, have the exact same string value.

The two nodes do not have to have the same type, parent, or base URI. Namespace declarations are considered only to the extent that they affect element and attribute names or values typed as QNames; “unused” namespaces are ignored.

When comparing two element or document nodes, child comments and processing instructions are ignored. However, the presence of a comment that splits a text node in two will cause the text nodes to be unequal. Whitespace-only text nodes are considered significant.

The deep-equal function can also be used to compare arrays and maps. Two arrays are deep-equal if all of their members are deep-equal (in the same order). Two maps are deep-equal if they have all the same entries (with equal keys and values), regardless of order.

Special Cases
  • If both $parameter1 and $parameter2 are the empty sequence, the function returns true.

  • If only one of $parameter1 or $parameter2 is the empty sequence, the function returns false.

  • If $collation is provided, the comparison uses that collation; otherwise, it uses the default collation. For more information, see “Collations”.

  • In the context of this function, NaN is considered equal to itself. This is to ensure that a node is always deep-equal to itself, even if some descendant has a typed value of NaN.

  • If $parameter1 or $parameter2 contains a function item other than an array or map, error FOTY0015 is raised.

Examples

The examples below assume that the variables $prod1 and $prod2 are bound to the two product elements as shown:

declare variable $prod1 := <product dept="MEN" id="P123">
  <number>784</number>
</product>;
declare variable $prod2 := <product id="P123" dept="MEN"><!--comment-->
  <number>784</number>
</product>;
ExampleReturn value
deep-equal(1, 1) true
deep-equal( (1, 1), (1, 1) ) true
deep-equal( (1, 2), (1.0, 2.0) ) true
deep-equal( (1, 2), (2, 1) ) false
deep-equal($prod1, $prod2) true, because the order of the attributes and the presence of the comment are not significant
deep-equal($prod1/number, $prod2/number) true
deep-equal($prod1/node(), $prod2/node()) false because of the extra comment node

default-collation

Gets the default collation

Signature
default-collation() as xs:string
Usage Notes

This function returns the default collation that is used in most operations where a collation is not explicitly specified. If no default collation is specified in the query prolog, the function returns the system default collation. If no system default collation is provided, the function returns a value representing the Unicode Codepoint Collation, http://www.w3.org/2005/xpath-functions/collation/codepoint. See “Collations” for more information.

Example

default-collation() might return http://datypic.com/collation/custom if that is the name of the default collation declared in the query prolog.

default-language

Gets the default language

Signature
default-language() as xs:language
Usage Notes

This function returns the default language used by the format-date, format-dateTime, format-time, and format-integer functions.

Example

default-language() might return en if English is the default language used by the implementation.

distinct-values

Selects distinct atomic values from a sequence

Signature
distinct-values($arg as xs:anyAtomicType*,
                $collation as xs:string) as xs:anyAtomicType*
Usage Notes

This function returns a sequence of unique atomic values from $arg. Values are compared based on their typed value. Values of different numeric types may be equal—for example, the xs:integer value 1 is equal to the xs:decimal value 1.0, so the function only returns one of these values. If two values have incomparable types, e.g., xs:string and xs:integer, they are considered distinct, and no error is raised. Untyped values are treated like strings.

The $arg sequence can contain atomic values or nodes, or a combination of the two. The nodes in the sequence have their typed values extracted using the usual function conversion rules. This means that only the contents of the nodes are compared, not any other properties of the nodes (for example, their names or identities). To get distinct nodes by identity instead, you can simply use the expression $seq/., which re-sorts the nodes and removes duplicates.

Because XQuery does not specify which of the duplicates to exclude, there may be some variation among implementations in the order and type of items in the result sequence.

Special Cases
  • If $arg is the empty sequence, the function returns the empty sequence.

  • If $arg contains more than one NaN value, only one of them is returned (even though one NaN value is technically not equal to other NaN values).

  • Dates and times with no time zone component are assumed to be in the implicit time zone.

  • If $collation is provided, the function uses that collation to compare string values; otherwise, it uses the default collation. For more information, see “Collations”.

  • If $arg contains an element whose schema type has element-only content, the type error FOTY0012 is raised, because such nodes do not have typed values.

Examples
ExampleReturn value
distinct-values( ("a", "b", "a") ) ("a", "b")
distinct-values( (1, 2, 3) ) (1, 2, 3)
distinct-values( ("a", 2, 3) ) ("a", 2, 3)
distinct-values( (xs:integer("1"), xs:decimal("1.0"), xs:float("1.0E0") ) ) (1)
distinct-values( (<a>3</a>, <b>5</b>) ) (3, 5)
distinct-values( (<a>3</a>, <b>3</b>) ) (3)
distinct-values( ["a", "b", "a"] ) ("a", "b")
distinct-values( () ) ()

doc

Opens one XML input document based on its URI

Signature
doc($uri as xs:string?) as document-node()?
Usage Notes

This function returns the document node of the resource associated with the URI $uri. For example:

doc("http://datypic.com/input/order.xml")

returns the document node of the document whose URI is http://datypic.com/input/order.xml. The doc function can be combined with a path expression to retrieve specific children, as in:

doc("catalog.xml")/catalog/product

Note that the doc function returns the document node, not the outermost element node. Therefore, you need to include the outermost element node in your path (catalog in the previous example).

The rules for how the function resolves the URI in $uri are described in “Resolving URIs of input documents”.

By default, the doc function is deterministic, meaning that it returns the same results each time it is called within a query. If you call the doc function more than once with the same argument, within the same query, the result is the same, even if somehow the resource at $uri has changed. Furthermore, the document nodes retrieved from each of these calls are identical to each other. Implementations may, however, offer users a way to indicate that determinism is not important, for performance reasons.

Special Cases
  • If $uri is the empty sequence, the function returns the empty sequence.

  • If $uri is not a lexically valid URI, error FODC0005 may be raised.

  • If the resource cannot be retrieved or parsed, for example, because it does not reference a resource, or the resource is not well-formed XML, the behavior is implementation-defined. It may result in error FODC0002, or in some other error handling behavior (such as a default document being opened).

  • If the processor cannot return deterministic results, error FODC0003 is raised.

Example

Depending on the processor and on the location of the file, any of the following might be used to return the document node of the order document:

  • doc("order.xml")

  • doc("http://datypic.com/input/order.xml")

  • doc("file:///C:/Documents%20and%20Settings/my%20order.xml")

doc-available

Determines whether a document is available

Signature
doc-available($uri as xs:string?) as xs:boolean
Usage Notes

This function provides a way to avoid errors returned by the doc function if a document is not available. This function will return true if calling the doc function on the same URI will result in a document node. It will return false if the doc function will not return a document node.

Special Case
  • If $uri is the empty sequence or is not a lexically valid or retrievable URI, the function returns false.

Example

This query will check if an XML document named http://datypic.com/new_order.xml is available:

if (doc-available("http://datypic.com/new_order.xml"))
then doc("http://datypic.com/new_order.xml")
else ()

If a document is available, it will return its document node. Otherwise, it will return the empty sequence. If the doc function had been called without verifying the existence of the document first, an error might have been raised.

Related Function

doc

document-uri

Gets the URI of a document node

Signature
document-uri($arg as node()?) as xs:anyURI?
Usage Notes

This function is basically the inverse of the doc function. Where the doc function accepts a URI and returns a document node, the document-uri function accepts a document node and returns the absolute URI associated with it. The URI may represent the location from which it was retrieved, or simply the URI that serves as its name in an XML database.

In most cases, calling this function has the same result as calling the base-uri function with the document node.

Special Cases
  • If $arg is not a document node, the function returns the empty sequence.

  • If $arg does not have a document URI (for example, because it is constructed), the function returns the empty sequence.

  • If the $arg node’s document URI is a relative URI that cannot be resolved, the function returns the empty sequence.

  • If $arg is the empty sequence, the function returns the empty sequence.

  • If $arg is not provided, the context item is used. In this case, it is an error if the context item is absent (XPDY0002) or not a node (XPTY0004).

  • When using XQuery 1.0, the zero-argument version of this function is not available, so $arg must be provided.

Example

If the variable $orderDoc is bound to the result of doc("http://datypic.com/input/order.xml"), then document-uri($orderDoc) returns http://datypic.com/input/order.xml.

Related Functions

doc, base-uri

element-with-id

Returns elements that have a specified ID child or attribute

Signature
element-with-id($arg as xs:string*, $node as node()) as element()*
Usage Notes

Given a sequence of IDs ($arg), this function returns the elements with those IDs. If $node is not provided, the function looks for elements in the same document as the current context node. If $node is provided, the function looks for elements in the same document as $node.

The strings in the $arg sequence can either be individual ID values or space-separated lists of ID values. Although $arg is a sequence of xs:string values, you can also pass values of type xs:IDREF or xs:IDREFS, since these types are derived from xs:string.

An element is considered by the element-with-id function to have a particular ID if either:

  • It has an attribute that is marked as an ID, that has that ID value.

  • It has a child element that is marked as an ID and its content is that particular ID value.

This behavior is in contrast with the id function, which, in the latter case returns the element that is marked an ID, not its parent.

An element or attribute node can become “marked as an ID” by being validated by a schema where it is declared as having type xs:ID, or (for an attribute) being described in a DTD as being of type ID. Also, if it is an attribute named xml:id, it is automatically considered to be an ID.

The function returns the nodes in document order, not the order designated by the sequence of $arg values. The result sequence contains no duplicate elements, even if an ID value was included twice in $arg.

Working with IDs and IDREFs is discussed in further detail in “Working with IDs”.

Special Cases
  • Any values in $arg that are not lexically valid IDs (i.e., XML NCNames) are ignored, even if there is an element with that invalid ID.

  • If there is no element with a specified ID, an error is not raised, but no element is returned for that ID value.

  • In the case of an invalid (but well-formed) document where more than one element has the same ID, the function returns the first element in the document with that ID.

  • If $arg is the empty sequence, the function returns the empty sequence.

  • If no matching elements were found, the function returns the empty sequence.

  • If $node is not provided, the context item is used. In this case, it is an error if the context item is absent (XPDY0002) or not a node (XPTY0004).

  • Error FODC0001 is raised if $node is not part of a document (its root is not a document node).

  • This function was optionally supported in XQuery 1.0, and always supported in XQuery 3.0 and later.

Examples

These examples use the input document catalog-with-ids.xml shown in Example A-2. It is assumed that the input document has been validated and that the type of the id element is xs:ID.

The final example shows the difference between the element-with-id function and the id function. See the discussion of the id function for a more typical example, where the IDs are attributes instead of elements.

ExampleReturn value
doc("catalog-with-ids.xml")/element-with-id("A1") The first product element
doc("catalog-with-ids.xml")/
element-with-id( ("A1", "A2") )
Both product elements, in document order
doc("catalog-with-ids.xml")/
element-with-id("A1 A2")
Both product elements, in document order
doc("catalog-with-ids.xml")/id("A1") The id child of the first product element
Example A-2. Product catalog document with IDs (catalog-with-ids.xml)
<catalog>
  <product dept="WMN">
    <id>A1</id>
    <number>557</number>
    <name language="en">Fleece Pullover</name>
  </product>
  <product dept="ACC">
    <id>A2</id>
    <number>563</number>
    <name language="en">Floppy Sun Hat</name>
  </product>
</catalog>
Related Functions

id, idref

empty

Determines whether a sequence is empty

Signature
empty($arg as item()*) as xs:boolean
Usage Notes

This function determines whether a sequence is empty, i.e., whether it contains zero items. A sequence is not considered empty just because it only contains a zero-length string, the value 0, or an element with empty content. To test whether an element has empty content, use the expression:

string($node1) = ""

It is often unnecessary to call the empty function because sequences are automatically converted to their effective boolean value where a Boolean value is expected. For example, if you want to test whether there are any product elements in the catalog, you can use the test expression:

if (not(doc("catalog.xml")//product) then ...

In this case, the sequence of selected product elements is converted to the Boolean value true if the sequence is not empty, and false if the sequence is empty. There is no need to call the empty function to determine this. But beware: this only works for node sequences, not for atomic values.

Examples
ExampleReturn value
empty( ("a", "b", "c") ) false
empty( () ) true
empty(0) false
empty(<desc/>) false
empty(<desc></desc>) false
empty(doc("order.xml")/order) false
empty(doc("order.xml")/foo) true
Related Functions

exists, boolean

encode-for-uri

Applies URI escaping rules to a string that is to be used as a path segment of a URI

Signature
encode-for-uri($uri-part as xs:string?) as xs:string
Usage Notes

URIs require that some characters be escaped with their hexadecimal Unicode codepoint preceded by the % character. This includes non-ASCII characters and some ASCII characters, namely control characters, spaces, and several others.

In addition, certain characters in URIs are separators that are intended to delimit parts of URIs, namely the characters ; , / ? : @ & = + $ [ ] %. If the intended use of a string is as a segment of a URI path, where such separators have special meaning, the encode-for-uri function allows you to escape these separator characters, while also escaping the other necessary special characters.

Like the escape-html-uri and iri-to-uri functions, the encode-for-uri function replaces each special character with an escape sequence in the form %xx (possible repeating), where xx is two hexadecimal digits (in uppercase) that represent the character in UTF-8. For example, édition.html is changed to %C3%A9dition.html, with the é escaped as %C3%A9.

The encode-for-uri function is the most aggressive of the three encoding functions. All characters except the following are escaped:

  • Letters a through z and A through Z

  • Digits 0 through 9

  • Hyphen (-), underscore (_), period (.), and tilde (~)

Because the function escapes delimiter characters, it’s unsuitable for escaping a complete URI. Instead, it’s useful for escaping strings before they are assembled into a URI—for example, the values of query parameters.

Special Case
  • If $uri-part is the empty sequence, the function returns a zero-length string.

Examples

The first example shows a typical use case, where a filename contains the separator % character and some spaces that need to be escaped. The second example shows the escaping of an entire URL by using this function, which can have undesired results. The escape-html-uri function would have been a better choice.

ExampleReturn value
encode-for-uri("Sales % Numbers.pdf") Sales%20%25%20Numbers.pdf
encode-for-uri("http://datypic.com/a%20URI#frag") http%3A%2F%2Fdatypic.com%2Fa%2520URI%23frag

ends-with

Determines whether one string ends with another

Signature
ends-with($arg1 as xs:string?, $arg2 as xs:string?,
          $collation as xs:string) as xs:boolean
Usage Notes

This function returns an xs:boolean value indicating whether one string ($arg1) ends with the characters of a second string ($arg2). Trailing whitespace is significant, so you may want to use the normalize-space function to trim the strings before using this function.

Special Cases
  • If $arg2 is a zero-length string or the empty sequence, the function returns true.

  • If $arg1 is a zero-length string or the empty sequence, but $arg2 is not, the function returns false.

  • If $collation is provided, the comparison uses that collation; otherwise, it uses the default collation. For more information, see “Collations”.

Examples
ExampleReturn value
ends-with("query", "y") true
ends-with("query", "query") true
ends-with("query", "") true
ends-with("query ", "y") false
ends-with("", "y") false

map:entry

Creates a map with a single entry

Signature
map:entry($key as xs:anyAtomicType, $value as item()*) as map(*)
Usage Notes

This function returns a map with a single entry, whose key is $key and whose value is $value. It is not particularly useful when constructing a map from a fixed number of entries; the map constructor described in “Constructing Maps” can do that. For example, the map constructor map { "ACC":"Accessories"} is equivalent to the function call map:entry("ACC", "Accessories").

The function is most useful when creating a map from a variable number of entries. It can be used with the map:merge function for this purpose, for example:

map:merge(doc("catalog.xml")//product !
map:entry(string(number), string(name)))

creates a map that contains an entry for each product, whose key is the product number and whose value is the name (both strings).

Special Case
  • This function is new in XQuery 3.1.

Examples

The examples assume this variable declaration:

declare variable $map1 := map {1:"first", 2:"second"};
ExampleReturn value
map:entry(1, "first") map {1:"first"}
map:merge( ($map1, map:entry(3, "third")) ) map {1:"first", 2:"second", 3:"third"}
map:merge( (map:entry(1, "first"), map:entry(2, "second")) ) map {1:"first", 2:"second"}
map:merge(doc("catalog.xml")//product ! map:entry(string(number), string(name))) map {"557":"Fleece Pullover", "563":"Floppy Sun Hat", "443":"Deluxe Travel Bag", "784":"Cotton Dress Shirt"}
Related Functions

map:put, map:merge

environment-variable

Returns the value of an environment variable

Signature
environment-variable($name as xs:string) as xs:string?
Usage Notes

This function is used to return the value of an environment variable based on its name. The available-environment-variables function can be used to get a list of the names of all the available environment variables. The definition of environment variable is processor- and platform-dependent.

Special Cases
  • If there is no environment variable with the name $name, the function returns the empty sequence.

  • This function is new in XQuery 3.0.

Example

When evaluating the function call environment-variable("JAVA_HOME") in a Windows environment, a standalone XQuery processor might return the value of that Windows environment variable, e.g., C:Program FilesJavajdk1.8.0_25.

error

Explicitly raises an error

Signature
error($code as xs:QName?, $description as xs:string,
      $error-object as item()*) as none
Usage Notes

This function allows you to stop execution of the query, with a specific error message. This is useful if an unexpected or invalid condition exists, such as a missing or invalid data item. You can incorporate calls to the error function in your query to signal such problems to the query user. For example:

if (not ($prod/number))
then error(QName("http://datypic.com/err", "ProdNumReq"),
           "Missing product number.")
else $prod/number

results in a ProdNumReq error if $prod has no number child.

How a processor will use the optional $description and $error-object arguments is implementation-dependent. Most processors will report the $description as part of the error message to the user.

Some processors may report the error name as a URI, where the local part is a fragment identifier, as in http://datypic.com/err#ProdNumReq.

The error function is the same function that the processor calls implicitly whenever there is an error during query evaluation. The return type of none is only used for the error function and is not available to query authors. It simply means that the error function never returns any value; evaluation of the query stops once the error function is called.

Remember that order of execution in XQuery is undefined. You can’t always rely on the fact that your error test will be evaluated before some other expression that it is designed to guard. In fact, you can’t always rely on the error expression being evaluated at all if, for example, it appears as part of a larger expression (perhaps a variable assignment) whose result is never used. However, simple cases such as if ($condition) then $value else error() should be safe.

Special Case
  • If $code is not provided, the error name defaults to FOER0000 (“Unidentified error”), in the http://www.w3.org/2005/xqt-errors namespace.

Examples

The second example assumes the prod prefix has been declared in the query.

Example
error()
error(xs:QName("prod:ProdNumReq"))
error(QName("http://datypic.com/err", "ProdNumReq"), "Missing number.")
error(QName("http://datypic.com/err", "ProdNumReq"), "Missing number.", $prod)
Related Function

trace

escape-html-uri

Escapes all non-ASCII characters in a string

Signature
escape-html-uri($uri as xs:string?) as xs:string
Usage Notes

HTML agents require that some URI characters be escaped with their hexadecimal Unicode codepoint preceded by the % character. This includes non-ASCII characters and some ASCII characters, namely control characters, spaces, and several others.

The escape-html-uri function replaces each of these special characters with an escape sequence in the form %xx (possible repeating), where xx is two hexadecimal digits (in uppercase) that represent the character in UTF-8. For example, édition.html is changed to %C3%A9dition.html, with the é escaped as %C3%A9. Specifically, it escapes everything except those ASCII characters whose decimal codepoint is between 32 and 126, inclusive. This allows these URIs to be appropriately handled by HTML agents such as web browsers, for example, in HTML href attributes.

The way this function is specified is a pragmatic compromise. HTTP requires special characters such as spaces to be escaped. However, HTML documents often contain URIs designed for local use within the browser—for example, JavaScript function calls—and these local URIs (which are never sent over HTTP) will often fail if spaces and other ASCII characters are escaped. This function therefore only escapes non-ASCII characters.

Special Case
  • If $uri is the empty sequence, the function returns a zero-length string.

Examples
ExampleReturn value
escape-html-uri("http://datypic.com/") http://datypic.com/
escape-html-uri("édition.html") %C3%A9dition.html
escape-html-uri("/datypic.com/a URI#frag") /datypic.com/a URI#frag
Related Functions

encode-for-uri, iri-to-uri

exactly-one

Verifies that a sequence contains exactly one item

Signature
exactly-one($arg as item()*) as item()
Usage Notes

This function returns $arg unchanged if it contains exactly one item. Otherwise, error FORG0005 is raised.

This function is useful when static typing is in effect, to avoid apparent static type errors. For example, to use a computed element constructor, you might be tempted to write the expression:

element {node-name($prod)}  { 563 }

However, if static typing is used, this expression causes a static error. This is because the node-name function returns 0 or 1 xs:QName values, while the computed element constructor requires that one and only one xs:QName value be provided. A static error can be avoided by using the expression:

element {exactly-one(node-name($prod))}  { 563 }

In this case, no static error is raised. Rather, a dynamic error is raised if node-name returns the empty sequence. For more information on static typing, see Chapter 15.

If static typing is NOT in effect, calling exactly-one is not usually necessary, but it does no harm. The effect is usually to make explicit a runtime type check that would otherwise have been done automatically.

Examples
ExampleReturn value
exactly-one( () ) Error FORG0005
exactly-one("a") a
exactly-one( ("a", "b") ) Error FORG0005

exists

Determines whether a sequence is not empty

Signature
exists($arg as item()*) as xs:boolean
Usage Notes

This function returns true if the sequence contains one or more items; it is the opposite of the empty function. It is often unnecessary to call the exists function because sequences are automatically converted to the effective boolean value where a Boolean value is expected. For example, if you want to test whether there are any product elements in catalog.xml, you can use the test expression:

if (doc("catalog.xml")//product)  then ...

In this case, the sequence of selected product elements is converted to the Boolean value true if the sequence is not empty, and false if the sequence is empty. There is no need to call the exists function to determine this. But beware: this only works for node sequences, not for atomic values.

Examples
ExampleReturn value
exists( ("a", "b", "c") ) true
exists("") true
exists( () ) false
exists(false()) true
Related Functions

empty, one-or-more

math:exp

Returns the value of ex, where x is the argument

Signature
math:exp($arg as xs:double?) as xs:double?
Usage Notes

This function returns the mathematical constant e (approximately 2.71828) raised to the power of $arg.

Special Cases
  • If $arg is the empty sequence, the function returns the empty sequence.

  • This function is new in XQuery 3.0.

Examples
ExampleReturn value
math:exp(0) 1
math:exp(1) 2.7182818284590455 (approximately)
math:exp(-1) 0.36787944117144233 (approximately)
Related Functions

math:exp10, math:pow

math:exp10

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

Signature
math:exp10($arg as xs:double?) as xs:double?
Usage Notes

This function returns the number 10 raised to the power of $arg.

Special Cases
  • If $arg is the empty sequence, the function returns the empty sequence.

  • This function is new in XQuery 3.0.

Examples
ExampleReturn value
math:exp10(-1) 0.1
math:exp10(0) 1
math:exp10(1) 10
Related Functions

math:exp, math:pow

false

Constructs a Boolean false value

Signature
false() as xs:boolean
Usage Notes

This function, which takes no arguments, is useful for constructing the Boolean value false. XQuery uses false() and true() function calls instead of keywords false and true. This is most commonly used to supply a value in a function call where a Boolean value is required.

Example

The expression false() returns the xs:boolean value false.

Related Functions

true, boolean

filter

Returns the items for which a supplied function returns true

Signature
filter($seq as item()*, $f as function(item()) as xs:boolean) as item()*
Usage Notes

This function returns those items in $seq for which the supplied function $f returns true. The order of the items is preserved. The supplied function must return one and only one boolean value. Calling the filter function is similar to using a predicate that calls a supplied function. For example:

let $f := starts-with#2
let $seq := ("ab", "aa", "xy")
return filter($seq, $f(?, "a"))

is equivalent to:

let $f := starts-with#2
let $seq := ("ab", "aa", "xy")
return $seq[$f(., "a")]

Both return the sequence ("ab", "aa") because those are the items that start with “a”. Using the filter function is stricter because the supplied function must return a boolean value, whereas in the second example the supplied function could return any sequence and it would be interpreted as an effective boolean value.

Special Cases
  • If $seq is the empty sequence, then the empty sequence is returned.

  • This function is new in XQuery 3.0, and only supported by implementations that support higher-order functions. If the function is called by a 3.0 processor but not supported, error XPST0017 will be raised.

Examples
ExampleReturn value
filter( ("ab", "aa", "xy"), starts-with#2(?, "a") ) ("ab", "aa")
filter( (4, 5, 6), function($n) {$n > 4}) (5, 6)
filter( (4, 5, 6), function($n) {$n > 6}) ()

array:filter

Returns the members of an array for whom a supplied function returns true

Signature
array:filter($array as array(*), 
             $function as function(item()*) as xs:boolean) as array(*)
Usage Notes

This function returns a new array containing those members of $array for which the function $function returns true. The order of the members is preserved. The function $function must return one and only one boolean value.

Special Cases
  • If $array is an empty array, an empty array is returned.

  • This function is new in XQuery 3.1, and only supported by implementations that support higher-order functions. If the function is called by a 3.1 processor but not supported, error XPST0017 will be raised.

Examples
ExampleReturn value
array:filter(["ab", "aa", "xy"], starts-with#2(?, "a")) ["ab", "aa"]
array:filter([4, 5, 6], function($n) {$n > 4}) [5, 6]
array:filter([4, 5, 6], function($n) {$n > 6}) []

map:find

Recursively searches a sequence for map entries with a particular key

Signature
map:find($input as item()*, $key as xs:anyAtomicType) as array(*)
Usage Notes

This function recursively searches $input for map entries whose key is $key and returns their values as an array. The $input sequence can contain any kind of items. If an array is included, each member of the array is then searched. If a map is included, the value of each map entry is searched. The search is recursive, so multiple levels of nested maps and arrays (e.g., maps within maps, or maps within arrays within map values) will be searched. Other items, such as atomic values or XML nodes, are ignored.

Special Cases
  • If $input is an empty sequence or an empty map or array, or no entries with the $key are found, the function returns an empty array.

  • This function is new in XQuery 3.1.

Examples

The examples assume these variable declarations:

declare variable $map1 := map {1:"first", 2:"second"};
declare variable $map2 := map {
    "A": map {1: "1-in-A"},
    "B": map {2: "2-in-B"},
    "C": map {1: "1-in-C"} 
    };
declare variable $array1 := [map {1:"1-in-array"}, 32];
ExampleReturn value
map:find($map1, 1) ["first"]
map:find(($map1, $map2), 1) ["first","1-in-A","1-in-C"]
map:find($array1, 1) ["1-in-array"]
map:find($array1, 3) []
map:find($map1, "first") [], because "first" is a map value, not a key
Related Functions

map:contains, map:get

array:flatten

Turns arrays into sequences

Signature
array:flatten($input as item()*) as item()*
Usage Notes

This function takes the $input items and removes arrays from them, replacing them with the members of the array as a sequence, in order. This is done recursively, so that if there are multiple levels of arrays, they are all removed. The result is a sequence of items at a single level.

Special Cases
  • If $input is the empty sequence, the function returns the empty sequence.

  • If $input does not contain any arrays, $input is returned unchanged.

  • This function is new in XQuery 3.1.

Examples
ExampleReturn value
array:flatten(["a", "b", "c"]) ("a", "b", "c")
array:flatten( (["a", "b"], ["c", "d"]) ) ("a", "b", "c", "d")
array:flatten( (["a", "b"], ["c", ["d"], ["e"]]) ) ("a", "b", "c", "d", "e")
array:flatten( ("a", "b", "c") ) ("a", "b", "c")

floor

Rounds a number down to the nearest lower integer

Signature
floor($arg as xs:numeric?) as xs:numeric?
Usage Notes

This function returns the largest whole number that is not greater than $arg. It returns a numeric value of type xs:float, xs:double, xs:decimal, or xs:integer, depending on which type the argument is derived from. If $arg is untyped, it is cast to xs:double.

Special Cases
  • If $arg is the empty sequence, the function returns the empty sequence.

  • If $arg is one of the values 0, -0, NaN, INF, or -INF, the function returns this same value.

Examples
ExampleReturn value
floor(5) 5
floor(5.1) 5
floor(5.7) 5
floor(-5.1) -6
floor(-5.7) -6
floor( () ) ()

fold-left

Applies a supplied function on a sequence from left to right, accumulating a result

Signature
fold-left($seq as item()*, $zero as item()*,
          $f as function(item()*, item()) as item()*) as item()*
Usage Notes

This function performs an operation (the function $f) on two items at a time, accumulating a result as it goes. It first calls the function using $zero as the first argument and the first item in $seq as the second argument. It then calls it a second time using the result of the previous function call as the first argument, and the second item in $seq as the second argument. It continues until there are no further items in $seq. For example, the function call:

fold-left(1 to 3, 0, function($a, $b) { $a + $b })

passes a function that adds the two values together. It adds 0 (the $zero argument) to 1, takes the result of that and adds it to 2, and takes the result of that and adds it to 3, finally returning 6.

For functions that perform associative operations such as addition, fold-left and fold-right return the same value.

Special Cases
  • If $seq is the empty sequence, $zero is returned.

  • This function is new in XQuery 3.0, and only supported by implementations that support higher-order functions. If the function is called by a 3.0 processor but not supported, error XPST0017 will be raised.

Examples
ExampleReturn value
fold-left(1 to 6, 0, function($a, $b) { $a + $b }) 21 (the sum of the numbers 1 through 6)
fold-left( ("a", "b", "c"), "",
function($a, $b) { concat($a, $b) })
"abc"
fold-left( ("a", "b", "c"), "",
function($a, $b) { concat($b, $a) })
"cba"
fold-left( ("a", "b", "c"), "x",
function($a, $b) { concat($a, '-', $b) })
"x-a-b-c"
fold-left( ("a", "b", "c"), "", concat(?, ?) ) "abc"
fold-left( (), 0, function($a, $b) { $a + $b }) 0

array:fold-left

Applies a supplied function on array members from left to right, accumulating a result

Signature
array:fold-left($array as array(*), $zero as item()*, 
                $function as function(item()*, item()*) as item()*) as item()*
Usage Notes

This function performs an operation (the function $function) on two arguments at a time (one of which is a member of $array), accumulating a result as it goes. It first applies the function to two values: taking $zero as the first argument, and the first member in $array as the second argument. It then calls it a second time, taking the result of the previous function call as the first argument, and the second member of $array as the second argument. It continues until there are no further members in $array. For example, the function call:

array:fold-left([1, 2, 3], 0, function($a, $b) { $a + $b })

passes a function that adds the two values together. It adds 0 (the $zero argument) to 1, takes the result of that and adds it to 2, and takes the result of that and adds it to 3, finally returning 6.

The array:fold-left function is similar to the fold-left function, but works on an array rather than a sequence. One consequence of that is that array:fold-left can operate on multiple items (since multiple items can be a single member of an array).

Special Cases
  • If $array is an empty array, $zero is returned.

  • This function is new in XQuery 3.1, and only supported by implementations that support higher-order functions. If the function is called by a 3.1 processor but not supported, error XPST0017 will be raised.

Examples
ExampleReturn value
array:fold-left([1, 2, 3, 4, 5, 6], 0,
function($a, $b) { $a + $b })
21 (the sum of the numbers 1 through 6)
array:fold-left(["a", "b", "c"], "",
function($a, $b) { concat($a, $b) })
"abc"
array:fold-left(["a", "b", "c"], "",
function($a, $b) { concat($b, $a) })
"cba"
array:fold-left(["a", "b", "c"], "x",
function($a, $b) { concat($a, '-', $b) })
"x-a-b-c"
array:fold-left( ["a", "b", "c"], "", concat(?, ?) ) "abc"
array:fold-left([], 0, function($a, $b) { $a + $b }) 0

fold-right

Applies a supplied function on a sequence from right to left, accumulating a result

Signature
fold-right($seq as item()*, $zero as item()*,
           $f as function(item(), item()*) as item()*) as item()*
Usage Notes

This function performs an operation (the function $f) on two items at a time, accumulating a result as it goes. It first calls the function, using the last item in $seq as the first argument and $zero as the second argument. It then calls it a second time, using the second to last item in $seq as the first argument and the result of the first function call as the second argument. It continues until there are no further items in $seq. For example, the function call:

fold-right(1 to 3, 0, function($a, $b) { $a + $b })

passes a function that adds the two values together. It adds 3 to 0 (the $zero argument), takes the result of that and adds it to 2, and takes the result of that and adds it to 1, finally returning 6.

For functions that perform associative operations such as addition, fold-left and fold-right return the same value.

Special Cases
  • If $seq is the empty sequence, $zero is returned.

  • This function is new in XQuery 3.0, and only supported by implementations that support higher-order functions. If the function is called by a 3.0 processor but not supported, error XPST0017 will be raised.

Examples
ExampleReturn value
fold-right(1 to 6, 0, function($a, $b) { $a + $b }) 21 (the sum of the numbers 1 through 6)
fold-right( ("a", "b", "c"), "",
function($a, $b) { concat($a, $b) })
"abc"
fold-right( ("a", "b", "c"), "",
function($a, $b) { concat($b, $a) })
"cba"
fold-right( ("a", "b", "c"), "x",
function($a, $b) { concat($a, '-', $b) })
"a-b-c-x"
fold-right( ("a", "b", "c"), "", concat(?, ?) ) "abc"
fold-right( (), 0, function($a, $b) { $a + $b }) 0

array:fold-right

Applies a supplied function on array members from right to left, accumulating a result

Signature
array:fold-right($array as array(*), $zero as item()*,
                 $function as function(item()*, item()*) as item()*) as item()*
Usage Notes

This function performs an operation (the function $function) on two arguments at a time (one of which is a member of $array), accumulating a result as it goes. It first applies the function to two values: taking the last member of $array as the first argument and $zero as the second argument. It then calls the function a second time, with the second-to-last member in $array as the first argument and the result of the previous function call as the second argument. It continues until there are no further members in $array. For example, the function call:

array:fold-right([1, 2, 3], 0, function($a, $b) { $a + $b })

passes a function that adds the two values together. It adds 3 to 0 (the $zero argument), takes the result of that and adds it to 2, and takes the result of that and adds it to 1, finally returning 6.

The array:fold-right function is similar to the fold-right function, but works on an array rather than a sequence. One consequence of that is that array:fold-right can operate on multiple items (since multiple items can be a single member of an array).

Special Cases
  • If $array is an empty array, $zero is returned.

  • This function is new in XQuery 3.1, and only supported by implementations that support higher-order functions. If the function is called by a 3.1 processor but not supported, error XPST0017 will be raised.

Examples
ExampleReturn value
array:fold-right([1, 2, 3, 4, 5, 6], 0,
function($a, $b) { $a + $b })
21 (the sum of the numbers 1 through 6)
array:fold-right(["a", "b", "c"], "",
function($a, $b) { concat($a, $b) })
"abc"
array:fold-right(["a", "b", "c"], "",
function($a, $b) { concat($b, $a) })
"cba"
array:fold-right(["a", "b", "c"], "x",
function($a, $b) { concat($a, '-', $b) })
"a-b-c-x"
array:fold-right( ["a", "b", "c"], "", concat(?, ?) ) "abc"
array:fold-right([], 0, function($a, $b) { $a + $b }) 0

for-each

Applies a supplied function to a sequence

Signature
for-each($seq as item()*, $action as function(item()) as item()*) as item()*
Usage Notes

This function applies the function $action to each of the items in $seq and concatenates all the results together in order. It is a shorthand that avoids having to use a FLWOR expression for simple cases. For example, for-each( ("a", "b"), $f) is equivalent to for $x in ("a", "b") return $f($x), where $f is a variable bound to a function.

Special Cases
  • If $seq is the empty sequence, the empty sequence is returned.

  • This function is new in XQuery 3.0, and only supported by implementations that support higher-order functions. If the function is called by a 3.0 processor but not supported, error XPST0017 will be raised.

Examples
ExampleReturn value
for-each( ("a", "b", "c"), upper-case(?)) ("A", "B", "C")
for-each( (0, 1, 2), function($a) { $a + 5 }) (5, 6, 7)

array:for-each

Applies a supplied function to every member in an array

Signature
array:for-each($array as array(*), 
               $action as function(item()*) as item()*) as array(*)
Usage Notes

This function applies the function $action to each of the members in $array. The result of the function is an array where each member is the result of calling the function $action once. It is a shorthand that avoids having to use a FLWOR expression for simple cases.

This function is similar to the for-each function except that it works on an array instead of a sequence.

Special Cases
  • If $array is an empty array, an empty array is returned.

  • This function is new in XQuery 3.1, and only supported by implementations that support higher-order functions. If the function is called by a 3.1 processor but not supported, error XPST0017 will be raised.

Examples
ExampleReturn value
array:for-each( ["a", "b", "c"],
function($x) {concat($x, "x")} )
["ax", "bx", "cx"]
array:for-each( ["a", "b", "c"],
function($x) {$x, "x"} )
[("a", "x"), ("b", "x"), ("c", "x")]
array:for-each( ["a", "b", "c"],
string-to-codepoints(?) )
[97, 98, 99]

map:for-each

Applies a supplied function to every entry in a map

Signature
map:for-each($map as map(*), 
           $action as function(xs:anyAtomicType, item()*) as item()*) as item()*
Usage Notes

This function applies the function $action to every entry in the map $map. The result of the map:for-each function is the concatenation of the results of the function in $action applied to each entry in the map. The order of the items in the result is implementation-dependent.

The $action function must accept two arguments. The first is the map key, and the second is the map value.

This function is similar to the for-each function except that it works on a map instead of a sequence.

Special Cases
  • If $map is an empty map, the empty sequence is returned.

  • This function is new in XQuery 3.1, and only supported by implementations that support higher-order functions. If the function is called by a 3.1 processor but not supported, error XPST0017 will be raised.

Examples

The examples assume this variable declaration:

declare variable $map1 := map {1:"first", 2:"second"};
ExampleReturn value
map:for-each($map1, function($k, $v) {concat($k, $v)}) ("1first", "2second")
map:merge(map:for-each($map1, function($k, $v) {map:entry($k + 1, $v)})) map {2:"first", 3:"second"}
Related Functions

array:for-each, for-each

for-each-pair

Applies a supplied function to pairs of items taken from two sequences

Signature
for-each-pair($seq1 as item()*, $seq2 as item()*,
              $action as function(item(), item()) as item()*) as item()*
Usage Notes

This function takes two sequences ($seq1 and $seq2) and applies the supplied function $action to pairs of values from each sequence. For example, if each of $seq1 and $seq2 contain three items, the supplied function will be called three times, first with the first item from $seq1 and the first item from $seq2, next with the second item from $seq1 and the second item from $seq2, and so on. The results of the function calls are concatenated in order.

Special Cases
  • If either $seq1 or $seq2 is the empty sequence, the empty sequence is returned.

  • If $seq1 and $seq2 contain a different number of items, the function is only applied as many times as there are items in the smaller sequence. For example, if $seq1 has three items and $seq2 has five items, the function is only applied three times.

  • This function is new in XQuery 3.0, and only supported by implementations that support higher-order functions. If the function is called by a 3.0 processor but not supported, error XPST0017 will be raised.

Examples
ExampleReturn value
for-each-pair( ("a", "b", "c"), ("x", "y", "z"), concat#2) ("ax", "by", "cz")
for-each-pair(1 to 5, 1 to 5, function($a, $b){$a * $b}) (1, 4, 9, 16, 25)
for-each-pair( ("a", "b", "c", "d", "e"), ("x", "y", "z"), concat#2) ("ax", "by", "cz")

array:for-each-pair

Applies a supplied function to pairs of members taken from two arrays

Signature
array:for-each-pair($array1 as array(*), $array2 as array(*),
                    $function as function(item()*, item()*) as item()*)
       as array(*)
Usage Notes

This function takes two arrays ($array1 and $array2) and applies the supplied function $function to pairs of members from each array. For example, if each of $array1 and $array2 contains three members, the supplied function will be called three times, first with the first member from $array1 and the first member from $array2, next with the second member from $array1 and the second member from $array2, and so on. The result is a new array that contains a member for the result of each call to the function.

This function is similar to the for-each-pair function except that it works on arrays instead of sequences.

Special Cases
  • If either $array1 or $array2 is an empty array, an empty array is returned.

  • If $array1 and $array2 contain a different number of members, the function is only applied as many times as there are members in the smaller array. For example, if $array1 has three members and $array2 has five members, the function is only applied three times.

  • This function is new in XQuery 3.1, and only supported by implementations that support higher-order functions. If the function is called by a 3.1 processor but not supported, error XPST0017 will be raised.

Examples
ExampleReturn value
array:for-each-pair(["a", "b", "c"], ["x", "y", "z"],
concat#2)
["ax", "by", "cz"]
array:for-each-pair(["a", "b", "c"], ["x", "y", "z"],
function($a, $b){$a, $b})
[("a", "x"), ("b", "y"), ("c", "z")]
array:for-each-pair([1, 2, 3, 4, 5], [1, 2, 3, 4, 5],
function($a, $b){$a * $b})
[1, 4, 9, 16, 25]
array:for-each-pair(["a", "b", "c", "d", "e"], ["x", "y", "z"], concat#2) ["ax", "by", "cz"]

format-date

Formats a date according to a picture string

Signature
format-date($value as xs:date?, $picture as xs:string,
            $language as xs:string?, $calendar as xs:string?,
            $place as xs:string?) as xs:string?
Usage Notes

This function formats the date $value according to the pattern $picture. Three additional arguments allow specification of a $language, $calendar, and $place. If any of these three arguments are specified, all must be present. In other words, the function accepts either two arguments or five arguments, but the empty sequence can be used as a placeholder.

Details on how these five arguments are interpreted is identical for the format-date, format-time, and format-dateTime functions. See the “format-dateTime” section for a detailed explanation of the arguments. The only difference is that format-date cannot use time-related component specifiers, namely H, h, P, m, s, and f.

Special Cases
  • If $value is the empty sequence, the function returns the empty sequence.

  • If $picture refers to time-related components like H, error FOFD1350 is raised.

  • If $picture or $calendar is invalid, error FOFD1340 is raised.

  • This function is new in XQuery 3.0.

Examples
ExampleReturn value
format-date(xs:date("2015-04-06"), "[M01]/[D01]/[Y0001]") 04/06/2015
format-date(xs:date("2015-04-06"), "[M]-[D]-[Y]") 4-6-2015
format-date(xs:date("2015-04-06"),
"[MNn] [D], [Y]", "en", (), () )
April 6, 2015
format-date(xs:date("2015-04-06"),
"[MNn] [D1o], [Y]", "en", (), () )
April 6th, 2015
format-date(xs:date("2015-04-06"),
"The [Dwo] day of [MNn], [Y]", "en", (), () )
The sixth day of April, 2015
format-date(xs:date("2015-04-06"),
"[D01] [MN,*-3] [Y0001]", "en", (), () )
06 APR 2015

format-dateTime

Formats a date/time according to a picture string

Signature
format-dateTime($value as xs:dateTime?, $picture as xs:string, 
                $language as xs:string?, $calendar as xs:string?,
                $place as xs:string?) as xs:string?
Usage Notes

This function formats the date/time $value according to the pattern $picture. Three additional arguments allow specification of a $language, $calendar, and $place. If any of these three arguments are specified, all must be present. In other words, the function accepts either two arguments or five arguments, but the empty sequence can be used as a placeholder.

The picture string contains variable markers, which appear in square brackets. Anything between the variable markers (outside square brackets) is considered a literal character and is copied to the formatted output unchanged. To escape a square bracket so that it can be used as a literal character, it can be doubled ([[ or ]]).

Each variable marker has up to three parts in between the square brackets:

  • A mandatory component specifier, which is one of the case-sensitive letters from the first column of Table A-6.

  • An optional one or two presentation modifiers. If not specified, the default value from the third column of Table A-6 is used.

  • An optional comma followed by a width modifier.

Table A-6. Components of the date/time picture string
SpecifierMeaningDefault presentation modifier
Y Year (absolute value) 1
M Month in year 1
D Day in month 1
d Day in year 1
F Day of week n
W Week in year 1
w Week in month 1
H Hour in day (24 hours) 1
h Hour in half-day (12 hours) 1
P AM/PM marker n
m Minute in hour 01
s Second in minute 01
f Fractional seconds 1
Z Time zone (ignored if the value has no time zone) 01:01
z Time zone with prefix GMT or equivalent, for example, GMT+1 or GMT-05:00 (ignored if the value has no time zone) 01:01
C Calendar name or abbreviation n
E Era, for example AD n

The presentation modifier, which comes directly after the component specifier, specifies how to format that component. For numeric values like day of the month, you can use the values allowed by the $picture argument to the format-integer function. For example, 0 (or 1, the digits are interchangeable) will simply format it as a number, 00 will pad it with zeros to make it two digits, and Ww indicates a word, like Two.

If the component is a day of the week, month of the year, time zone or era, it can also be spelled out as a name, for example Monday or JUNE. If the presentation modifier is n, it is all lowercase; if it is N, it is all uppercase; and if it is Nn, it is in title case.

To use ordinal numbers, for example 1st or First, the first presentation modifier can be followed by the letter o. The letters c (cardinal), a (alphabetic), and t (traditional) are also allowed, with the same meanings they have when used with the format-integer function.

The last part of a variable marker is a width modifier that indicates the allowed length of the output. It is separated from the rest of the variable marker with a comma, and indicates a minimum and maximum length separated by a hyphen. For example, ,3-4 indicates that it must be a minimum of three characters and a maximum of four. An asterisk can be used on either side of the hyphen to indicate that there is no minimum or maximum length. If no hyphen or maximum width is used, it means that there is no maximum length. One use for this is to abbreviate names, for example [MNn,3-3] outputs three-letter abbreviations for month names (Jan, Feb, etc.). Some implementations will use conventional abbreviations, while others simply truncate the value. For year components (Y), setting a width left-truncates the year, so if the year is 2015 and the variable marker is [Y,2-2], it is formatted as 15.

$language specifies the natural language to use when formatting words. It is used, for example, in names of days of the week, month names, and numbers expressed as words such as two. It should be a value as described by the xs:language type, with typical values being language codes like en (English) or de (German), optionally including a regional modifier like en-US (English, United States).

$calendar specifies the calendar to use to format the date.

$place specifies a place, which can allow for regional differences within a language. It is typically a country code, or an Olson Timezone name such as America/New_York.

The names of calendars and places, and how they affect the formatted dates, is implementation-defined. The documentation for your XQuery processor should list the options available to you. If a $language, $calendar, or $place is not recognized by the processor, it will not raise an error but will instead fall back to its default value and indicate that it did so at the beginning of the output string, for example:

format-dateTime(xs:dateTime("2015-05-31T12:00:00"),
                "[Mn]", "x-Klingon", (), () )

might return [Language: en]may if the processor does not recognize the language x-Klingon.

Special Cases
  • If $value is the empty sequence, the function returns the empty sequence.

  • If $picture or $calendar is invalid, error FOFD1340 is raised.

  • This function is new in XQuery 3.0.

Examples
ExampleReturn value
format-dateTime(xs:dateTime("2015-04-06T17:31:03"),
"[M01]/[D01]/[Y0001] at [H01]:[m01]:[s01]")
04/06/2015 at 17:31:03
format-dateTime(xs:dateTime("2015-04-06T17:31:03"),
"[h].[m01][Pn] on [FNn], [MNn] [D1o]")
5.31p.m. on Monday, April 6th
format-dateTime(xs:dateTime("2015-04-06T17:31:03"),
"[MNn] [D], [Y]", "en", (), () )
April 6, 2015

Additional examples are provided in the “format-date” and “format-time” sections.

Related Functions

format-date, format-time

format-integer

Formats an integer according to a picture string

Signature
format-integer($value as xs:integer?, $picture as xs:string, 
               $lang as xs:string?) as xs:string
Usage Notes

This function formats the integer $value according to the pattern $picture. This can be used to pad integers with leading zeros, insert grouping separators between segments of an integer, or convert integers to other formats like letters or Roman numerals. The $picture has two parts: the primary format token and the format modifier. They are separated by a semicolon. The primary format token can be a decimal digit pattern, which has three parts:

  1. A “#” character that represents an optional digit

  2. A number that represents a mandatory digit (any number in the digit family can be used; they are interchangeable)

  3. A grouping separator that is anything other than a letter or number

For example, the pattern 0000 represents four mandatory digits, so the result will contain at least four digits (padding with leading zeros, if necessary). The pattern #,##0 uses the optional digit sign #, which does not insert leading zeros but causes a comma to be inserted between each group of three digits that is present. Optional digits are only needed to show the placement of the grouping separator; otherwise they have no effect. There are several rules regarding the placement of the three parts of the decimal digit pattern:

  • At least one mandatory digit must be present.

  • All mandatory digits must be from the same digit family (i.e., the same 10 consecutive codepoints defined by Unicode).

  • Optional digits (if present) must appear before mandatory digits.

  • A grouping separator must not appear at the beginning or end of the pattern, or next to another grouping separator.

As an alternative to the decimal digit pattern, the primary format token can instead be one of the following values:

Format tokenMeaningSequence (in English)
a Lowercase letters a b c ... z aa ab ac....
A Uppercase letters A B C ... Z AA AB AC....
i Lowercase Roman numerals i ii iii iv v vi vii viii ix x ....
I Uppercase Roman numerals I II III IV V VI VII VIII IX X ....
W Uppercase words ONE TWO THREE FOUR ...
w Lowercase words one two three four ...
Ww Initial uppercase words One Two Three Four ...

The primary format token can optionally be followed by a semicolon and a format modifier, which can have three parts, in order:

  1. One of the letters c (for cardinal, the default) or o (for ordinal). If the letter o is specified, ordinal numbers such as 1st and 2nd are used, rather than cardinal numbers like 1 and 2.

  2. An optional implementation-defined sequence of characters in parentheses that allow other possible variations of cardinal and ordinal numbering sequences.

  3. One of the letters a (for alphabetic) or t (for traditional). This is not used in English, but in some languages it is necessary to distinguish between two numbering sequences that use letters.

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

  • If $picture has an invalid format, error FODF1310 is raised.

  • This function is new in XQuery 3.0.

Examples
ExampleReturn value
format-integer(123, '0000') 0123
format-integer(123, '00') 123
format-integer(12345678, '#,##0') 12,345,678
format-integer(4, 'a') d
format-integer(4, 'i') iv
format-integer(4, 'Ww', 'en') Four
format-integer(15, '0;o') 15th
format-integer(15, 'Ww;o', 'de') Fünfzehnte
Related Function

format-number

format-number

Formats a number according to a picture string

Signature
format-number($value as xs:numeric?, $picture as xs:string, 
              $decimal-format-name as xs:string?) as xs:string
Usage Notes

This function formats the number $value according to the pattern $picture and the decimal format $decimal-format-name. It can be used to format values of any numeric type, but for integers it may be best to use the format-integer function, because of its support for different number styles.

$picture can be used to pad numbers with leading or trailing zeros, insert grouping separators between segments of a number, or show numbers with exponents. For example, the pattern 0000 represents four mandatory digits, so the result will contain at least four digits (padding with leading zeros, if necessary). The pattern #,##0 uses the optional digit sign #, which will not insert leading zeros but will cause a comma to be inserted between each group of three digits that is present.

There are a variety of characters that can be specified in the picture string. Each is listed here with its default value in parentheses.

Decimal separator (“.”)

Separates the integer part of the number from the fractional part, sometimes referred to as a decimal point. It can be used in both the picture string (to indicate its position) and in the formatted number. For example, the picture string 00.00 causes the number 12.5 to be formatted as 12.50. If no decimal separator appears in the picture string, the number will be rounded according to the rules of the round-half-to-even function.

Grouping separator (“,”)

Separates groups of numbers, typically used as a thousands separator. It can be used in both the picture string (to indicate its position) and in the formatted number. For example, the picture string #,##0 causes the number 12345 to be formatted as 12,345. A larger number like 123456789 is formatted with a grouping separator separating every three digits (123,456,789), using the same picture string; it is not necessary to put multiple grouping separators in the picture string. If no grouping separator appears in the picture string, none will appear in the formatted number.

Mandatory (zero) digit (“0”)

Used in a picture string to indicate a mandatory digit. If the number being formatted has fewer digits than there are mandatory digits in the picture string, zeros are padded. Leading zeros may be added for mandatory digits to the left of the decimal separator, and trailing zeros may be added for mandatory digits to the right. For example, the picture string 000.00 will cause the number 18 to be formatted as 018.00. Although zero (“0”) is commonly used, actually using any digit in the same family will have the same effect. The picture string 123.45 would work equally well in the previous example, although it is less clear.

Optional digit (“#”)

Used in a picture string to indicate an optional digit. It is only useful if used in conjunction with a grouping separator, to indicate how many digits should be in each group. For example, in the picture string #,##0.00, the optional digit character is used to create three characters between the grouping separator and the decimal separator, so that the processor knows to group the number in sets of three digits.

Pattern separator (“;”)

Divides a picture string into two parts, the first to handle positive numbers and the second to handle negative numbers. For example, the picture string #,##0.00;(#,##0.00) could be used to surround negative currency amounts with parentheses as is done in financial statements. If there is no pattern separator, negative numbers are formatted just like positive numbers, except that they are preceded by a minus sign.

Percent sign (“%”)

Used in a picture string to indicate that the number should be multiplied by 100. It also indicates the position of the percent sign in the results (either at the beginning or the end). For example, the picture string 0% will cause the number 0.18 to be formatted as 18%.

Per-mille sign (“‰”)

Used in a picture string to indicate that the number should be multiplied by 1000. It also indicates the position of the per-mille sign in the results (either at the beginning or the end). For example, the picture string 0‰ will cause the number 0.018 to be formatted as 18‰.

Exponent separator (“e”)

Used in a picture string to indicate that the number should be formatted using scientific notation. For example, the picture string 00.0e0 will cause the number 1234 to be formatted as 12.3e2. To be effective, the exponent separator must be between digit characters.

Any other characters

Any other characters not listed above can also appear in the picture string. These characters will be considered “passive” characters that should just be copied to the formatted output. For example, the picture string a000z will cause the number 18 to be formatted as a018z. These other characters must appear at the beginning and/or the end, not between any of the other special characters described.

You can override the default values for any of these properties by using a decimal format declaration. The decimal format declaration, described in “The Decimal Format Declaration”, appears in the prolog and sets values for any or all of the special characters. It can also override how the minus sign, the value NaN, and the value INF appear in the formatted results.

It is possible to specify a default decimal declaration, which is used by the two-argument version of the format-number. If you need to format numbers multiple different ways in the same query, you can also name your decimal format declarations and pass that name to the format-number function as the third $decimal-format-name argument.

Special Cases
  • If $value is the empty sequence or NaN, the NaN symbol specified in the decimal format is returned.

  • If $picture has an invalid format, error FODF1310 is raised.

  • If $decimal-format-name is omitted, the default decimal declaration is used.

  • If $decimal-format-name is not a known decimal format, error FODF1280 is raised. A decimal format by that name must be declared using a decimal format declaration.

  • This function is new in XQuery 3.0.

Examples

The following examples assume that the query does not contain a decimal format declaration; all the properties use their default values.

ExampleReturn value
format-number(12, '0000') 0012
format-number(12, '0000.00') 0012.00
format-number(12345.6, '#,###.00') 12,345.60
format-number(12345.6, '#,###') 12,346 (result is rounded)
format-number(12344.5, '#,###') 12,344 (result is rounded to nearest even number)
format-number(123456789, '#,###') 123,456,789 (only one grouping separator is needed)
format-number(-1, "#,##0.00") -1.00
format-number(-1, "#,##0.00;(#,##0.00)") (1.00)
format-number(-12, '000') -012
format-number(0.18, '0%') 18%
format-number(0.018, '0‰') 18‰
format-number(1234.5678, '00.000e0') 12.346e2
format-number(12, 'Number: 0') Number: 12

To override the default values and reverse the decimal separator and grouping separator, you can use a decimal format declaration. For example, the following query:

declare default decimal-format decimal-separator="," grouping-separator=".";
format-number(12345.6, '#.###,00')

will return 12.345,60, where the two characters are switched in both the picture string and in the formatted number.

Related Function

format-integer

format-time

Formats a time according to a picture string

Signature
format-time($value as xs:time?, $picture as xs:string,
            $language as xs:string?, $calendar as xs:string?,
            $place as xs:string?) as xs:string?
Usage Notes

This function formats the time $value according to the pattern $picture. Three additional arguments allow specification of a $language, $calendar, and $place. If any of these three arguments are specified, all must be present. In other words, the function accepts either two arguments or five arguments, but the empty sequence can be used as a placeholder.

Details on how these five arguments are interpreted is identical for the format-time, format-date, and format-dateTime functions. See the “format-dateTime” section for a detailed explanation of the arguments. The only difference is that format-time cannot use date-related component specifiers, namely Y, M, D, d, F, W, and w.

Special Cases
  • If $value is the empty sequence, the function returns the empty sequence.

  • If $picture refers to date-related components like Y, error FOFD1350 is raised.

  • If $picture or $calendar is invalid, error FOFD1340 is raised.

  • This function is new in XQuery 3.0.

Examples
ExampleReturn value
format-time(xs:time("17:31:03"), "[h]:[m] [PN]") 5:31 P.M.
format-time(xs:time("17:31:03"), "[H]:[m]") 17:31
format-time(xs:time("17:31:03.234"),
"[h01]:[m]:[s].[f001]")
05:31:03.234
format-time(xs:time("17:31:03-05:00"),
"[h]:[m]:[s] [PN] [z]")
5:31:03 P.M. GMT-05:00
format-time(xs:time("17:31:03-05:00"),
"[h]:[m]:[s] [PN] [ZN,*-3]", "en", (), () )
5:31:03 P.M. EST

function-arity

Returns the arity of a supplied function

Signature
function-arity($func as function(*)) as xs:integer
Usage Notes

This function returns the number of arguments (arity) of the function $func. If it is a partially applied function, the arity will be the number of placeholders, not the total number of arguments to be passed to that function.

Special Case
  • This function is new in XQuery 3.0, and only supported by implementations that support higher-order functions. If the function is called by a 3.0 processor but not supported, error XPST0017 will be raised.

Examples
ExampleReturn value
function-arity(concat#4) 4
function-arity(function($a, $b){$a + $b}) 2
function-arity(substring(?, 1, 1)) 1
function-arity(substring(?, ?, ?)) 3

function-lookup

Returns the function having a given name and arity

Signature
function-lookup($name as xs:QName, $arity as xs:integer) as function(*)?
Usage Notes

This function will return the function with the name $name and the arity $arity. This function is useful when it is necessary in a query to decide which of several functions (if any) to use. This might be, for example, because the query might be run with processors supporting different versions, because it needs to react dynamically at runtime to user-provided options, or because it may need to run with different library modules depending on the situation.

Special Cases
  • If there is no function with the specified name and arity, the function will return the empty sequence.

  • This function is new in XQuery 3.0, and only supported by implementations that support higher-order functions. If the function is called by a 3.0 processor but not supported, error XPST0017 will be raised.

Examples
ExampleReturn value
function-lookup(xs:QName('fn:substring'), 2) substring#2
function-lookup(xs:QName('fn:substring'), 3)("abc", 2, 1) "b"
function-lookup(xs:QName('fn:substring'), 12) ()

The following query checks if the functx:is-a-number function is available, calls it if it is available, but uses an alternate expression if it is not available:

let $myValue := "12345"
let $f := fn:function-lookup(xs:QName('functx:is-a-number'), 1)
return if (exists($f))
       then $f($myValue)
       else ($myValue castable as xs:double)

function-name

Returns the name of a supplied function

Signature
function-name($func as function(*)) as xs:QName?
Usage Notes

This function returns the name of the function $func.

Special Cases
  • If $func is anonymous, the empty sequence is returned.

  • This function is new in XQuery 3.0, and only supported by implementations that support higher-order functions. If the function is called by a 3.0 processor but not supported, error XPST0017 will be raised.

Examples
ExampleReturn value
function-name(concat#4) A QName whose namespace is http://www.w3.org/2005/xpath-functions and whose local part is concat
function-name(function($a, $b){$a + $b}) ()

generate-id

Returns a unique identifier for a node

Signature
generate-id($arg as node()?) as xs:string
Usage Notes

This function returns a unique identifier for a node. The format of the identifier and algorithm for generating it are implementation-dependent, but it will always start with a letter and contain only alphanumeric characters, meaning that it is a syntactically valid XML name. During any given execution of a query, calling generate-id with the same node will always yield the same result.

This function is useful any time unique identifiers need to be artificially generated. One example is creating links in the query results. A query can make multiple passes at a document and use the unique identifiers to create hyperlinks in the results, as shown in the “Example” section.

Special Cases
  • If $arg is the empty sequence, the function returns a zero-length string.

  • If $arg is not provided, the context item is used. In this case, it is an error if the context item is absent (XPDY0002) or not a node (XPTY0004).

  • This function is new in XQuery 3.0.

Example

The query in Example A-3 generates an HTML document that lists all the products in the catalog, with a table of contents at the beginning. The generate-id function is called twice for each product: once when generating the table of contents, to create a link to the product section, and once when generating the product section, to provide the target for that link. The generated IDs shown (d0e3, d0e15, etc.) are those generated by Saxon for this example; other implementations would generate different IDs.

In this simple case, it would also be possible to use a sequential number for each product by using an at expression in the for clause. However, for more complex cases, generate-id can be very useful in this type of linking scenario.

Example A-3. Using generate-id

Query

<html>
  <body>
    <h1>Table of Contents</h1>
    {for $prod in doc("catalog.xml")//product
     return <p><a href="#{generate-id($prod)}">{data($prod/number)}</a></p>}
  
    <h1>Product Info</h1>
    {for $prod in doc("catalog.xml")//product
     return 
      (<h2 id="{generate-id($prod)}">{data($prod/number)}</h2>,
       <p>Name: {data($prod/name)}, Dep: {data($prod/@dept)}</p>)}
  </body>
</html>

Results

<html>
   <body>
     <h1>Table of Contents</h1>
     <p><a href="#d0e3">557</a></p>
     <p><a href="#d0e15">563</a></p>
     <p><a href="#d0e24">443</a></p>
     <p><a href="#d0e33">784</a></p>
     <h1>Product Info</h1>
     <h2 id="d0e3">557</h2>
     <p>Name: Fleece Pullover, Dep: WMN</p>
     <h2 id="d0e15">563</h2>
     <p>Name: Floppy Sun Hat, Dep: ACC</p>
     <h2 id="d0e24">443</h2>
     <p>Name: Deluxe Travel Bag, Dep: ACC</p>
     <h2 id="d0e33">784</h2>
     <p>Name: Cotton Dress Shirt, Dep: MEN</p>
   </body>
</html>

array:get

Gets the value at the specified position in an array

Signature
array:get($array as array(*), $position as xs:integer) as item()*
Usage Notes

This function returns the member in position $position in the array $array. Arrays in XQuery are 1-based, meaning that the position of the first member is 1, not 0 as in some other programming languages.

An alternative to using the array:get function is to invoke the array as a function, for example, $array1(2) is equivalent to array:get($array1, 2). It is also possible to use the lookup operator (?) on arrays, for example, $array1?2. These alternatives are described in “Looking Up Array Values”.

Special Cases
  • If the position specified does not exist in the array, for example, if the array has three members and the fourth one is requested, error FOAY0001 is raised. The size of the array can be determined by calling array:size.

  • This function is new in XQuery 3.1.

Examples

The examples assume these variable declarations:

declare variable $array1 := ["abc", "def", "ghi"];
declare variable $array2 := ["abc", [10, 20]];
ExampleReturn value
array:get($array1, 2) "def"
array:get($array2, 2) [10, 20]
array:get($array2, 3) Error FOAY0001
Related Function

array:subarray

map:get

Gets the value associated with the specified key in a map

Signature
map:get($map as map(*), $key as xs:anyAtomicType) as item()*
Usage Notes

This function returns the value associated with the key $key in the map $map. It compares the keys in a type-aware manner, for example the string "1" is not the same as the integer 1.

An alternative to using this function is to invoke the map as a function. For example, map:get($mymap, 1) is the same as $mymap(1). It is also possible to use the lookup operator (?) on maps, for example, $mymap?1. These alternatives are described in “Looking Up Map Values”.

Special Cases
  • If $key is not present as a key in $map, the function returns the empty sequence. However, a return value of the empty sequence could also mean that the key is present but its associated value was the empty sequence. Invoking the map:contains function will distinguish the two scenarios.

  • If $key has a type that is not comparable to the types of the keys of the map, for example, $key is a string but the keys of $map are integers, the function returns the empty sequence rather than returning an error.

  • If $key is untyped, it is compared to the keys of the map as a string value.

  • When strings are compared, they are compared as Unicode codepoints only; the default collation is not used.

  • This function is new in XQuery 3.1.

Examples

The examples assume this variable declaration:

declare variable $map1 := map {3:"first", 4:"second", 5:()};
ExampleReturn value
map:get($map1, 3) "first"
map:get($map1, 5) (), because that is the value associated with the key 5
map:get($map1, 6) (), because there is no key 6 in the map
map:get($map1, "3") (), because the string "3" is not equal to the integer 3

has-children

Determines whether a node has children

Signature
has-children($node as node()?) as xs:boolean
Usage Notes

This function returns true if a node has any child nodes. This includes child element nodes, text nodes (even ones that are all whitespace), processing instructions, and comments. The expression has-children($n) is equivalent to exists($n/node()), but calling has-children could be faster using some processors. The main purpose of this function is to support streaming in XSLT, but it can be used for convenience in XQuery also.

Special Cases
  • If $node is the empty sequence, the function returns false.

  • If $node is not provided, the context item is used. In this case, it is an error if the context item is absent (XPDY0002) or not a node (XPTY0004).

  • This function is new in XQuery 3.0.

Examples
ExampleReturn value
has-children(doc("catalog.xml")) true
has-children(doc("catalog.xml")//product[1]/name) true (it has a text node child)
has-children(doc("catalog.xml")//product[1]/name/text()) false
has-children(<empty-el/>) false

head

Returns the first item in a sequence

Signature
head($arg as item()*) as item()?
Usage Notes

This function returns the first item in a sequence.

Special Cases
  • If $arg is the empty sequence, the function returns the empty sequence.

  • This function is new in XQuery 3.0.

Examples
ExampleReturn value
head( ("a", "b", "c" ) ) "a"
head("a") "a"
head(1 to 3) 1
head(doc("catalog.xml")//product) The first product

array:head

Returns the first member of an array

Signature
array:head($array as array(*)) as item()*
Usage Notes

This function returns the first member of $array. It is equivalent to $array(1) or array:get($array, 1).

Special Cases
  • If the array is empty, error FOAY0001 is raised.

  • This function is new in XQuery 3.1.

Examples
ExampleReturn value
array:head(["abc", "def", "ghi"]) "abc"
array:head(["abc"]) "abc"
array:head([]) Error FOAY0001

hours-from-dateTime

Gets the hour portion of a date/time

Signature
hours-from-dateTime($arg as xs:dateTime?) as xs:integer?
Usage Notes

This function returns the hour portion of an xs:dateTime value, as an integer between 0 and 23, inclusive.

Special Cases
  • If $arg is the empty sequence, the function returns the empty sequence.

  • If the time portion of $arg is 24:00:00, the function will return 0.

Examples
ExampleReturn value
hours-from-dateTime(xs:dateTime("2015-08-15T10:30:23")) 10
hours-from-dateTime(xs:dateTime("2015-08-15T10:30:23-05:00")) 10
Related Function

hours-from-time

hours-from-duration

Gets the number of hours in a duration

Signature
hours-from-duration($arg as xs:duration?) as xs:integer?
Usage Notes

This function calculates the hours component of an xs:duration value, as an integer between -23 and 23 (inclusive). This is not necessarily the same as the integer that appears before the H in the value. For example, if the duration is PT1H90M, the function returns 2 rather than 1. This is because 90 minutes is equal to 1.5 hours, and the canonical value is therefore PT2H30M. Likewise, if the duration is PT36H, the result is 12, because the canonical value is P1DT12H.

Special Cases
  • If $arg is a negative duration, the function returns a negative value.

  • If $arg is the empty sequence, the function returns the empty sequence.

Examples
ExampleReturn value
hours-from-duration(xs:duration("P1DT5H")) 5
hours-from-duration(xs:duration("-PT36H")) -12
hours-from-duration(xs:duration("PT1H90M")) 2
hours-from-duration(xs:duration("PT2H59M")) 2
hours-from-duration(xs:duration("PT3600S")) 1
hours-from-duration(xs:duration("P1Y")) 0

hours-from-time

Gets the hour portion of a time

Signature
hours-from-time($arg as xs:time?) as xs:integer?
Usage Notes

This function returns the hour portion of an xs:time value, as an integer between 0 and 23, inclusive.

Special Cases
  • If $arg is the empty sequence, the function returns the empty sequence.

  • If $arg is 24:00:00, the function returns 0.

Examples
ExampleReturn value
hours-from-time(xs:time("10:30:23")) 10
hours-from-time(xs:time("10:30:23-05:00")) 10
Related Function

hours-from-dateTime

id

Returns elements that have a specified ID value or attribute

Signature
id($arg as xs:string*, $node as node()) as element()*
Usage Notes

Given a sequence of IDs ($arg), this function returns the elements with those IDs. If $node is not provided, the function looks for elements in the same document as the current context item. If $node is provided, the function looks for elements in the same document as $node.

The strings in the $arg sequence can either be individual ID values or space-separated lists of ID values. Although $arg is a sequence of xs:string values, you can also pass values of type xs:IDREF or xs:IDREFS, since these types are derived from xs:string.

An element is considered by the id function to have a particular ID if either:

  • It has an attribute, that is marked as an ID, that has that ID value.

  • The type of the element itself is marked as an ID and its content is that particular ID value.

This behavior is in contrast with the element-with-id function, which, in the latter case returns the parent of that element that is an ID.

An element or attribute node can become “marked as an ID” by being validated by a schema where it is declared as having type xs:ID, or (for an attribute) being described in a DTD as being of type ID. Also, if it is an attribute named xml:id, it is automatically considered to be an ID.

The function returns the nodes in document order, not the order designated by the sequence of $arg values. The result sequence contains no duplicate elements, even if an ID value was included twice in $arg.

Working with IDs and IDREFs is discussed in further detail in “Working with IDs”.

Special Cases
  • Any values in $arg that are not lexically valid IDs (i.e., XML NCNames) are ignored, even if there is an element with that invalid ID.

  • If there is no element with the specified ID, an error is not raised, but no element is returned for that ID value.

  • In the case of an invalid (but well-formed) document where more than one element has the same ID, the function returns the first element with that ID.

  • If $arg is the empty sequence, the function returns the empty sequence.

  • If no matching elements are found, the function returns the empty sequence.

  • If $node is not provided, the context item is used. In this case, it is an error if the context item is absent (XPDY0002) or not a node (XPTY0004).

  • Error FODC0001 is raised if $node is not part of a document (its root is not a document node).

Examples

These examples use the input document book.xml shown in Example A-4. It is assumed that the input document has been validated and that the type of the id attribute is xs:ID.

ExampleReturn value
doc("book.xml")/id("preface") The first section element
doc("book.xml")/id( ("context", "preface") ) The first two section elements, in document order
doc("book.xml")/id("context preface") The first two section elements, in document order
doc("book.xml")//section[3]/secRef/id(@refs) The second section element
doc("book.xml")//section[4]/secRef/id(@refs) The second and third section elements
doc("book.xml")//secRef/id(@refs) The second and third section elements
doc("book.xml")/ id( ("preface", "noMatch", "in!valid") ) The first section element
Example A-4. XML document with IDs and IDREFs (book.xml)
<book>
  <section id="preface">This book introduces XQuery...
    The examples are downloadable<fnref ref="fn1"/>...
  </section>
  <section id="context">...</section>
  <section id="language">...Expressions, introduced
   in <secRef refs="context"/>, are...
  </section>
  <section id="types">...As described in
    <secRef refs="context language"/>, you can...
  </section>
  <fn fnid="fn1">See http://datypic.com.</fn>
</book>
Related Functions

idref, element-with-id

idref

Finds references to a specified set of IDs

Signature
idref($arg as xs:string*, $node as node()) as node()*
Usage Notes

This function returns the nodes (elements or attributes) that reference one of a specified sequence of IDs ($arg). If $node is not provided, the function looks for elements and attributes in the same document as the current context item. If $node is provided, the function looks for elements and attributes in the same document as $node.

In order to be considered to reference an ID, the node must be marked as an IDREF or IDREFS type, and it must contain that ID value. Generally, this means that it was declared to be of type xs:IDREF or xs:IDREFS in an in-scope schema definition (or the equivalent in a DTD). If it is an IDREFS value, only one of the values in the list need match the ID.

The function returns the nodes in document order, not the order designated by the sequence of $arg values. The result sequence contains no duplicate elements, even if an ID value was included twice in $arg. However, there may be several elements or attributes in the results that reference the same ID.

Note that if the IDREF value is contained in an attribute, the function returns the attribute node, not the containing element. This is designed to handle cases where an element has more than one IDREF attribute and you need to know which one matched.

Special Cases
  • Any values in $arg that are not lexically valid IDs (i.e., XML NCNames) are ignored, even if there is an element with a matching invalid IDREF.

  • If $arg is the empty sequence, the function returns the empty sequence.

  • If no matching nodes were found, the function returns the empty sequence.

  • If $node is not provided, the context item is used. In this case, it is an error if the context item is absent (XPDY0002) or not a node (XPTY0004).

  • Error FODC0001 is raised if $node is not part of a document (its root is not a document node).

Working with IDs and IDREFs is discussed in further detail in “Working with IDs”.

Examples

These examples use the input document book.xml shown in Example A-4. It is assumed that the input document has been validated, that the type of the id and fnid attributes is xs:ID, the type of the ref attribute is xs:IDREF, and the type of the refs attribute is xs:IDREFS.

ExampleReturn value
doc("book.xml")/idref("language") The refs attribute of the second secRef element
doc("book.xml")/idref("context") The refs attributes of both secRef elements
doc("book.xml")/idref( ("context", "language") ) The refs attributes of both secRef elements
doc("book.xml")//fn[1]/idref(@fnid) The ref attribute of the fnref element
doc("book.xml")/idref( ("language", "noMatch", "in!valid") ) The refs attribute of the second secRef element
Related Functions

id, element-with-id

implicit-timezone

Gets the implicit time zone used by the processor

Signature
implicit-timezone() as xs:dayTimeDuration
Usage Notes

This function returns the implicit time zone as an xs:dayTimeDuration value. The implicit time zone is used in comparisons and calculations involving date and time values that do not have explicitly defined time zones.

The implicit time zone is implementation-defined. In practice, it will often default to the time zone used by the system clock in the operating system, or perhaps it will depend on the locale of the individual user.

Example

implicit-timezone() returns -PT5H if the implicit time zone is UTC minus five hours (represented as -05:00 in date/time values).

in-scope-prefixes

Lists all namespace prefixes that are in the scope of a specified element

Signature
in-scope-prefixes($element as element()) as xs:string*
Usage Notes

This function returns a sequence of prefixes (as strings) that are used in the in-scope namespaces for $element. The results include a zero-length string if there is a default namespace declaration. It also always includes the xml prefix, which is built into the XML recommendation.

Note that the function uses in-scope namespaces, as opposed to statically known namespaces. That is, it returns information about the namespaces declared in the source document, not the namespaces declared in the query. The difference between in-scope and statically known namespaces is described further in “In-Scope Versus Statically Known Namespaces”. More on working with namespaces and qualified names can be found in “Working with Qualified Names”.

Example

The query:

in-scope-prefixes(<prefList xmlns="http://datypic.com/prod"
   xmlns:prod2="http://datypic.com/prod2">xyz</prefList>)

returns the sequence ("", "prod2", "xml") in some arbitrary order.

index-of

Determines where (and whether) an atomic value appears in a sequence

Signature
index-of($seq as xs:anyAtomicType*, $search as xs:anyAtomicType,
         $collation as xs:string) as xs:integer*
Usage Notes

This function returns a sequence of integers representing the position(s) of the value $search within the sequence $seq, in order, starting with 1 (not 0).

The items in $seq are compared to those in $search by their typed value, not their name or node identity. If either sequence contains nodes, those nodes are atomized to extract their atomic values. Untyped values are treated like strings.

Special Cases
  • If $search cannot be compared with a value in $seq, for example, because $search is a string and $seq contains an integer, it will not match that value, but it will not raise an error.

  • If the $search value does not appear in $seq, the function returns the empty sequence.

  • If $seq is the empty sequence, the function returns the empty sequence.

  • If $collation is provided, the comparison uses that collation to compare string values; otherwise, it uses the default collation. For more information, see “Collations”.

Examples
ExampleReturn value
index-of( ("a", "b", "c"), "a") 1
index-of( ("a", "b", "c"), "d") ()
index-of( (4, 5, 6, 4), 4) (1, 4)
index-of( (4, 5, 6, 4), 04.0) (1, 4)
index-of( ("a", 5, 6), "a") 1
index-of( (), "a") ()
index-of( (<a>1</a>, <b>1</b>), <c>1</c> ) (1, 2)
Related Function

position

innermost

Returns the nodes in a sequence that are not ancestors of any other nodes in the sequence

Signature
innermost($nodes as node()*) as node()*
Usage Notes

This function returns those nodes in $nodes that are not ancestors of other nodes in $nodes. In other words, innermost($nodes) is equivalent to $nodes except $nodes/ancestor::node. The nodes are returned in document order.

The main purpose of this function is to support streaming in XSLT, but it can be used for convenience in XQuery also. For example, if your document has section elements within section elements, you can get the innermost (lowest-level) section elements by specifying innermost(//section). Calling the function with all elements in a document returns only the leaf-level elements in the document.

Special Cases
  • If $nodes is the empty sequence, the function returns the empty sequence.

  • This function is new in XQuery 3.0.

Examples

Given the input document:

<div class="example">
  <div>
    <p>Example 1-1:</p>
    <div class="listing">
      <p>Example goes here</p>
    </div>
  </div>
</div>

calling innermost(//div) will return the div that has no div descendants, namely the one whose class is listing.

The function call innermost(doc("catalog.xml")//*) returns a sequence of the 11 leaf nodes in the document, number, name, etc. The last item in the sequence will be the i element, not the desc element.

Related Function

outermost

insert-before

Inserts items into a sequence

Signature
insert-before($target as item()*, $position as xs:integer,
              $inserts as item()*) as item()*
Usage Notes

This function returns a sequence containing all the items of $target, plus the item(s) in $inserts inserted at the position indicated by $position. Position numbers start at 1, not 0.

Special Cases
  • If $inserts is the empty sequence, the function returns the $target sequence.

  • If $target is the empty sequence, the function returns the $inserts sequence.

  • If $position is greater than the number of items in $target, the $inserts items are appended to the end.

  • If $position is less than 1, the $inserts items are inserted at the beginning.

Examples
ExampleReturn value
insert-before( ("a", "b", "c"), 1, ("x", "y") ) ("x", "y", "a", "b", "c")
insert-before( ("a", "b", "c"), 2, ("x", "y") ) ("a", "x", "y", "b", "c")
insert-before( ("a", "b", "c"), 10, ("x", "y") ) ("a", "b", "c", "x", "y")
insert-before( ("a", "b", "c"), 0, ("x", "y") ) ("x", "y", "a", "b", "c")
insert-before( ("a", "b", "c"), 2, () ) ("a", "b", "c")
insert-before( (), 3, ("a", "b", "c") ) ("a", "b", "c")

array:insert-before

Inserts a member into an array at the specified position

Signature
array:insert-before($array as array(*), $position as xs:integer,
                    $member as item()*) as array(*)
Usage Notes

This function creates an array that contains all the members of $array, plus the items in $member inserted as a new member at the position $position. To insert at the end of the array, the $position can be one greater than the number of members in the array.

Special Cases
  • If $position is less than 1, or greater than the size of $array + 1, error FOAY0001 is raised. The size of the array can be determined by calling array:size.

  • If $member is a sequence of multiple items, each item does not become a member. A single member is inserted whose value is the sequence of all the items in $member.

  • If $member is an array, the entire array becomes a single member of the outer array; the two arrays are not merged.

  • If $member is the empty sequence, a member is still added to the array, whose value is the empty sequence.

  • This function is new in XQuery 3.1.

Examples

The examples assume this variable declaration:

declare variable $array1 := ["abc", "ghi", "jkl"];
ExampleReturn value
array:insert-before($array1, 2, "def") ["abc", "def", "ghi", "jkl"]
array:insert-before($array1, 4, "mno") ["abc", "ghi", "jkl", "mno"]
array:insert-before($array1, 4, ("mno", "pqr") ) ["abc", "ghi", "jkl", ("mno", "pqr")]
array:insert-before($array1, 6, "mno") Error FOAY0001
array:insert-before($array1, 0, "aaa") Error FOAY0001

iri-to-uri

Applies URI escaping rules to a string

Signature
iri-to-uri($iri as xs:string?) as xs:string
Usage Notes

URIs require that some characters be escaped with their hexadecimal Unicode codepoint preceded by the % character. This includes non-ASCII characters and some ASCII characters, namely control characters, spaces, and several others.

The iri-to-uri function replaces each special character with an escape sequence in the form %xx (possible repeating), where xx is two hexadecimal digits (in uppercase) that represent the character in UTF-8. For example, édition.html is changed to %C3%A9dition.html, with the é escaped as %C3%A9.

All characters except the following are escaped:

  • Letters a through z and A through Z

  • Digits 0 through 9

  • Hyphen (-), underscore (_), period (.), exclamation point (!), tilde (~), asterisk (*), apostrophe ('), parentheses (“(” and “)”), and hash mark (#)

  • Semicolon (;), forward slash (/), question mark (?), colon (:), at sign (@), ampersand (&), equals sign (=), plus sign (+), dollar sign ($), comma (,), square brackets ([ and ]), and percent sign (%)

The last set of characters specified in the preceding list is generally used to delimit parts of URIs. If you are escaping a single step of a URI path (as opposed to an entire URI), it is better to use the encode-for-uri function, which does escape these characters.

Special Case
  • If $iri is the empty sequence, the function returns a zero-length string.

Examples
ExampleReturn value
iri-to-uri ("http://datypic.com/édition 2.html") http://datypic.com/%C3%A9dition%202.html
iri-to-uri ("http://datypic.com/Sales Numbers.pdf") http://datypic.com/Sales%20Numbers.pdf
iri-to-uri ("http://datypic.com/Sales % Numbers.pdf") http://datypic.com/Sales%20%%20Numbers.pdf

array:join

Concatenates a number of arrays

Signature
array:join($arrays as array(*)*) as array(*)
Usage Notes

This function concatenates the members of $arrays into a single array. The order of the members is retained, based on their position in the argument.

Special Cases
  • If $arrays is the empty sequence, an empty array is returned.

  • This function is new in XQuery 3.1.

Examples

The examples assume these variable declarations:

declare variable $array1 := ["abc", "def", "ghi"];
declare variable $array2 := [1, 2, 3];
ExampleReturn value
array:join( ($array1, $array2) ) ["abc", "def", "ghi", 1, 2, 3]
array:join( ($array2, $array1) ) [1, 2, 3, "abc", "def", "ghi"]
array:join( ($array2, $array1, [4, 5]) ) [1, 2, 3, "abc", "def", "ghi", 4, 5]
array:join( ($array1, []) ) ["abc", "def", "ghi"]
array:join( () ) [ ]
array:join( [ ] ) [ ]

json-doc

Opens a JSON input document based on its URI

Signature
json-doc($href as xs:string?, $options as map(*)) as item()?
Usage Notes

This function opens a JSON resource associated with the URI $href and parses it to create an item, generally a map or array. Details of how JSON constructs are mapped to XQuery maps and arrays are provided in “Parsing JSON”.

Calling json-doc is equivalent to calling the unparsed-text function and then applying the parse-json function to the result. The rules for how the function resolves the URI in $href are described in “Resolving URIs of input documents”.

If there is any doubt about whether the JSON document exists or is correctly encoded, it is advisable to call the unparsed-text-available function before this function to avoid fatal errors.

$options is a map that controls how escaped characters, duplicate keys, and deviations from JSON are handled. It is described in detail in the “parse-json” section, since it allows the exact same values, with the same behaviors, as the $options parameter for parse-json.

Special Cases
  • If $href is the empty sequence, the function returns the empty sequence.

  • Any of the error conditions listed for the unparsed-text and parse-json functions may also be raised by this function.

  • This function is new in XQuery 3.1.

Example

Given the following input document called product.json:

{
   "number": 557,
   "name": "Fleece Pullover",
   "colorChoices": ["navy", "black"],
   "is-current": true,
   "other": null
}

The function call json-doc("product.json") will return a map equivalent to the document, as in:

map {
   "number": xs:double(557),
   "name": "Fleece Pullover",
   "colorChoices": ["navy", "black"],
   "is-current": true(),
   "other": ()
}

json-to-xml

Converts JSON to XML

Signature
json-to-xml($json-text as xs:string?, $options as map(*)) as document-node()?
Usage Notes

This function takes a string that is in JSON syntax and parses it to create an XML document node. The resulting XML has elements such as map, array, and string to structure the original content. Details of how JSON constructs are mapped to XML are provided in “Converting Between JSON and XML”.

To read JSON from a file, this function can be used in conjunction with the unparsed-text function.

$options is a map with the following possible entries (all of them optional), whose keys are strings:

liberal

Boolean value indicating whether deviations from the JSON syntax are allowed. The default is false. If the value is true, an implementation may choose to ignore certain recoverable deviations from the JSON syntax, such as omitting quotes around keys or allowing leading zeros in numbers.

duplicates

String indicating how the function should handle duplicate keys in a JSON object. If the value is reject (the default if validate is true), and duplicate keys are encountered, error FOJS0003 is raised. If the value is use-first, the first of the duplicate entries is retained. If the value is retain (the default unless validate is true), the duplicate entries are retained in the XML.

validate

Boolean value indicating whether the generated XML should be schema-validated. The default is implementation-defined.

escape

Boolean value indicating whether special characters are escaped in the result. If the value is false (the default), special characters are not escaped. If the value is true, JSON escapes (preceded by backslashes) are used for special characters in the result XML. For example, the letter é is escaped as u00E9. In this case, any string element in the generated XML that contains a JSON-escaped value will have an attribute escaped="true". Any element in the generated XML that has a key attribute that contains a JSON-escaped value will have an attribute escaped-key="true". This setting controls the escaping of special characters in the result, regardless of whether the characters were escaped in the input JSON.

fallback

A function item that is to be called if the input contains an escape sequence that represents an invalid character in XML. The function’s signature must be function(xs:string) as xs:string. For example, the function function($s){"ERROR!!"} would insert the string ERROR!! if it encountered such a character. If this function is not provided, the Unicode replacement character (&#xFFFD;) is inserted.

Additional implementation-defined options can be included in the $options map.

Special Cases
  • If $json-text is the empty sequence, the function returns the empty sequence.

  • If $json-text does not conform to the JSON grammar, error FOJS0001 is raised. An exception is that if the liberal option is set to true and the implementation can handle the anomaly, it will not raise an error.

  • If $options contains an invalid value, error FOJS0005 is raised.

  • If $options contains an entry "duplicates": "reject" and duplicates are encountered, error FOJS0003 is raised.

  • If $options contains an entry "validate": true() and the processor does not support schema validation, error FOJS0004 is raised.

  • This function is new in XQuery 3.1.

Examples

A simple example of calling the json-to-xml function with no options is shown in Example A-5.

Example A-5. A simple call to json-to-xml

Query

xquery version "3.1";
json-to-xml('{
   "number": 557,
   "name": "Fleece Pullover",
   "colorChoices": ["navy", "black"],
   "is-current": true,
   "other": null
}')

Results

<map xmlns="http://www.w3.org/2005/xpath-functions">
  <number key="number">557</number>
  <string key="name">Fleece Pullover</string>
  <array key="colorChoices">
    <string>navy</string>
    <string>black</string>
  </array>
  <boolean key="is-current">true</boolean>
  <null key="other"/>
</map>

A more complex example that uses the $options argument is shown in Example A-6. This example specifies some of the options with default values (unnecessarily) just to show the appropriate syntax. Duplicate names appear in a JSON object, and the first one is used as specified by the "duplicates": "use-first" entry.

Escape sequences in the strings in colorChoices show the escaping behavior. u00E9 is a valid escape sequence and is converted to the character é because of the "escape": false() entry. uFFFF is an invalid character in XML, so the fallback function is called and the text ERROR!! is inserted in place of the escape sequence.

Example A-6. Calling json-to-xml with options

Query

xquery version "3.1";
json-to-xml('{
   "number": 557,
   "name": "Fleece Pullover",
   "name": "Fleece Pullover Redux",
   "colorChoices": ["navy u00E9", "black uFFFF"],
   "is-current": true,
   "other": null
}',
map {"duplicates": "use-first",
  "liberal": false(),
  "validate": false(),
  "escape": false(),
  "fallback": function($s){"ERROR!!"}})

Results

<map xmlns="http://www.w3.org/2005/xpath-functions">
  <number key="number">557</number>
  <string key="name">Fleece Pullover</string>
  <array key="colorChoices">
    <string>navy é</string>
    <string>black ERROR!!</string>
  </array>
  <boolean key="is-current">true</boolean>
  <null key="other"/>
</map>

map:keys

Returns all the keys in a map

Signature
map:keys($map as map(*)) as xs:anyAtomicType*
Usage Notes

This function returns a sequence of atomic values that are used as keys in the $map. The order of the result sequence is in implementation-dependent order, since there is no order associated with the entries in a map.

Special Cases
  • If $map is empty, the empty sequence is returned.

  • This function is new in XQuery 3.1.

Examples
ExampleReturn value
map:keys( map {1:"first", 2:"second"} ) (1, 2) (in implementation-dependent order)
map:keys( map {"a":"first"} ) "a"
map:keys( map {} ) ()
Related Functions

map:size, map:contains

lang

Tests whether the language of a node matches a specified language

Signature
lang($testlang as xs:string?, $node as node()) as xs:boolean
Usage Notes

The language of a node is determined by the existence of an xml:lang attribute on the node itself or among its ancestors. The lang function can be used on any node, not just one containing string values. It is often used in the predicates of path expressions to filter data for a particular language.

$testlang specifies the language to test. The function returns true if the relevant xml:lang attribute of $node has a value that matches $testlang. The function returns false if the relevant xml:lang attribute does not match $testlang, or if there is no relevant xml:lang attribute.

The relevant xml:lang attribute is the one that appears as an attribute of the node itself, or of one of its ancestors. If more than one xml:lang attribute can be found among the node and its ancestors, the nearest one applies.

The matching process is case-insensitive. If $testlang is en, it matches the xml:lang value EN, and vice versa. Also, the value of the xml:lang attribute can be a sublanguage of the $testlang value. For example, en-US, en-UK, and en-US-UK are all sublanguages of en. Therefore, if $testlang is en, and xml:lang is en-US, the node will be matched. This does not work in reverse; if $testlang is en-US, and xml:lang is en, it will not match.

More information on the format of languages can be found in xs:language.

Special Cases
  • If $testlang is the empty sequence, it is treated like a zero-length string.

  • If $node is not provided, the context item is used. In this case, it is an error if the context item is absent (XPDY0002) or not a node (XPTY0004).

  • If no xml:lang attributes exist on the ancestors of a node, the function will return false.

Examples

These examples make use of the input document descs.xml shown in Example A-7.

ExampleReturn value
doc("descs.xml")//desc[lang("en")] The first desc element
doc("descs.xml")//desc[lang("en-US")] The first desc element
doc("descs.xml")//desc[lang("fr")] The second desc element
doc("descs.xml")//desc/line[lang("en")] The first line element
doc("descs.xml")/desclist[lang("en-US")] ()
doc("descs.xml")//desc[lang("FR")] The second desc element
Example A-7. Document with xml:lang attributes specified (descs.xml)
<desclist xml:lang="en">
  <desc xml:lang="en-US">
    <line>The first line of the description.</line>
  </desc>
  <desc xml:lang="fr">
    <line>La premi&#232;re ligne de la déscription.</line>
  </desc>
</desclist>

last

Gets the number of items in the current context

Signature
last() as xs:integer
Usage Notes

This function returns an integer representing the number of items in the current context. It is most often used in the predicate of path expressions, to retrieve the last item. For example:

doc("catalog.xml")/catalog/product[last()]

returns the last product child of catalog. That is because the last function returns 4, which serves as a positional predicate to retrieve the fourth product. The last function is also useful for testing whether an item is the last one in the sequence.

Special Case
  • If the context item is absent, error XPDY0002 is raised.

Examples

doc("catalog.xml")/catalog/product[last()] returns the last product child of catalog. Example A-8 demonstrates how you might test whether an item is the last one in the sequence. It shows a query that returns a list of all the product numbers, separated by commas. However, after the last product number, it includes a period rather than a comma. It uses the last function and an is expression to compare each product element to the last one in the catalog.

Example A-8. Example of the last function

Query

let $catalog := doc("catalog.xml")/catalog
for $prod in $catalog/product
return concat($prod/number,
            (if ($prod is $catalog/product[last()]) then (".") else (", ")) )

Results

557, 563, 443, 784.
Related Function

position

load-xquery-module

Loads a library module

Signature
load-xquery-module($module-uri as xs:string, $options as map(*)) as map(*)
Usage Notes

This function loads one or more XQuery library modules in order to allow access to its variables and functions. The $module-uri parameter passed to the function is the target namespace of the module(s), as opposed to the location. If $options is not provided, it is assumed that the processor knows where to locate the modules for that target namespace.

Calling this function has some benefits over using a module import declaration in the prolog. The function allows you to dynamically pass a context item, and values for external variables. It also allows modules to be loaded dynamically, only if they are needed.

The result of the function is a map that has two entries whose keys are the strings variables and functions, and whose values are maps. The variables map contains entries for each public global variable from the library module, where the key is the variable name (as an xs:QName) and the value is the variable value. The functions map contains entries for each unique function name in the library module, where the key is the function name (as an xs:QName) and the value is itself a map. This map contains an entry for each arity associated with that function name, where the key is the arity (as an xs:integer), and the value is a function item that can be dynamically invoked.

$options is a map that has the following possible entries (all of them optional), whose keys are strings:

KeyType of valueDescription
location-hints xs:string* A sequence of strings representing the locations (URIs) of the modules.
context-item item()? The item that will serve as the initial context item for the library module. This may affect the evaluation of global variables.
variables map(xs:QName, item()*) A map whose entries each provide a value for an external variable in the library module, where the key of the entry is the namespace-qualified name of the variable.
xquery-version xs:decimal The minimum version of the XQuery language that the processor must support. The default is the version specified in the prolog of the library module.
vendor-options map(xs:QName, item()*) A map containing vendor-defined configuration options for the function. The keys of the entries should be in the vendor-controlled namespace in order to be recognized.

Additional implementation-defined options can be included in the $options map.

Special Cases
  • If $module-uri is a zero-length string, error FOQM0001 is raised.

  • If $module-uri specifies a target namespace for which no module can be found, error FOQM0002 is raised.

  • If the function encounters a static error when trying to load a library module, error FOQM0003 is raised. This could be because the library module is syntactically incorrect or has static type errors.

  • If the function tries to dynamically load a module, but provides a type-invalid or missing value for the initial context item (by using a context-item entry in $options), error FOQM0005 is raised.

  • If the function tries to dynamically load a module, but provides a type-invalid or missing value for an external variable (by using a variables entry in $options), error FOQM0005 is raised.

  • If no suitable XQuery processor can be found, error FOQM0006 is raised. This might be because no processor was found, or the processor does not support the specified version, or the processor does not support the Module Feature.

  • This function is new in XQuery 3.1, and is only implemented by processors that support the Module Feature.

Examples

A simple library module is shown in Example A-9. It has one global variable and one function declaration.

Example A-9. A library module (strings.xqm)
module namespace strings = "http://datypic.com/strings";
declare variable $strings:maxStringLength := 32;
declare function strings:trim($arg as xs:string?) as xs:string? {
  replace(replace($arg,'^s+',''),'s+$','')
};

A simple call to the load-xquery-module function that loads this module, with no special options, is shown in Example A-10. It assumes that the processor knows where to find the module with the namespace http://datypic.com/strings and that no location hint is necessary.

To retrieve the strings:trim function, it uses lookup operators to traverse through the map returned by load-xquery-module (bound to $library). For clarity, an equivalent map is shown in the example. In the return clause of the query, the library function is called dynamically, and the resulting string is returned.

Example A-10. A simple call to load-xquery-module

Query

xquery version "3.1";
declare namespace strings = "http://datypic.com/strings";
let $library := load-xquery-module("http://datypic.com/strings")
let $trimFunction := $library?functions?(xs:QName("strings:trim"))?1
return $trimFunction("   x   y   ")

Equivalent value of $library

map {
  "variables": map{
                 xs:QName("strings:maxStringLength"): 32
                },
  "functions": map{
                 xs:QName("strings:trim"): map{
                     1: strings:trim#1 
                   }
                }
}

Results

x   y

For a more complex example, consider the library module shown in Example A-11, which has two global variables and two function declarations with the same name but different arity.

Example A-11. Library module that is dynamically loaded (lib2.xqm)
xquery version "3.1";
module namespace prod = "http://datypic.com/prod";
declare context item as element(catalog) external;
declare variable $prod:label as xs:string external;
declare variable $prod:prods as element(product)* := product;
declare function prod:countProds ($prods as element(product)*) as xs:string
  {concat($prod:label, ': ', count($prods))};
declare function prod:countProds ($prods as element(product)*, 
                                  $dept as xs:string) as xs:string
  {concat($prod:label, ': ', count($prods[@dept = $dept]))};

Example A-12 shows a query that loads this library module. It uses the $options map to specify the context item and the initial value for an external variable.

Example A-12. A more complex call to load-xquery-module

Query

xquery version "3.1";
declare namespace prod = "http://datypic.com/prod";
let $library := 
  load-xquery-module("http://datypic.com/prod",
                     map {"context-item": doc("catalog.xml")/catalog,
                          "location-hints": "lib2.xqm",
                          "variables": map{
                            xs:QName("prod:label") : "Product Count"}
                     })
let $prodsVariableValue := $library?variables?(xs:QName("prod:prods"))
let $countProdArity1 := $library?functions?(xs:QName("prod:countProds"))?1
return $countProdArity1($prodsVariableValue)

Equivalent value of $library

map {
  "variables": map{
                 xs:QName("prod:label"): "Product Count",
                 xs:QName("prod:prods"): doc("catalog.xml")/catalog/product
                },
  "functions": map{xs:QName("prod:countProds"): map{
                     1: prod:countProds#1,
                     2: prod:countProds#2 
                    }
                }
}

Results

Product Count: 4

local-name

Gets the local part of a node name, as a string

Signature
local-name($arg as node()?) as xs:string
Usage Notes

This function is useful only for element, attribute, and processing instruction nodes. For an element or attribute, this is simply its local name, which is stripped of any prefix it might have.

To find elements with a particular local name, instead of writing a/*[local-name()='nnn'], you can write a/*:nnn. However, the predicate test is useful if the name you are looking for is variable.

Special Cases
  • If $arg is not provided, the context item is used. In this case, it is an error if the context item is absent (XPDY0002) or not a node (XPTY0004).

  • The function returns a zero-length string if:

    • $arg is the empty sequence.

    • $arg is a node that does not have a name (i.e., a comment, document, or text node).

  • If $arg is a processing instruction node, the function returns its target.

Examples

These examples use the input document names.xml shown in Example A-13. They assume the following namespace declarations in the query prolog:

declare namespace pre = "http://datypic.com/pre";
declare namespace unpre = "http://datypic.com/unpre";
ExampleReturn value
local-name(doc("names.xml")//noNamespace) noNamespace
local-name(doc("names.xml")//pre:prefixed) prefixed
local-name(doc("names.xml")//unpre:unprefixed) unprefixed
local-name(doc("names.xml")//@pre:prefAttr) prefAttr
local-name(doc("names.xml")//@noNSAttr) noNSAttr
Example A-13. XML document with namespaces (names.xml)
<noNamespace>
  <pre:prefixed xmlns="http://datypic.com/unpre"
                xmlns:pre="http://datypic.com/pre">
    <unprefixed pre:prefAttr="a" noNSAttr="b">123</unprefixed>
  </pre:prefixed>
</noNamespace>

local-name-from-QName

Gets the local part of a QName

Signature
local-name-from-QName($arg as xs:QName?) as xs:NCName?
Usage Notes

This function returns the local part of an xs:QName. If you want to retrieve the local part of an element or attribute name, you should consider using the local-name function instead; it requires one less step.

Special Case
  • If $arg is the empty sequence, the function returns the empty sequence.

Examples
ExampleReturn value
local-name-from-QName(QName("http://datypic.com/prod", "number")) number
local-name-from-QName(QName ("", "number")) number
local-name-from-QName( () ) ()

math:log

Returns the natural logarithm

Signature
math:log($arg as xs:double?) as xs:double?
Usage Notes

This function returns the natural logarithm of $arg.

Special Cases
  • If $arg is the empty sequence, the function returns the empty sequence.

  • If $arg is less than or equal to zero, the result is NaN.

  • This function is new in XQuery 3.0.

Examples
ExampleReturn value
math:log(1.0e-3) -6.907755278982137 (approximately)
math:log(math:exp(1)) 1
math:log(-1) NaN
Related Function

math:log10

math:log10

Returns the base-ten logarithm

Signature
math:log10($arg as xs:double?) as xs:double?
Usage Notes

This function returns the base-10 logarithm of $arg.

Special Cases
  • If $arg is the empty sequence, the function returns the empty sequence.

  • If $arg is less than or equal to zero, the result is NaN.

  • This function is new in XQuery 3.0.

Examples
ExampleReturn value
math:log10(1e3) 3
math:log10(2) 0.3010299956639812 (approximately)
math:log10(-1) NaN
Related Function

math:log

lower-case

Converts a string to lowercase

Signature
lower-case($arg as xs:string?) as xs:string
Usage Notes

This function returns $arg, converted to lowercase letters. The mappings between lowercase and uppercase characters are determined by Unicode case mappings. If a character in $arg does not have a corresponding lowercase character, it is included in the result string unchanged.

For English, you can do a case-blind comparison by writing lower-case($A)=lower-case($B) (or use upper-case instead). However this doesn’t always work well for other languages. It’s better to use a case-insensitive collation.

Special Case
  • If $arg is the empty sequence, the function returns a zero-length string.

Examples
ExampleReturn value
lower-case("QUERY") query
lower-case("Query") query
lower-case("QUERY123") query123
Related Function

upper-case

matches

Determines whether a string matches a pattern

Signature
matches($input as xs:string?, $pattern as xs:string,
        $flags as xs:string) as xs:boolean
Usage Notes

This function returns true if $input matches $pattern, which is a regular expression, whose syntax is covered in Chapter 19. Unless the anchors ^ or $ are used, the function returns true if any substring of $input matches the regular expression.

The $flags parameter allows for additional options in the interpretation of the regular expression. It is discussed in detail in “Using Flags”.

Special Cases
  • If $input is the empty sequence, it is treated like a zero-length string.

  • If $pattern is a zero-length string, the function will return true.

  • If $pattern is not a valid regular expression, error FORX0002 is raised.

  • If $flags contains unsupported options, error FORX0001 is raised.

Examples
ExampleReturn value
matches("query", "q") true
matches("query", "ue") true
matches("query", "^qu") true
matches("query", "qu$") false
matches("query", "[ux]") true
matches("query", "q.*") true
matches("query", "[a-z]{5}") true
matches( (), "q" ) false
matches("query", "[qu") Error FORX0002

Additional examples that use the $flags argument can be found in Table 19-14.

max

Returns the maximum of the values in a sequence

Signature
max($arg as xs:anyAtomicType*, $collation as xs:string) as xs:anyAtomicType?
Usage Notes

This function returns the maximum value in $arg, which is a sequence that can only contain values of one type, or of types derived from it. The one exception is that they can be all numeric (of different numeric types), in which case numeric promotion rules apply. That type must be ordered; it must be possible to compare the values by using the < and > operators.

This function assumes untyped values are numeric unless they are explicitly cast to xs:string. To treat untyped data as strings, use the string function as shown in the last example.

The max function returns an atomic value, not the node that contains that value. For example, the expression:

max(doc("catalog.xml")//number)

will return the number 784, not the number element that contains 784.

Special Cases
  • If $arg is the empty sequence, the function returns the empty sequence.

  • If $arg contains the value NaN, the function returns NaN.

  • If $arg contains untyped values that cannot be cast to xs:double, error FORG0001 is raised.

  • If $arg contains values of a type that does not support the < and > operators, error FORG0006 is raised.

  • If $arg contains values of various types (and they are not all numeric), error FORG0006 is raised. The exception is that xs:anyURI values can be intermingled with xs:string values.

  • If $arg contains a date or time with no time zone, it is given the implicit time zone.

  • If $collation is provided, the function uses that collation to compare string values; otherwise, the default collation is used. For more information, see “Collations”.

Examples
ExampleReturn value
max( (2, 1, 5, 4, 3) ) 5
max( ("a", "b", "c") ) c
max( (xs:date("1999-04-15"), current-date()) ) The current date
max( ("a", "b", 1) ) Error FORG0006
max(2) 2
max(doc("order.xml")//item/@dept) Error FORG0001, if dept is untyped
max(doc("order.xml")//item/string(@dept)) WMN
Related Function

min

map:merge

Combines the entries from a number of maps

Signature
map:merge($maps as map(*)*, $options as map(*)) as map(*)
Usage Notes

This function returns a map that has all the combined entries of the maps in $maps. Keys are compared in a type-aware fashion, for example the key "1" (a string) is different from the key 1 (an integer).

$options is a map that has only one possible entry (optional), whose key is the string duplicates, which controls what to do if there is a duplicate key among the maps in $maps. Its possible values are the strings:

reject

The error FOJS0003 is raised.

use-first

The first duplicate is used; all others are discarded. This is the default value.

use-last

The last duplicate is used; all others are discarded.

use-any

Any of duplicates is used (it is implementation-dependent); all others are discarded.

combine

The values of the duplicate keys are concatenated into a single sequence.

Special Cases
  • If $maps is the empty sequence, an empty map is returned.

  • If $options is omitted, and duplicate keys exist among the $maps, the first value is used.

  • If $options is a map with a value other than those listed above for duplicates, error FOJS0005 is raised.

  • This function is new in XQuery 3.1.

Examples

The examples assume these variable declarations:

declare variable $map1 := map {1:"first", 2:"second"};
declare variable $map2 := map {1:"ONE", "abc":"def"};
declare variable $map3 := map {"1":"first", "2":"second"};
ExampleReturn value
map:merge( ($map1, $map2) ) map {1:"first", 2:"second", "abc":"def"}
map:merge( ($map2, $map1) ) map {1:"ONE", 2:"second", "abc":"def"}
map:merge( ($map1, $map3) ) map {1:"first", 2:"second", "1":"first", "2":"second"}
map:merge( ($map1, $map2, $map3) ) map {1:"first", 2:"second", "abc":"def", "1":"first", "2":"second"}
map:merge( ($map1, map{3:"third"}) ) map {1:"first", 2:"second", 3:"third"}
map:merge( ($map1, map{2:"second-new"}) ) map {1:"first", 2:"second"}
map:merge( ($map1, map:entry(2, "second-new")) ) map {1:"first", 2:"second"}
map:merge( ($map1) ) map {1:"first", 2:"second"}
map:merge( ($map1, $map2), map{"duplicates":"use-last"} ) map {1:"ONE", 2:"second", "abc":"def"}
map:merge( ($map1, $map2), map{"duplicates":"combine"} ) map {1:("first","ONE"), 2:"second", "abc":"def"}
map:merge( ($map1, $map2), map{"duplicates":"reject"} ) Error FOJS0003
map:merge( () ) map {}
Related Functions

map:put, map:entry

min

Returns the minimum of the values in a sequence

Signature
min($arg as xs:anyAtomicType*, $collation as xs:string) as xs:anyAtomicType?
Usage Notes

This function returns the minimum value in $arg, which is a sequence that can only contain values of one type, or a type derived from it. The one exception is that they can be all numeric, in which case numeric promotion rules apply. That type must be ordered; it must be possible to compare the values by using the < and > operators.

This function assumes untyped values are numeric unless they are explicitly cast to xs:string. To treat untyped data as strings, use the string function as shown in the last example.

The min function returns an atomic value, not the node that contains that value. For example, the expression:

min(doc("catalog.xml")//number)

will return the number 443, not the number element that contains 443.

Special Cases
  • If $arg is the empty sequence, the function returns the empty sequence.

  • If $arg contains untyped values that cannot be cast to xs:double, error FORG0001 is raised.

  • If $arg contains values of a type that does not support the < and > operators, error FORG0006 is raised.

  • If $arg contains values of various types (and they are not all numeric), error FORG0006 is raised. The exception is that xs:anyURI values can be intermingled with xs:string values.

  • If $arg contains a date or time with no time zone, it is assumed to be in the implicit time zone.

  • If $collation is provided, the function uses that collation to compare string values; otherwise, the default collation is used. For more information, see “Collations”.

Examples
ExampleReturn value
min( (2.0, 1, 3.5, 4) ) 1
min( ("a", "b", "c") ) a
min(doc("order.xml")//item/@color) Error FORG0001, if color is untyped
min(doc("order.xml")//item//string(@color)) ""
min(doc("order.xml")//item/@color/string(.)) black

Note that the last example evaluates to black because the string function is only called for existing color attributes. The second-to-last example returns a zero-length string because it finds the string value of every item’s color attribute, whether it has one or not.

Related Function

max

minutes-from-dateTime

Gets the minutes portion of a date/time

Signature
minutes-from-dateTime($arg as xs:dateTime?) as xs:integer?
Usage Notes

This function returns the minutes portion of an xs:dateTime value, as an integer between 0 and 59, inclusive.

Special Case
  • If $arg is the empty sequence, the function returns the empty sequence.

Example

minutes-from-dateTime(xs:dateTime("2015-08-15T10:30:23")) returns 30.

Related Function

minutes-from-time

minutes-from-duration

Gets the number of minutes in a duration

Signature
minutes-from-duration($arg as xs:duration?) as xs:integer?
Usage Notes

This function calculates the minutes component of an xs:duration value, as an integer between -59 and 59, inclusive. This is not necessarily the same as the integer that appears before the M in the value. For example, if the duration is PT1M90S, the function returns 2 rather than 1. This is because 90 seconds is equal to 1.5 minutes, and the canonical value is therefore PT2M30S. Likewise, if the duration is PT90M, the result is 30, because the canonical value is PT1H30M.

Special Cases
  • If $arg is a negative duration, the function returns a negative value.

  • If $arg is the empty sequence, the function returns the empty sequence.

Examples
ExampleReturn value
minutes-from-duration(xs:duration("PT30M")) 30
minutes-from-duration(xs:duration("-PT90M")) -30
minutes-from-duration(xs:duration("PT1M90S")) 2
minutes-from-duration(xs:duration("PT3H")) 0
minutes-from-duration(xs:duration("PT60M")) 0

minutes-from-time

Gets the minutes portion of a time

Signature
minutes-from-time($arg as xs:time?) as xs:integer?
Usage Notes

This function returns the minutes portion of an xs:time value, as an integer between 0 and 59, inclusive.

Special Case
  • If $arg is the empty sequence, the function returns the empty sequence.

Example

minutes-from-time(xs:time("10:30:23")) returns 30.

Related Function

minutes-from-dateTime

month-from-date

Gets the month portion of a date

Signature
month-from-date($arg as xs:date?) as xs:integer?
Usage Notes

This function returns the month portion of an xs:date value, as an integer between 1 and 12, inclusive.

Special Case
  • If $arg is the empty sequence, the function returns the empty sequence.

Example

month-from-date(xs:date("2015-08-15")) returns 8.

Related Function

month-from-dateTime

month-from-dateTime

Gets the month portion of a date/time

Signature
month-from-dateTime($arg as xs:dateTime?) as xs:integer?
Usage Notes

This function returns the month portion of an xs:dateTime value, as an integer between 1 and 12, inclusive.

Special Case
  • If $arg is the empty sequence, the function returns the empty sequence.

Example

month-from-dateTime(xs:dateTime("2015-08-15T10:30:23")) returns 8.

Related Function

month-from-date

months-from-duration

Gets the number of months in a duration

Signature
months-from-duration($arg as xs:duration?) as xs:integer?
Usage Notes

This function calculates the months component of an xs:duration value, as an integer between -11 and 11, inclusive. This is not necessarily the same as the integer that appears before the M in the value. For example, if the duration is P18M, the function returns 6 rather than 18. This is because 12 of those months are considered to be one year, and the canonical value is therefore P1Y6M.

Special Cases
  • If $arg is a negative duration, the function returns a negative value.

  • If $arg is the empty sequence, the function returns the empty sequence.

Examples
ExampleReturn value
months-from-duration(xs:duration("P3M")) 3
months-from-duration(xs:duration("-P18M")) -6
months-from-duration(xs:duration("P1Y")) 0
months-from-duration(xs:duration("P12M")) 0
months-from-duration(xs:duration("P31D")) 0

name

Gets the qualified name of a node as a string

Signature
name($arg as node()?) as xs:string
Usage Notes

This function returns a string that consists of the namespace prefix and colon (:), concatenated with the local part of the name. If the $arg node’s name is not in a namespace, the function returns the local part of the name, with no prefix. If the name is associated with the default namespace, the resulting name will not be prefixed.

The name function returns a value that depends on the choice of prefixes in the source document. This makes it well suited for displaying the name, for example, in error messages, but it should never be used to test the name, because choice of prefixes shouldn’t affect the result. For this purpose, use node-name instead.

Special Cases
  • If $arg is not provided, the context item is used. In this case, it is an error if the context item is absent (XPDY0002) or not a node (XPTY0004).

  • The function returns a zero-length string if:

    • $arg is the empty sequence.

    • $arg is a node that does not have a name (i.e., a document, comment, or text node).

  • If $arg is a processing instruction node, the function returns its target.

Examples

These examples use the input document names.xml shown in Example A-13. They assume the following namespace declarations in the query prolog. The prefixes pre2 and unpre2 are used rather than pre and unpre to demonstrate that when selecting nodes from an instance document, the prefix used in the instance document (not the query) is returned.

declare namespace pre2 = "http://datypic.com/pre";
declare namespace unpre2 = "http://datypic.com/unpre";
ExampleReturn value
name(doc("names.xml")//noNamespace) noNamespace
name(doc("names.xml")//pre2:prefixed) pre:prefixed
name(doc("names.xml")//unpre2:unprefixed) unprefixed
name(doc("names.xml")//@pre2:prefAttr) pre:prefAttr
name(doc("names.xml")//@noNSAttr) noNSAttr

namespace-uri

Gets the namespace part of an element or attribute name

Signature
namespace-uri($arg as node()?) as xs:anyURI
Usage Notes

This function returns the namespace part of the element or attribute name. This is the namespace that is bound to its prefix, or the default namespace if it is unprefixed. If the element or attribute name is not in a namespace, a zero-length value is returned.

Special Cases
  • If $arg is not provided, the context item is used. In this case, it is an error if the context item is absent (XPDY0002) or not a node (XPTY0004).

  • The function returns a zero-length xs:anyURI value if:

    • $arg is the empty sequence.

    • $arg is a kind of node that does not have a namespace (i.e., a document, comment, processing instruction, or text node).

    • $arg is an element or attribute whose name is not in a namespace.

Examples

These examples use the input document names.xml shown in Example A-13. They assume the following namespace declarations in the query prolog:

declare namespace pre = "http://datypic.com/pre";
declare namespace unpre = "http://datypic.com/unpre";
ExampleReturn value
namespace-uri(doc("names.xml")//noNamespace) A zero-length URI value
namespace-uri(doc("names.xml")//pre:prefixed) http://datypic.com/pre
namespace-uri(doc("names.xml")//unpre:unprefixed) http://datypic.com/unpre
namespace-uri(doc("names.xml")//@pre:prefAttr) http://datypic.com/pre
namespace-uri(doc("names.xml")//@noNSAttr) A zero-length URI value

namespace-uri-for-prefix

Gets the namespace bound to a specified prefix in the scope of a particular element

Signature
namespace-uri-for-prefix($prefix as xs:string?,
                         $element as element()) as xs:anyURI?
Usage Notes

This function returns the namespace bound to $prefix, using the in-scope namespaces of $element. If $prefix is a zero-length string or the empty sequence, the function returns the default namespace, if any.

The function is most often used in conjunction with the in-scope-prefixes function to determine all the namespaces that are declared on a particular element, including any namespaces that appear to be unused.

Special Cases
  • If $prefix is not bound to a namespace in scope, the function returns the empty sequence.

  • If $prefix is a zero-length string or the empty sequence, and there is no default namespace, the function returns the empty sequence.

Examples

These examples use the input document names.xml shown in Example A-13. They assume the following namespace declarations in the query prolog:

declare namespace pre = "http://datypic.com/pre";
declare namespace unpre = "http://datypic.com/unpre";
ExampleReturn value
namespace-uri-for-prefix("",
doc("names.xml")//noNamespace)
()
namespace-uri-for-prefix("pre",
doc("names.xml")//noNamespace)
()
namespace-uri-for-prefix("pre",
doc("names.xml")//pre:prefixed)
http://datypic.com/pre
namespace-uri-for-prefix("",
doc("names.xml")//unpre:unprefixed)
http://datypic.com/unpre
namespace-uri-for-prefix("pre",
doc("names.xml")//unpre:unprefixed)
http://datypic.com/pre

namespace-uri-from-QName

Gets the namespace URI part of a QName

Signature
namespace-uri-from-QName($arg as xs:QName?) as xs:anyURI?
Usage Notes

This function returns the namespace part of an xs:QName. If you want to retrieve the namespace of an element or attribute name, you should consider using the namespace-uri function instead; it saves a step.

Special Cases
  • If $arg is in no namespace, the function returns a zero-length value.

  • If $arg is the empty sequence, the function returns the empty sequence.

Examples
ExampleReturn value
namespace-uri-from-QName(QName ("http://datypic.com/pre", "prefixed")) http://datypic.com/pre
namespace-uri-from-QName(QName ("", "unprefixed")) A zero-length URI value
namespace-uri-from-QName( () ) ()

nilled

Determines whether an element is nilled

Signature
nilled($arg as node()?) as xs:boolean?
Usage Notes

In a schema, element declarations can designate elements as nillable. This allows them to appear in an instance document empty, even if their type would otherwise require them to have some content (character data or children or both).

An element is not considered to be nilled just because it is empty. For an element to be nilled, it must have an attribute xsi:nil whose value is true. Nilled elements are always empty; it is not valid for an element to have content and also have the xsi:nil attribute set to true.

On the other hand, some elements may be validly empty, but not be nilled. This may occur if an element has a complex type that specifies all optional children, or a simple type that allows blank values, such as xs:string. To test for an empty (but not necessarily nilled) element, you can use the expression string($node) = "".

It is useful to be able to check for a nilled element by using the nilled function to avoid unexpected results. For example, suppose you want to subtract the value of a discount element from the value of a price element. If the discount element is nilled, its typed value will be the empty sequence, and the result of the expression price - discount will be the empty sequence. You can avoid this by using the expression:

price - (if (nilled(discount)) then 0 else discount)
Special Cases
  • If $arg is not provided, the context item is used. In this case, it is an error if the context item is absent (XPDY0002) or not a node (XPTY0004).

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

  • If $arg is an untyped element (because it was not successfully validated against a schema element declaration), even if it has the xsi:nil="true" attribute, the function returns false.

  • If $arg is the empty sequence, the function returns the empty sequence.

  • When using XQuery 1.0, the zero-argument version of this function is not available.

Examples

These examples use the input document nils.xml shown in Example A-14. They assume that the input document has been validated against a schema that declares the child element as nillable.

ExampleReturn value
nilled(doc("nils.xml")//child[1]) false
nilled(doc("nils.xml")//child[2]) true
nilled(doc("nils.xml")//child[3]) false
nilled(doc("nils.xml")//child[4]) false
nilled(doc("nils.xml")//child[5]) false
Example A-14. Nilled elements (nils.xml)
<root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <child>12</child>
  <child xsi:nil="true"></child>
  <child></child>
  <child/>
  <child xsi:nil="false"></child>
</root>
Related Functions

empty, exists

node-name

Gets the qualified name of a node

Signature
node-name($arg as node()?) as xs:QName?
Usage Notes

This function returns the qualified name of a node as an xs:QName. It is useful only for element, attribute, and processing instruction nodes. For elements and attributes, it is simply the names used in XML documents. If the node’s name is not in any namespace, the namespace portion of the QName is empty, while the local part is the appropriate name.

Special Cases
  • If $arg is not provided, the context item is used. In this case, it is an error if the context item is absent (XPDY0002) or not a node (XPTY0004).

  • If $arg does not have a name (because it is a text, comment, or document node), the function returns the empty sequence.

  • If $arg is a processing instruction node, the function returns its target, with no prefix or namespace associated with it.

  • If $arg is the empty sequence, the function returns the empty sequence.

  • When using XQuery 1.0, the zero-argument version of this function is not available, so $arg must be provided.

Examples

These examples use the input document names.xml shown in Example A-13. They assume the following namespace declarations in the query prolog. The prefixes pre2 and unpre2 are used rather than pre and unpre to demonstrate that when selecting nodes from an instance document, the prefix used in the instance document (not the query) is returned. Although prefixes are technically irrelevant, they are saved in QName values by XQuery processors.

declare namespace pre2 = "http://datypic.com/pre";
declare namespace unpre2 = "http://datypic.com/unpre";
ExampleReturn value (xs:QName)
node-name(doc("names.xml")//noNamespace)

Namespace: empty

Prefix: empty

Local part: noNamespace

node-name(doc("names.xml")//pre2:prefixed)

Namespace: http://datypic.com/pre

Prefix: pre

Local part: prefixed

node-name(doc("names.xml")//unpre2:unprefixed)

Namespace: http://datypic.com/unpre

Prefix: empty

Local part: unprefixed

node-name(doc("names.xml")//@pre2:prefAttr)

Namespace: http://datypic.com/pre

Prefix: pre

Local part: prefAttr

node-name(doc("names.xml")//@noNSAttr)

Namespace: empty

Prefix: empty

Local part: noNSAttr

normalize-space

Normalizes the whitespace in a string

Signature
normalize-space($arg as xs:string?) as xs:string
Usage Notes

This function collapses whitespace in a string. Specifically, it performs three steps:

  1. Replaces each carriage return (#xD), line-feed (#xA), and tab (#x9) character with a single space (#x20)

  2. Collapses all consecutive spaces into a single space

  3. Removes all leading and trailing spaces

Special Cases
  • If $arg is the empty sequence, the function returns a zero-length string.

  • If $arg is not provided, the function uses the string value of the context item. In this case, if context item is absent, error XPDY0002 is raised.

Examples
ExampleReturn value
normalize-space("query") query
normalize-space(" query ") query
normalize-space("xml query") xml query
normalize-space(" xml  query ") xml query

normalize-space("xml

query")

xml query (line break becomes a space)
normalize-space("") A zero-length string
normalize-space(" ") A zero-length string
normalize-space( () ) A zero-length string
normalize-space(<element> query </element>) query

normalize-unicode

Performs Unicode normalization on a string

Signature
normalize-unicode($arg as xs:string?,
                  $normalizationForm as xs:string) as xs:string
Usage Notes

Unicode normalization allows text to be compared without regard to subtle variations in character representation. It replaces certain characters with equivalent representations. Two normalized values can then be compared to determine whether they are the same. Unicode normalization is also useful for allowing character strings to be sorted appropriately.

$normalizationForm controls which normalization form is used, and hence which characters are replaced. Examples of replacements that might be made include:

  • Some characters may be replaced by equivalent characters. The symbol £ (U+FFE1) is converted to an equivalent symbol, £ (U+00A3), using the form NFKC.

  • Some characters with accents or other marks represented by one codepoint may be decomposed to an equivalent representation that has two or more codepoints. The ç character (U+00E7) is changed to a representation that uses two codepoints (U+0063, which is “c”, and U+0327, which is the cedilla), using form NFKD. Other normalization forms may combine the two codepoints into a single codepoint.

  • Some characters that represent symbols may be replaced by letters or other characters. The symbol ㎗ (U+3397) is replaced by the two letters dl (U+0064 + U+006C), using the form NFKC. This change is not made when using the form NFC.

Valid values for $normalizationForm are listed in Table A-7. The value may be specified with leading or trailing spaces, in upper-, lower-, or mixed case. All implementations support the value NFC; some implementations may support the other values listed, as well as additional normalization forms.

Table A-7. Valid values for $normalizationForm
ValueMeaning
NFC Unicode Normalization Form C (NFC)
NFD Unicode Normalization Form D (NFD)
NFKC Unicode Normalization Form KC (NFKC)
NFKD Unicode Normalization Form KD (NFKD)
FULLY-NORMALIZED The fully normalized form, according to the W3C definition. This form takes into account XML constructs such as entity references and CDATA sections in text.
Zero-length stringNo normalization is performed.

Essentially, FULLY-NORMALIZED is NFC with the additional rule that “combining characters” (such as freestanding accents) cannot appear on their own at the start of a string. The advantage of this form is that concatenating two fully normalized strings will always give a fully normalized string.

Special Cases
  • If $normalizationForm is not provided, NFC is used as a default.

  • If $normalizationForm is a form that is not supported by the implementation, error FOCH0003 is raised.

  • If $normalizationForm is a zero-length string, no normalization is performed.

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

Examples
ExampleReturn value
normalize-unicode("query") query
normalize-unicode("query", "") query
normalize-unicode("", "NFKC")£
normalize-unicode("leçon", "NFKD") lec¸on
normalize-unicode("15", "NFC")15
normalize-unicode("15", "NFKC") 15 dl

For more information on Unicode normalization forms, see http://www.unicode.org/unicode/reports/tr15. The normalization charts, which identify the replacements for each character, for each form, can be found at http://www.unicode.org/charts/normalization.

not

Negates any Boolean value, turning false to true and true to false

Signature
not($arg as item()*) as xs:boolean
Usage Notes

This function accepts a sequence of items, from which it calculates the effective boolean value of the sequence as a whole before negating it. This means that when $arg is either a single Boolean value false, a zero-length string, the number 0 or NaN, or the empty sequence, it returns true. Otherwise, it usually returns false. The detailed rules for evaluating the effective boolean value of a sequence are described in “Effective Boolean Value”.

Special Case
  • If the effective boolean value of $arg cannot be determined, for example because $arg is a sequence of multiple atomic values, error FORG0006 is raised.

Examples
ExampleReturn value
not(12 > 20) true
not(doc("catalog.xml")//product) false if there is at least one product element in catalog.xml
not(true()) false
not( () ) true
not("") true
not(0) true
not(<e>false</e>) false

number

Constructs an xs:double value

Signature
number($arg as xs:anyAtomicType?) as xs:double
Usage Notes

This function constructs an xs:double value either from a node that contains a number, or from an atomic value. This function is useful for telling the processor to treat a node or value as a number, regardless of its declared type (if any). It returns the argument cast as an xs:double.

The difference between using the number function and the xs:double constructor is that the number function returns the value NaN in the case that the argument cannot be cast to a numeric value, whereas the xs:double constructor will raise an error if it is an invalid value, or the empty sequence if the argument is the empty sequence.

Special Cases
  • If $arg is not provided, the function uses the context item. In this case, if the context item is absent, error XPDY0002 is raised.

  • The function returns the value NaN in the case that $arg cannot be cast to a numeric value, i.e., if it is the empty sequence or a value that cannot be cast to xs:double.

Examples
ExampleReturn value
number(doc("prices.xml")//prod[1]/price) 29.99
number(doc("prices.xml")//prod/price) Error XPTY0004
number(doc("prices.xml")//prod[1]/@currency) NaN
number("29.99") 29.99
number("ABC") NaN
number( () ) NaN
doc("prices.xml")//prod/price[number() > 35] The two price elements with values over 35

one-or-more

Verifies that a sequence contains one or more items

Signature
one-or-more($arg as item()*) as item()+
Usage Notes

This function returns $arg unchanged if it contains one or more items. Otherwise, error FORG0004 is raised.

This is useful when static typing is in effect, to avoid apparent static type errors. For example, suppose you wanted to call a user-defined local:concatNames function that takes as an argument one or more strings (but not the empty sequence). To use the function, you might be tempted to write the expression:

local:concatNames(doc("catalog.xml")//name)

However, if static typing is used, this expression causes a static error if the name element is optional in the schema. This is because the path expression might return the empty sequence, while the local:concatNames function requires that at least one string be provided. A static error can be avoided by using the expression:

local:concatNames(one-or-more(doc("catalog.xml")//name))

In this case, no static error is raised. Rather, a dynamic error is raised if the path expression returns the empty sequence. For more information on static typing, see Chapter 15.

If static typing is not in effect, calling one-or-more is not usually necessary, but it does no harm. The effect is usually to make explicit a runtime type check that would otherwise have been done automatically.

Examples
ExampleReturn value
one-or-more( () ) Error FORG0004
one-or-more("a") a
one-or-more( ("a", "b") ) ("a", "b")
Related Functions

zero-or-one, exactly-one

outermost

Returns the nodes in a sequence that have no ancestors among the other nodes in the sequence

Signature
outermost($nodes as node()*) as node()*
Usage Notes

This function returns those nodes in $nodes that are not descendants of other nodes in $nodes. The nodes are returned in document order.

The main purpose of this function is to support streaming in XSLT, but it can be used in XQuery also. For example, if your document has section elements within section elements, you can get the outermost (highest-level) section elements by specifying outermost(//section).

Special Cases
  • If $nodes is the empty sequence, the function returns the empty sequence.

  • This function is new in XQuery 3.0.

Examples

Given the input document:

<div class="example">
  <div>
    <p>Example 1-1:</p>
    <div class="listing">
      <p>Example goes here</p>
    </div>
  </div>
</div>

calling outermost(//div) will return the div that has no div ancestors, namely the one whose class is example.

The function call outermost(doc("catalog.xml")//*) will return the root catalog element.

Related Function

innermost

parse-ietf-date

Converts a date/time in IETF format to xs:dateTime

Signature
parse-ietf-date($value as xs:string?) as xs:dateTime?
Usage Notes

This function parses a string that is in IETF date format and turns it into an xs:dateTime value. An IETF date is composed of the following parts, all of which are case-insensitive and can be separated by extra whitespace:

  • An optional day name (e.g., Monday or Mon) followed by a comma. This is ignored by the parse-ietf-date function.

  • A date that consists of a day number (one to two digits), the month name abbreviation (e.g., Jan), and a year (two or four digits). Each of these three parts is separated by either a space or a hyphen. Two-digit years have a 19 prefixed to them by the parse-ietf-date function.

  • A time that consists of an hour (one to two digits), a number of minutes (two digits), and an optional number of seconds (two digits, optionally followed by a decimal point and more digits). Each of these three parts is separated by a colon.

  • An optional time zone, in the form of a name (e.g., UTC or EST) or an offset (e.g., +01:00 or -05:00, colons optional). If both an offset and a name are provided, the name is ignored by the parse-ietf-date function. If a time zone is not provided, 00:00 is assumed.

As an alternative, the order of the components can be month name, day, time, and then year. More information about the IETF date format is found in section 3.3 of the HTTP specification, RFC 2616, which can be found at http://www.ietf.org/rfc/rfc2616.txt.

To convert from an xs:dateTime to an IETF date, you can use the built-in format-date function with the picture string [FNn3], [D01] [MNn3] [Y04] [H01]:[m01]:[s01] [Z0000].

Special Cases
  • If $value does not use valid IETF date syntax, or represents an invalid date or time such as April 31, error FORG0010 is raised.

  • This function is new in XQuery 3.1.

Examples
ExampleReturn value
parse-ietf-date("Wed, 05 Jul 2015 13:25:15 GMT") 2015-07-05T13:25:15Z
parse-ietf-date("Wed, 5 Jul 94 07:29 GMT") 1994-07-05T07:29:00Z
parse-ietf-date("Wed Jul 05 13:25:15 EST 2015") 2015-07-05T13:25:15-05:00
parse-ietf-date("Sunday, 05-Nov-94 08:25:15 GMT") 1994-11-05T08:25:15Z
parse-ietf-date("Wed, 5 Jul 2015 13:25:15 +0500") 2015-07-05T13:25:15+05:00

parse-json

Parses a JSON string

Signature
parse-json($json-text as xs:string?, $options as map(*)) as item()?
Usage Notes

This function takes a string that is in JSON syntax and parses it to create an item, generally a map or array. Details of how JSON constructs are mapped to XQuery maps and arrays are provided in “Parsing JSON”.

$options is a map that has the following possible entries (all of them optional), whose keys are strings:

liberal

Boolean value indicating whether deviations from the JSON syntax are allowed. The default is false. If the value is true, an implementation may choose to ignore certain recoverable deviations from the JSON syntax, such as omitting quotes around keys or allowing leading zeros in numbers.

duplicates

String indicating how the function should handle duplicate keys in a JSON object. If the value is reject, and duplicate keys are encountered, error FOJS0003 is raised. If the value is use-first (the default), the first of the duplicate entries is retained. If the value is use-last, the last of the duplicate entries is retained.

escape

Boolean value indicating whether special characters are escaped in the result. If the value is true (the default), JSON escapes (preceded by backslashes) are used for special characters. For example, the letter é is escaped as u00E9. If the value is false, special characters are not escaped. This setting controls the escaping of special characters in the result, regardless of whether the characters were escaped in the input JSON.

fallback

A function item that is to be called if the input contains an escape sequence that represents an invalid character in XML (and escape is not true). The function’s signature must be function(xs:string) as xs:string. For example, the function function($s){"ERROR!!"} would insert the string ERROR!! if it encountered such a character. If this function is not provided, the Unicode replacement character (&#xFFFD;) is inserted.

Additional implementation-defined options can be included in the $options map.

Special Cases
  • If $json-text is the empty sequence, or the string "null", the function returns the empty sequence.

  • If $json-text does not conform to the JSON grammar (optionally including implementation-defined extensions), error FOJS0001 is raised. An exception is that if the liberal option is set to true and the implementation can handle the anomaly, it will not raise an error.

  • If $options contains an invalid value, error FOJS0005 is raised.

  • If $options contains an entry "duplicates": "reject" and duplicates are encountered, error FOJS0003 is raised.

  • This function is new in XQuery 3.1.

Examples

A simple example of calling the parse-json function with no options is shown in Example A-15. The function call parses the JSON string and returns an equivalent map.

Example A-15. A simple call to parse-json

Query

xquery version "3.1";
parse-json('{
   "number": 557,
   "name": "Fleece Pullover",
   "colorChoices": ["navy", "black"],
   "is-current": true,
   "other": null 
}')

Results

map {
   "number": xs:double(557),
   "name": "Fleece Pullover",
   "colorChoices": ["navy", "black"],
   "is-current": true(),
   "other": () 
}

A more complex example that uses the $options argument is shown in Example A-16. This example specifies some of the options with default values (unnecessarily) to show the appropriate syntax. Duplicate names appear in the JSON, and the first one is used as specified by the "duplicates": "use-first" entry.

Escape sequences in the strings in colorChoices show the escaping behavior. u00E9 is a valid escape sequence and is converted to the character é because of the "escape": false() entry. uFFFF is an invalid character in XML, so the fallback function is called and the text ERROR!! is inserted in place of the escape sequence.

Example A-16. Calling parse-json with options

Query

xquery version "3.1";
parse-json('{
   "number": 557,
   "name": "Fleece Pullover",
   "name": "Fleece Pullover Redux",
   "colorChoices": ["navy u00E9", "black uFFFF"],
   "is-current": true,
   "other": null
}',
map {"duplicates": "use-first",
  "liberal": false(),
  "validate": false(),
  "escape": false(),
  "fallback": function($s){"ERROR!!"}
})

Results

map {
   "number": xs:double(557),
   "name": "Fleece Pullover",
   "colorChoices": ["navy é", "black ERROR!!"],
   "is-current": true(),
   "other": () 
}
Related Functions

json-doc , json-to-xml

parse-xml

Converts a string in XML syntax to a document node with a single element child

Signature
parse-xml($arg as xs:string?) as document-node(element(*))?
Usage Notes

This function parses a string that is in the form of an XML document and converts it to a document node that contains the XML structure. One use case for this is to parse nested XML documents that are contained in CDATA strings or otherwise escaped. Some of the behavior of this function is implementation-defined, such as whether to validate against a DTD or schema, or whether to use an XML 1.0 or XML 1.1 parser to parse the string.

This function requires that $arg be well-formed XML with only a single outermost element. To parse XML document fragments, for example, a sequence of several elements without a single root, use the parse-xml-fragment function instead.

Special Cases
  • If $arg is the empty sequence, the function returns the empty sequence.

  • If $arg is not well-formed XML (including namespace well-formedness), with a single root element, error FODC0006 is raised.

  • If the implementation attempts to perform DTD validation and $arg is not valid according to the DTD, error FODC0006 is raised.

  • This function is new in XQuery 3.0.

Examples
ExampleReturn value
parse-xml("<number>557</number>") A document node whose only child is a number element
parse-xml("<?xml version='1.0' encoding='UTF-8'?> <product dept='ACC'> <number>557</number> </product>") A document node whose only child is a product element
Related Functions

parse-xml-fragment , doc

parse-xml-fragment

Converts a string in XML syntax to a document node

Signature
parse-xml-fragment($arg as xs:string?) as document-node()?
Usage Notes

This function parses a string that is in XML syntax and converts it to a document node that contains the XML structure. Unlike the parse-xml function, the $arg string is not required to represent a well-formed XML document. It does not have to have a single outermost element; it can represent a sequence of multiple elements, or even no elements and just character data, which is converted to a text node. Even so, the function always returns a document node that contains the other nodes.

Special Cases
  • If $arg is the empty sequence, the function returns the empty sequence.

  • If $arg is a zero-length string, the function returns a document node with no children.

  • If $arg is not a well-formed XML fragment, for example, because it has overlapping tags or misuses namespace prefixes, error FODC0006 is raised.

  • This function is new in XQuery 3.0.

Examples
ExampleReturn value
parse-xml-fragment("<number>557</number><name>Fleece Pullover</name>") A document node whose two children are a number and a name element
parse-xml-fragment("<?xml version='1.0' encoding='UTF-8'?> <product dept='ACC'> <number>557</number> </product>") A document node whose only child is a product element
parse-xml-fragment("Our <i>favorite</i> shirt!") A document node whose three children are a text node containing "Our ", an i element, and a text node containing " shirt"
Related Functions

parse-xml , doc

path

Returns the path to a node

Signature
path($arg as node()?) as xs:string?
Usage Notes

This function returns a path expression that will select the node $arg relative to its containing root. If the node is part of a document node (its root is a document), the returned string will start with /. If its root is not a document node, it will start with Q{http://www.w3.org/2005/xpath-functions}root(). From there it will traverse down through the node hierarchy until it reaches the node specified in $arg, adding steps to the path along the way, depending on the node kind:

  • An element node will be represented as Q{, followed by the full namespace name, followed by } and the local part of the element’s name. It will also include a positional predicate, for example, [2] to indicate that it is the second element by that name in any given parent. If the element name is not in a namespace, the namespace name will be omitted, so the local part will be prefixed with just Q{}. This syntax that uses the Q{ and } delimiters is described in “URI-Qualified Names”.

  • For an attribute node, the name will be preceded by the @ sign. If an attribute name is not in a namespace, the delimiters Q{ and } will be omitted and just the local part of the name will be used. No positional predicate is required for attributes because their names are unique for a particular element.

  • A text node will be represented as text(), followed by a positional predicate.

  • A comment node will be represented as comment(), followed by a positional predicate.

  • A processing instruction node will be represented as processing-instruction(, followed by the processing instruction name, followed by ), followed by a positional predicate.

Special Cases
  • If $arg is omitted, the function uses the context item. In this case, it is an error if the context item is absent (XPDY0002) or not a node (XPTY0004).

  • If $arg is a document node, the function returns "/".

  • If $arg is the empty sequence, the function returns the empty sequence.

  • This function is new in XQuery 3.0.

Examples

The examples assume these variable declarations. The input document cat_ns.xml shown in Example 10-4.

declare variable $c := doc("catalog.xml");
declare variable $n := doc("cat_ns.xml");
ExampleReturn value
path($c) /
path($c/catalog/product[1]/number) /Q{}catalog[1]/Q{}product[1]/Q{}number[1]
path($c/catalog/product[1]/@dept) /Q{}catalog[1]/Q{}product[1]/@dept
path($c//desc/text()[.='Our ']) /Q{}catalog[1]/Q{}product[4]/Q{}desc[1]/text()[1]
path($n/*:catalog) /Q{http://datypic.com/cat}catalog[1]
path($n/*:catalog/*:product[1]) /Q{http://datypic.com/cat}catalog[1]/Q{http://datypic.com/prod}product[1]

math:pi

Returns the mathematical constant π (pi)

Signature
math:pi() as xs:double
Usage Notes

This function returns an approximation to the mathematical constant π (pi).

Special Case
  • This function is new in XQuery 3.0.

Example

math:pi() returns approximately 3.141592653589793.

position

Gets the position of the context item within the context sequence

Signature
position() as xs:integer
Usage Notes

This function returns an integer representing the position (starting with 1, not 0) of the current context item within the context sequence (the current sequence of items being processed). In XQuery, the position function is almost invariably used in predicates (in square brackets) to test the relative position of a node.

Special Case
  • If the context item is absent, error XPDY0002 is raised.

Examples

The expression:

doc("catalog.xml")/catalog/product[position() < 3]

returns the first two product children of catalog. You could also select the first two children of product, with any name, using a wildcard, as in:

doc("catalog.xml")/catalog/product/*[position() < 3]

Note that the expression product[position() = 3] is equal to the expression product[3], so the position function is not very useful in this case. However, you might use the expression:

doc("catalog.xml")/catalog/product[position() = (1 to 3)]

to get the first three products. You can use the position and last functions together to get the last product, as in:

doc("catalog.xml")/catalog/product[position() = last()]
Related Functions

last, index-of

math:pow

Returns the first argument raised to the power of the second

Signature
math:pow($x as xs:double?, $y as xs:numeric) as xs:double?
Usage Notes

This function returns the value of $x raised to the power of $y.

Special Cases
  • If $x is the empty sequence, the function returns the empty sequence.

  • This function is new in XQuery 3.0.

Examples
ExampleReturn value
math:pow(2, 3) 8
math:pow(2, -3) 0.125
math:pow(0, 0) 1
math:pow(0, -3) INF
Related Functions

math:exp, math:exp10

prefix-from-QName

Gets the prefix associated with a specified qualified name

Signature
prefix-from-QName($arg as xs:QName?) as xs:NCName?
Usage Notes

This function returns the prefix associated with the qualified name $arg. Note that the prefix associated with a qualified name selected from an input document will be the prefix that is used in that input document, not a prefix used in the query.

Special Cases
  • If $arg is the empty sequence, the function returns the empty sequence.

  • If $arg has no prefix (e.g., because it is associated with the default namespace, or it is not in a namespace), the function returns the empty sequence.

Examples

These examples use the input document names.xml shown in Example A-13. They assume the following namespace declarations in the query prolog. The prefix pre2 is used rather than pre to demonstrate that when selecting nodes from an instance document, it is the prefix used in the instance document (not the query) that matters. However, when constructing a new element, the prefix used in the query itself is the one associated with the name, as shown in the last example.

declare namespace pre2 = "http://datypic.com/pre";
declare namespace unpre = "http://datypic.com/unpre";
ExampleReturn value
prefix-from-QName(node-name(doc("names.xml")//noNamespace)) ()
prefix-from-QName(node-name(doc("names.xml")//pre2:prefixed)) pre
prefix-from-QName(node-name(doc("names.xml")//unpre:unprefixed)) ()
prefix-from-QName(node-name(doc("names.xml")//@pre2:prefAttr)) pre
prefix-from-QName(node-name(doc("names.xml")//@noNSAttr)) ()
prefix-from-QName(node-name(<pre2:new>xyz</pre2:new>)) pre2

array:put

Replaces a member in an array at the specified position

Signature
array:put($array as array(*), $position as xs:integer,
          $member as item()*) as array(*)
Usage Notes

This function creates an array that contains all the members of $array, except that the items in $member replace the member at the position $position.

Special Cases
  • If $position is less than 1, or greater than the size of $array, error FOAY0001 is raised. The size of the array can be determined by calling array:size.

  • If $member is a sequence of multiple items, each item does not become a member. The replacement is a single member whose value is the sequence of all the items in $member.

  • If $member is an array, the entire array becomes a single member of the outer array; the two arrays are not merged.

  • If $member is the empty sequence, the member at $position is replaced with a member whose value is the empty sequence.

  • This function is new in XQuery 3.1.

Examples

The examples assume this variable declaration:

declare variable $array1 := ["abc", "ghi", "jkl"];
ExampleReturn value
array:put($array1, 2, "def") ["abc", "def", "jkl"]
array:put($array1, 3, ("mno", "pqr") ) ["abc", "ghi", ("mno", "pqr")]
array:put($array1, 3, () ) ["abc", "ghi", ()]
array:put($array1, 4, "mno") Error FOAY0001
array:put($array1, 0, "aaa") Error FOAY0001

map:put

Adds or replaces an entry in a map

Signature
map:put($map as map(*), $key as xs:anyAtomicType, $value as item()*) as map(*)
Usage Notes

This function returns a map that has all the entries of $map plus a new entry with the key $key and the value $value. If the key already exists in $map, the entry is replaced rather than added.

Special Case
  • This function is new in XQuery 3.1.

Examples

The examples assume this variable declaration:

declare variable $map1 := map {1:"first", 2:"second"};
ExampleReturn value
map:put($map1, 1, "ONE") map {1:"ONE", 2:"second"}
map:put($map1, 3, "third") map {1:"first", 2:"second", 3:"third"}
map:put($map1, "abc", "def") map {1:"first", 2:"second", "abc":"def"}
Related Function

map:merge

QName

Constructs a QName from a URI and a local part

Signature
QName($paramURI as xs:string?, $paramQName as xs:string) as xs:QName
Usage Notes

This function takes a namespace URI $paramURI and a qualified (optionally prefixed) name $paramQName and constructs a QName value from them. If $paramQName is prefixed, that prefix is retained in the resulting xs:QName value.

Unlike the xs:QName constructor, the QName function does not require a literal argument. Therefore, the name could be the result of a dynamically evaluated expression. Because this function supplies all three components of the QName (local name, prefix, and URI), the effect does not depend on the context. There is no requirement that the prefix and namespace are bound in an outer expression.

Special Cases
  • If $paramURI is a zero-length string or the empty sequence, and $paramQName has a prefix, error FOCA0002 is raised.

  • If $paramURI is a zero-length string or the empty sequence, and $paramQName does not have a prefix, the resulting name is considered to be in no namespace.

  • If $paramURI is not a lexically valid URI value, error FOCA0002 is raised.

  • If $paramQName does not follow the lexical rules for an XML qualified name (e.g., because it starts with a number or it contains two colons), error FOCA0002 is raised.

Examples
ExampleReturn value (xs:QName)
QName("http://datypic.com/prod", "product")

Namespace: http://datypic.com/prod

Prefix: empty

Local part: product

QName("http://datypic.com/prod", "pre:product")

Namespace: http://datypic.com/prod

Prefix: pre

Local part: product

QName("", "product")

Namespace: empty

Prefix: empty

Local part: product

QName("", "pre:product") Error FOCA0002

random-number-generator

Generates sequences of random numbers

Signature
random-number-generator($seed as xs:anyAtomicType?) as map(xs:string, item())
Usage Notes

This function returns a random number generator that can be used to generate sequences of random numbers. It returns a map that has three entries, whose keys are strings:

number

A random number between 0 and 1, whose type is xs:double.

next

A function item (that takes zero arguments) that will generate the next random number, returning itself a map.

permute

A function item that takes one argument, an arbitrary sequence, and returns a random permutation of that sequence.

$seed optionally provides a seed to the random number generator. Using the same seed across multiple executions should result in the same random number. It is possible to use current-dateTime() as the seed to ensure different random numbers, but this only works across different query executions. Because current-dateTime() always returns the same value within one query execution, it cannot be used to provide a different seed each time the function is called within one query execution.

Within the same query execution, if this function is called multiple times (with no argument or the same argument), it will return the same map with the same number entry, so random-number-generator should not be used repeatedly to generate multiple random numbers. Instead, the function returned in the next entry should be called if more than one random number is required.

Special Case
  • This function is new in XQuery 3.1.

Examples
ExampleReturn value
random-number-generator()?number A single random number between 0 and 1
random-number-generator()?permute(1 to 100) The integers 1 to 100 in random order
for $seq in 1 to 100 return random-number-generator()?number The same random number between 0 and 1, repeated 100 times
for $seq in 1 to 100 return random-number-generator($seq)?number 100 numbers between 0 and 1 that may be different, or may be the same (even though the seed is different).

The last two examples in the table show that calling the random-number-generator function repeatedly can return the same results. To generate a sequence of multiple different random numbers, a function can be written to recursively call the function item that is the next entry returned by the previous random number generator. For example:

declare function local:random-sequence($length as xs:integer,
                                       $rng as map(xs:string, item())) {
  if ($length lt 1)
  then ()
  else ($rng?number, local:random-sequence($length - 1, $rng?next()))
};
local:random-sequence(5, random-number-generator())

In this code, the random-number-generator function is only called once, in the main body of the query. The result of that function (a map) is passed to the recursive local:random-sequence function. That first iteration of local:random-sequence uses the number entry returned by the random-number-generator function, and then calls itself to get the rest of the random numbers of the sequence, passing the results of the function in the next entry as the random number generator, and so on. This means that the same random number generator function is not called more than once, resulting in random numbers that are very likely to be different.

remove

Removes an item from a sequence based on its position

Signature
remove($target as item()*, $position as xs:integer) as item()*
Usage Notes

This function returns a sequence of all the items in $target except for the item at $position. Position numbers start at 1, not 0.

Special Cases
  • If $position is less than 1 or greater than the number of items in $target, no items are removed.

  • If $target is the empty sequence, the function returns the empty sequence.

Examples
ExampleReturn value
remove( ("a", "b", "c"), 1) ("b", "c")
remove( ("a", "b", "c"), 2) ("a", "c")
remove( ("a", "b", "c"), 10) ("a", "b", "c")
remove( ("a", "b", "c"), 0) ("a", "b", "c")

array:remove

Removes a member from an array

Signature
array:remove($array as array(*), $positions as xs:integer*) as array(*)
Usage Notes

This function returns an array with all the members of $array except for the ones at $positions. Positions start at 1 rather than 0.

Special Cases
  • If $positions has a value that is not a position in the array (either because it is less than 1 or greater than the number of members in the array), error FOAY0001 is raised. The size of the array can be determined by calling array:size.

  • This function is new in XQuery 3.1.

Examples

The examples assume this variable declaration:

declare variable $array1 := ["abc", "def", "ghi", "jkl"];
ExampleReturn value
array:remove($array1, 2) ["abc", "ghi", "jkl"]
array:remove(["abc"], 1) [ ]
array:remove($array1, (2,3)) ["abc", "jkl"]
array:remove($array1, ()) ["abc", "def", "ghi", "jkl"]
array:remove($array1, 5) Error FOAY0001

map:remove

Removes an entry from a map

Signature
map:remove($map as map(*), $keys as xs:anyAtomicType*) as map(*)
Usage Notes

This function returns a map with all the entries of $map except for the ones whose key is in $keys. If there is no entry with a particular key, that key value is ignored; no error is raised.

Special Case
  • This function is new in XQuery 3.1.

Examples

The examples assume this variable declaration:

declare variable $map1 := map {1:"first", 2:"second"};
ExampleReturn value
map:remove($map1, 2) map {1:"first"}
map:remove($map1, (2,3)) map {1:"first"}
map:remove($map1, 3) map {1:"first", 2:"second"}
map:remove($map1, "abc") map {1:"first", 2:"second"}
Related Functions

map:put, map:merge

replace

Replaces substrings that match a pattern with a specified replacement string

Signature
replace($input as xs:string?, $pattern as xs:string,
        $replacement as xs:string, $flags as xs:string) as xs:string
Usage Notes

This function takes the string $input and replaces any parts that match $pattern with $replacement. $pattern is a regular expression; its syntax is covered in Chapter 19.

While it is nice to have the power of regular expressions, you don’t have to be familiar with regular expressions to replace a particular sequence of characters; you can just specify the string you want replaced for $pattern, as long as it doesn’t contain any special characters.

$replacement specifies a string (not a pattern) that is to be used as a replacement. $flags allows for additional options in the interpretation of the regular expression, such as multi-line processing and case insensitivity. It is discussed in detail in “Using Flags”.

Reluctant quantifiers and sub-expressions are two extremely useful features that can be used in conjunction with the replace function. They are described in “Reluctant Quantifiers” and “Using Sub-Expressions with Replacement Variables”, respectively.

Special Cases
  • If $input does not match $pattern, it is returned as is.

  • If $input is the empty sequence, it is treated like a zero-length string.

  • If $pattern is not a valid regular expression, error FORX0002 is raised.

  • If the entire $pattern matches a zero-length string, for example q?, error FORX0003 is raised.

  • If $replacement contains an unescaped dollar sign ($) that is not followed by a digit, error FORX0004 is raised. ($ is used to escape a dollar sign.)

  • If $replacement contains an unescaped backslash () that is not followed by a dollar sign ($), error FORX0004 is raised. (\ is used to escape a backslash.)

  • If $flags contains unsupported options, error FORX0001 is raised.

  • If two overlapping strings match $pattern, only the first is replaced.

Examples
ExampleReturn value
replace("query", "r", "as") queasy
replace("query", "qu", "quack") quackery
replace("query", "[ry]", "l") quell
replace("query", "[ry]+", "l") quel
replace("query", "z", "a") query
replace("query", "query", "") A zero-length string
replace( (), "r", "as") A zero-length string
replace("query", "r?", "as") Error FORX0003
replace("query", "(r", "as") Error FORX0002
replace("Chapter", "(Chap)|(Chapter)", "x") xter
replace("elementary", "e.*?e", "*") *mentary

If more than one sub-expression matches, starting at the same position, the first alternative is chosen. This is exhibited by the second-to-last example, where Chap is replaced instead of Chapter.

In the last example, there are actually two substrings in the original string that match the pattern: ele and eme. Only the first of these is replaced, because the second overlaps the first. Note that this example uses a reluctant quantifier; otherwise, the whole eleme would be replaced.

Related Function

translate

resolve-QName

Constructs a QName from a string by using the in-scope namespaces of an element

Signature
resolve-QName($qname as xs:string?, $element as element()) as xs:QName?
Usage Notes

This function constructs a QName from a string representing a qualified name ($qname) by using the in-scope namespaces of an element ($element). $qname may be prefixed (for example, prod:number), or unprefixed (for example, number). The in-scope namespaces of $element are to be used to determine which namespace URI is bound to the prefix. If $qname is unprefixed, the default namespace declaration of $element is used. If there is no default namespace declaration in scope, the constructed QName has no namespace.

Note that when using the function, the prefix is never resolved using the context of the query. For example, if you bind the prefix pre to the namespace http://datypic.com/pre in the query prolog, that is irrelevant when you call the resolve-QName function with the first argument pre:myName. It is only relevant how that prefix is bound in $element. If you want to use the context of the query, you can simply use the xs:QName constructor, as in xs:QName("pre:myName").

Typically, this function is used (in the absence of a schema) to resolve a QName appearing in the content of a document against the namespace context of the element where the QName appears. For example, to retrieve all products that carry the attribute xsi:type="prod:ProductType", you can use a path such as:

declare namespace prod = "http://datypic.com/prod";

doc("catalog.xml")//product[resolve-QName(@xsi:type, .)
                            = xs:QName("prod:ProductType")]

This test allows the value of xsi:type in the input document to use any prefix (not just prod), as long as it is bound to the http://datypic.com/prod namespace.

Special Cases
  • If $qname is prefixed, and that prefix is not bound to a namespace in the scope of $element, error FONS0004 is raised.

  • If $qname is not a lexically correct QName (for example, if it is not a valid XML name, or if it contains more than one colon), error FOCA0002 is raised.

  • If $qname is the empty sequence, the function returns the empty sequence.

Examples

These examples assume the following variable declarations:

declare variable $root := <root>
  <order xmlns:ord="http://datypic.com/ord"
         xmlns="http://datypic.com">
    <!-- ... -->
  </order>
</root>;
declare variable $order := $root/*:order;
ExampleReturn value (xs:QName)
resolve-QName("myName", $root)

Namespace: empty

Prefix: empty

Local part: myName

resolve-QName("myName", $order)

Namespace: http://datypic.com

Prefix: empty

Local part: myName

resolve-QName("ord:myName", $root) Error FONS0004
resolve-QName("ord:myName", $order)

Namespace: http://datypic.com/ord

Prefix: ord

Local part: myName

declare namespace prod = "http://datypic.com/prod";

resolve-QName("prod:myName", $order)

Error FONS0004

resolve-uri

Resolves a relative URI reference, based on a base URI

Signature
resolve-uri($relative as xs:string?, $base as xs:string) as xs:anyURI?
Usage Notes

This function takes a base URI ($base) and a relative URI ($relative) and resolves them, returning an absolute URI.

If $base is not provided, the static base URI is used. This may have been set by the processor outside the scope of the query, or it may have been declared in the query prolog by using a base URI declaration.

Special Cases
  • If $relative is the empty sequence, the function returns the empty sequence.

  • If $relative is already an absolute URI, the function returns $relative unchanged.

  • If $base is not provided and the static base URI is absent, error FONS0005 is raised.

  • If $relative or $base is not a syntactically valid URI, or is unsuitable for URI resolution, error FORG0002 is raised.

  • If the resolution fails for any other reason, error FORG0009 is raised.

Examples

These examples assume the following declaration in the prolog:

declare base-uri "http://datypic.com/";
ExampleReturn value
resolve-uri("prod", "http://datypic.com/") http://datypic.com/prod
resolve-uri("prod2", "http://datypic.com/prod1") http://datypic.com/prod2
resolve-uri("http://example.org", "http://datypic.com") http://example.org
resolve-uri("prod") http://datypic.com/prod
resolve-uri("", "http://datypic.com") http://datypic.com
resolve-uri("") http://datypic.com
Related Functions

base-uri, static-base-uri

reverse

Reverses the order of the items in a sequence

Signature
reverse($arg as item()*) as item()*
Usage Notes

This function returns the items in $arg in reverse order. These may be any kind of items, including nodes, atomic values, function items, or some combination of these.

Special Case
  • If $arg is the empty sequence, the function returns the empty sequence.

Examples
ExampleReturn value
reverse( (1, 2, 3, 4, 5) ) (5, 4, 3, 2, 1)
reverse( (6, 2, 4) ) (4, 2, 6)
reverse( "abc" ) "abc"
Related Functions

sort, array:reverse

array:reverse

Reverses the order of members in an array

Signature
array:reverse($array as array(*)) as array(*)
Usage Notes

This function returns a new array with all the members of $array in reverse order.

Special Case
  • This function is new in XQuery 3.1.

Examples
ExampleReturn value
array:reverse(["abc", "def", "ghi"]) ["ghi", "def", "abc"]
array:reverse(["abc"]) ["abc"]
array:reverse([("a", "b", "c")]) [("a", "b", "c")], because there is only one member in the array, which itself happens to be a sequence of more than one item.
array:reverse([ ]) [ ]
Related Functions

array:sort, reverse

root

Gets the root of the tree containing a node

Signature
root($arg as node()?) as node()?
Usage Notes

This function returns a document node if the $arg node is part of a document, but it may also return an element if the $arg node is not part of a document. The root function can be used in conjunction with path expressions to find siblings and other elements that are in the same document. For example:

root($myNode)/descendant-or-self::product

retrieves all product elements that are in the same document (or document fragment) as $myNode.

Calling the root function is similar to starting a path with / or //. It is more flexible in that it can appear anywhere in a path or other expression. Also, unlike starting a path with /, the root function does not require the root to be a document node; it could be an element in the case of a document fragment.

Special Cases
  • If $arg is the empty sequence, the function returns the empty sequence.

  • If $arg is the root node, the function simply returns $arg.

  • If $arg is not provided, the function uses the context item. In this case, it is an error if the context item is absent (XPDY0002) or not a node (XPTY0004).

Examples

The examples assume the following variable declarations:

declare variable $myNode := doc("catalog.xml")//product[1];
declare variable $frag := <a><x></x></a>;
ExampleReturn value
root($myNode) The document node of catalog.xml
root($myNode)/descendant-or-self::number All number elements that are in the same document as $myNode
root() The root of the current context item
root(.) The root of the current context item
root($frag/x) The a element

round

Rounds a number to a specified number of decimal places

Signature
round($arg as xs:numeric?, $precision as xs:integer) as xs:numeric?
Usage Notes

This function rounds a numeric value $arg to the number of decimal places indicated by $precision. For example, if $precision is 2, the function rounds 594.3271 to 594.33. If $precision is 0 or not provided, the number is rounded to a whole number.

Specifying a negative precision results in the number being rounded to the left of the decimal point. For example, if $precision is -2, the function rounds 594.3271 to 600.

If $arg is exactly halfway between two possible result values, it is rounded upward. This is in contrast to the round-half-to-even function, which rounds it to whichever adjacent value is an even number at the required precision.

The function returns a numeric value of type xs:float, xs:double, xs:decimal, or xs:integer, depending on the type from which $arg is derived. If $arg is untyped, it is cast to xs:double.

Special Cases
  • If $arg is the empty sequence, the function returns the empty sequence.

  • If $arg is between -0.5 and -0 (inclusive) and $precision is 0 or not provided, the function returns -0.

  • If $arg is one of the values 0, -0, NaN, INF, or -INF, the function returns this same value.

  • The two-argument version of this function is not available in XQuery 1.0. If you are using XQuery 1.0, you may wish to use round-half-to-even if you need to specify a precision.

Examples
ExampleReturn value
round(5) 5
round(5.1) 5
round(5.5) 6
round(-5.5) -5
round(-5.51) -6
round(9372.253, 2) 9372.25
round(9372.253, 0) 9372
round(9372.253, -3) 9000

round-half-to-even

Rounds a number, with half values rounded to the nearest even number

Signature
round-half-to-even($arg as xs:numeric?, $precision as xs:integer) as xs:numeric?
Usage Notes

This type of rounding is used in financial and statistical applications so that the sum of a column of rounded numbers comes closer to the sum of the same unrounded numbers.

The returned value is rounded to the number of decimal places indicated by $precision. For example, if $precision is 2, the function rounds 594.3271 to 594.33. If $precision is 0 or not provided, the number is rounded to a whole number. Specifying a negative precision results in the number being rounded to the left of the decimal point. For example, if $precision is -2, the function rounds 594.3271 to 600.

If $arg is exactly half way between two possible result values, it is rounded to whichever adjacent value is an even number at the required precision. This is in contrast to the round function, which rounds it upward in this case.

The function returns a numeric value of type xs:float, xs:double, xs:decimal, or xs:integer, depending on the type from which $arg is derived. If $arg is untyped, it is cast to xs:double.

The function works best with xs:decimal values. With xs:double and xs:float values, the rounding may not work exactly as expected. This is because an xs:double value written as 0.015, being only an approximation to a decimal number, is often not precisely midway between 0.01 and 0.02.

Special Cases
  • If $arg is the empty sequence, the function returns the empty sequence.

  • If $arg is between -0.5 and -0 (inclusive) and $precision is 0 or not provided, the function returns -0.

  • If $arg is one of the values 0, -0, NaN, INF, or -INF, the function returns this same value.

Examples
ExampleReturn value
round-half-to-even(5.5) 6
round-half-to-even(6.5) 6
round-half-to-even(9372.253, 2) 9372.25
round-half-to-even(9372.253, 0) 9372
round-half-to-even(9372.253, -3) 9000
Related Functions

round, floor, ceiling

seconds-from-dateTime

Gets the seconds portion of a date/time

Signature
seconds-from-dateTime($arg as xs:dateTime?) as xs:decimal?
Usage Notes

This function returns the seconds portion of an xs:dateTime value, as a decimal number.

Special Case
  • If $arg is the empty sequence, the function returns the empty sequence.

Example

seconds-from-dateTime(xs:dateTime("2015-08-15T10:30:23.5")) returns 23.5.

Related Function

seconds-from-time

seconds-from-duration

Gets the number of seconds in a duration

Signature
seconds-from-duration($arg as xs:duration?) as xs:decimal?
Usage Notes

This function calculates the seconds component of an xs:duration value, as a decimal number between -60 and 60, exclusive. This is not necessarily the same as the number that appears before the S in the value. For example, if the duration is PT90S, the function returns 30 rather than 90. This is because 60 of those seconds are considered to be 1 minute, and the canonical value is therefore PT1M30S.

Special Cases
  • If $arg is a negative duration, the function returns a negative value.

  • If $arg is the empty sequence, the function returns the empty sequence.

Examples
ExampleReturn value
seconds-from-duration(xs:duration("PT30.5S")) 30.5
seconds-from-duration(xs:duration("-PT90.5S")) -30.5
seconds-from-duration(xs:duration("PT1M")) 0
seconds-from-duration(xs:duration("PT60S")) 0

seconds-from-time

Gets the seconds portion of a time

Signature
seconds-from-time($arg as xs:time?) as xs:decimal?
Usage Notes

This function returns the seconds portion of an xs:time value, as a decimal number.

Special Case
  • If $arg is the empty sequence, the function returns the empty sequence.

Example

seconds-from-time(xs:time("10:30:23.5")) returns 23.5.

Related Function

seconds-from-dateTime

serialize

Converts an item into a string in XML or JSON format

Signature
serialize($arg as item()*, $params as item()?) as xs:string
Usage Notes

This function will take an item and convert it into a string that (by default) is in XML format. This is useful for embedding smaller XML documents in CDATA sections of larger documents, or any time a string representation of an XML document is needed. Using other serialization output methods, it can also be used to serialize text, JSON, or (X)HTML.

The $params argument specifies such options as the output method, whether to include an XML declaration, and whether to indent the output. If it is provided, it must be either an element named output:serialization-parameters, or a map. If $params is not provided, or if specific serialization parameters are not specified within $params, implementation-defined default values are used.

The structure of the $params argument (as XML or a map) and the meaning of all the parameters are described in detail in “Serializing Output”.

Special Cases
  • If serialization cannot be performed by the processor, perhaps because of an invalid serialization parameter value or because $arg is an attribute node, a serialization error will be raised. Serialization errors have names that start with SE and are described in Appendix C.

  • If the implementation does not support serialization, error FODC0010 is raised.

  • If $params is provided but it is not a map or output:serialization-parameters element, error XPTY0004 is raised.

  • This function is new in XQuery 3.0. The ability to specify $params as a map is new in XQuery 3.1.

Examples

For brevity, these examples omit the XML declaration that might also appear at the beginning of the string, unless the omit-xml-declaration serialization parameter is set to yes.

ExampleReturn value
serialize(doc("catalog.xml")//
product[1]/name)
"<name language="en">Fleece Pullover</name>"
serialize(doc("catalog.xml")//
desc)
"<desc>Our <i>favorite</i> shirt!</desc>"
serialize(doc("catalog.xml")//
number)
"<number>557</number><number>563</number><number>443</number><number>784</number>"
serialize(doc("catalog.xml")//
product[1]/number/text())
"557"

To serialize JSON to a string, you need to specify the json output method in the $params argument, as shown in Example A-17.

Example A-17. Serializing JSON to a string

Query

xquery version "3.1";
serialize(map {
   "number": xs:double(557),
   "name": "Fleece Pullover",
   "colorChoices": ["navy", "black"],
   "is-current": true(),
   "other": () 
},
<output:serialization-parameters
   xmlns:output="http://www.w3.org/2010/xslt-xquery-serialization">
  <output:method value="json"/>
  <output:indent value="yes"/>
</output:serialization-parameters>)

Results

"{
   "number": 557,
   "name": "Fleece Pullover",
   "colorChoices": ["navy", "black"],
   "is-current": true,
   "other": null 
}"

Example A-18 shows the equivalent example using a map for $params instead of an XML element.

Example A-18. Expressing serialization parameters as a map
xquery version "3.1";
serialize(map {
   "number": xs:double(557),
   "name": "Fleece Pullover",
   "colorChoices": ["navy", "black"],
   "is-current": true(),
   "other": () 
}, map {
   "method": "json",
   "indent": true()
})
Related Functions

parse-xml , parse-json

math:sin

Returns the sine

Signature
math:sin($θ as xs:double?) as xs:double?
Usage Notes

This function finds the sine of , which is an angle in radians. The result is in the range -1.0e0 to +1.0e0, inclusive.

Special Cases
  • If is the empty sequence, the function returns the empty sequence.

  • If is positive or negative zero, the function returns .

  • If is INF, -INF, or NaN, the function returns NaN.

  • This function is new in XQuery 3.0.

Examples
ExampleReturn value
math:sin(0) 0
math:sin(math:pi() div 2) 1 (approximately)
math:sin(math:pi()) 0 (approximately)

array:size

Returns the number of members in an array

Signature
array:size($array as array(*)) as xs:integer
Usage Notes

This function returns the number of members in $array. This works differently from the count function on arrays, which will always return 1 because there is one single item, an array.

Special Cases
  • If the array is empty, zero is returned.

  • This function is new in XQuery 3.1.

Examples
ExampleReturn value
array:size([1, 2, 3]) 3
array:size(["abc", ["def", "ghi"]]) 2 (the second member of the array is itself an array with two members)
array:size([ ]) 0
array:size([[ ]]) 1 (the member is an empty array)
count([1, 2, 3]) 1

map:size

Returns the number of entries in a map

Signature
map:size($map as map(*)) as xs:integer
Usage Notes

This function returns the number of entries in $map.

Special Cases
  • If $map is empty, zero is returned.

  • This function is new in XQuery 3.1.

Examples
ExampleReturn value
map:size( map {1:"first", 2:"second"} ) 2
map:size( map {} ) 0
Related Function

map:keys

sort

Sorts a sequence

Signature
sort($input as item()*, $collation as xs:string?, 
     $key as function(item()) as xs:anyAtomicType*) as item()*
Usage Notes

This function sorts the items in a sequence. It serves a similar purpose to the order by clause of a FLWOR expression. It can be more compact than a FLWOR, and in some cases more flexible, for example, if a sort key is chosen dynamically.

If $key is not provided, the items’ typed values are used as their sort keys. This is permissible for atomic values with types that allow comparisons. It will also work for elements or attributes, which will be sorted by their typed values, specifically the result of calling the data function on that item. If they are schema-validated, the sort order will take into consideration their type, for example, placing 99 before 100. Otherwise, they will be sorted as strings, where 99 will come after 100.

If $key is provided, it is a function that returns the sort key for an item. That function must accept a single item and return a sequence of zero or more atomic values. If the function returns multiple values for the sort key, they are compared one by one, in order. For example, if the function returns ("a", "c", "d") for the first item and ("a", "b", "f") for the second item, the second item will be placed before the first item in the result sequence, because b is less than c. This is analogous to specifying multiple values to sort on in an order by clause.

Special Cases
  • If any of the sort keys have typed values that can’t be compared, type error XPTY0004 is raised. This might arise either because they have mixed types (for example, a combination of xs:string and xs:integer values), or because they have a type that does not allow comparisons, such as xs:duration.

  • If $key is omitted and $input contains an item for which the data function will raise an error, for example, a map or a schema-validated element with element-only content, error FOTY0012 is raised.

  • If $collation is provided (and not the empty sequence), the comparison uses that collation; otherwise, it uses the default collation. For more information, see “Collations”.

  • This function is new in XQuery 3.1, and the three-argument version is only supported by implementations that support higher-order functions. If the function is called by a 3.1 processor but not supported, error XPST0017 will be raised..

Examples
ExampleReturn value
sort( (6, 2, 4) ) (2, 4, 6)
sort(doc("catalog.xml")//product/number) The number elements, sorted by their contents (as strings if there is no schema, or as numbers if they were validated against a schema that declared them as having a numeric type)
sort(doc("catalog.xml")//product/number/number(.)) The contents of the number elements, sorted as numbers
sort(doc("catalog.xml")//product, (),
function($prod) {$prod/number})
The product elements, sorted by the value of their number child
sort(doc("catalog.xml")//product, (),
function($prod) {$prod/name, $prod/number})
The product elements, sorted first by name and then by number
sort( (-6, -2, 4), (), abs#1) (-2, 4, -6)
Related Functions

array:sort , reverse

array:sort

Sorts an array

Signature
array:sort($array as array(*), $collation as xs:string?, 
           $key as function(item()*) as xs:anyAtomicType*) as array(*)
Usage Notes

This function sorts the members of an array, returning a new array with the members in sorted order.

If $key is not provided, the members’ typed values are used as sort keys. This is permissible for atomic values with types that allow comparisons. It will also work for elements or attributes, which will be sorted by their typed values, specifically the result of calling the data function on that member. If they are schema-validated, the sort order will take into consideration their type, for example, placing 99 before 100. Otherwise, they will be sorted as strings, where 99 will come after 100.

If $key is provided, it is a function that returns the sort key for each member. That function must return a sequence of zero or more atomic values. If the function returns multiple values for the sort key, they are compared one by one, in order. For example, if the function returns ("a", "c", "d") for the first member and ("a", "b", "f") for the second member, the second member will be placed before the first member in the result array, because b is less than c. This is analogous to specifying multiple values to sort on in an order by clause.

Special Cases
  • If any of the sort keys have typed values that can’t be compared, type error XPTY0004 is raised. This might arise either because they have mixed types (for example, a combination of xs:string and xs:integer values), or because they have a type that does not allow comparisons, such as xs:duration.

  • If $key is omitted and $array has a member for which the data function will raise an error, for example, a map or a schema-validated element with element-only content, error FOTY0012 is raised.

  • If $collation is provided (and not the empty sequence), the comparison uses that collation; otherwise, it uses the default collation. For more information, see “Collations”.

  • This function is new in XQuery 3.1, and the three-argument version is only supported by implementations that support higher-order functions. If the function is called by a 3.1 processor but not supported, error XPST0017 will be raised.

Examples
ExampleReturn value
array:sort([6, 2, 4]) [2, 4, 6]
array:sort([("a", "c", "b"), ("a", "b", "f")]) [("a", "b", "f"), ("a", "c", "b")]
array:sort( [6, 2, -4], (), abs#1) [2, -4, 6]
Related Functions

sort , array:reverse

math:sqrt

Returns the square root

Signature
math:sqrt($arg as xs:double?) as xs:double?
Usage Notes

This function returns the non-negative square root of $arg.

Special Cases
  • If $arg is the empty sequence, the function returns the empty sequence.

  • If $arg is negative zero (-0), the function returns negative zero. This is the only case where the result can have a negative sign.

  • If $arg is 0, INF, or NaN, the function returns $arg.

  • If $arg is less than 0, the function returns NaN.

  • This function is new in XQuery 3.0.

Examples
ExampleReturn value
math:sqrt(4) 2
math:sqrt(2) 1.414213562373095 (approximately)
math:sqrt(-2) NaN

starts-with

Determines whether one string starts with another

Signature
starts-with($arg1 as xs:string?, $arg2 as xs:string?,
            $collation as xs:string) as xs:boolean
Usage Notes

This function returns an xs:boolean value indicating whether one string ($arg1) starts with the characters of another string ($arg2). Leading and trailing whitespace is significant, so you may want to use the normalize-space function to trim the strings before using this function.

Special Cases
  • If $arg2 is a zero-length string or the empty sequence, the function returns true.

  • If $arg1 is a zero-length string or the empty sequence, but $arg2 is not, the function returns false.

  • If $collation is provided, the comparison uses that collation; otherwise, it uses the default collation. For more information, see “Collations”.

Examples
ExampleReturn value
starts-with("query", "que") true
starts-with("query", "query") true
starts-with("query", "u") false
starts-with("query", "") true
starts-with("", "query") false
starts-with("", "") true
starts-with("query", ()) true
starts-with(" query", "q") false

static-base-uri

Gets the static base URI

Signature
static-base-uri() as xs:anyURI?
Usage Notes

This function returns the static base URI. This may have been set by the processor outside the scope of the query, or it may have been declared in the query prolog by using a base URI declaration.

The static base URI is used for constructed elements and for resolving relative URIs when no other base URI is available. It is not the same as the base URI of any given element or document node. For more information, see “Static base URI”.

Example

static-base-uri() might return http://datypic.com/prod, if that is the static base URI.

Related Functions

base-uri , resolve-uri

string

Returns the string value of an item

Signature
string($arg as item()?) as xs:string
Usage Notes

If $arg is a node, this function returns its string value. The method of determining the string value of a node depends on its kind. Table A-8 describes how the string value is determined for each node kind.

If $arg is an atomic value, the function returns that value, cast to xs:string. For more information on casting a typed value to string, see “Casting to xs:string or xs:untypedAtomic.

Table A-8. String value based on node kind
Node kindString value
ElementThe text content of the element and all its descendant elements, concatenated together in document order. Attribute values are not included.
DocumentThe string values of all the descendant elements, concatenated together in document order. That is, the text content of the original XML document, minus all the markup.
AttributeThe attribute value.
TextThe text itself.
Processing instructionThe content of the processing instruction (everything but its target).
CommentThe content of the comment.

When $arg is a typed node, there may be some differences in the formatting such as leading and trailing whitespace and leading zeros. This is because the implementation can optionally provide the canonical representation of the value instead of the actual characters that appear in an input document. For example, if <myInt> 04 </myInt> appears in an input document, and it is validated and annotated with the type xs:integer, its string value may be returned as 4 without leading or trailing spaces instead of 04.

If you want the resulting value to be some type other than xs:string, you should use the data function instead. For example, if $myInt is bound to the myInt element from the previous paragraph, the expression data($myInt) returns the integer value 4.

Special Cases
  • If $arg is not provided, the function uses the context item. In this case, if the context item is absent, error XPDY0002 is raised.

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

  • If $arg is an element with empty content (e.g., <a></a> or <a/>), the function returns a zero-length string.

  • If $arg is a function item, including a map or array, error FOTY0014 is raised.

Examples

Given the fourth product element in our catalog:

<product dept="MEN">
  <number>784</number>
  <name language="en">Cotton Dress Shirt</name>
  <colorChoices>white gray</colorChoices>
  <desc>Our <i>favorite</i> shirt!</desc>
</product>

the string value of the product element is:

784Cotton Dress Shirtwhite grayOur favorite shirt!

assuming a schema is in place; otherwise, there will be additional whitespace between the values. The string value of the number element is 784 and the string value of the desc element is Our favorite shirt!.

Related Function

data

string-join

Concatenates a sequence of strings together, optionally using a separator

Signature
string-join($arg1 as xs:anyAtomicType*, $arg2 as xs:string) as xs:string
Usage Notes

This function concatenates the sequence of strings $arg1, optionally using a separator $arg2. If $arg2 is absent or a zero-length string, no separator is used.

Special Cases
  • If $arg1 is the empty sequence, the function returns a zero-length string.

  • The one-argument version of this function is new in XQuery 3.0.

Examples
ExampleReturn value
string-join( ("a", "b", "c"), "-") a-b-c
string-join( ("a", "b", "c"), "") abc
string-join( ("a", "b", "c") ) abc
string-join( ("a", "", "c"), "-") a--c
string-join( "a", "-") a
string-join( (), "-") A zero-length string
Related Function

concat

string-length

Finds the length of a string

Signature
string-length($arg as xs:string?) as xs:integer
Usage Notes

This function returns the number of characters in the string. Whitespace is significant, so leading and trailing whitespace characters are counted.

Special Cases
  • If $arg is not provided, the function uses the string value of the context item. In this case, if the context item is absent, error XPDY0002 is raised.

  • If $arg is the empty sequence, the function returns 0.

  • Unlike some programming languages, Unicode characters with codepoints above 65535 count as one character, not two.

Examples
ExampleReturn value
string-length("query") 5
string-length(" query ") 7
string-length(normalize-space(" query ")) 5
string-length("xml query") 9
string-length("") 0
string-length( () ) 0

string-to-codepoints

Converts a string to a sequence of Unicode codepoint values

Signature
string-to-codepoints($arg as xs:string?) as xs:integer*
Usage Notes

This function returns a sequence of integers representing the Unicode codepoints of the characters in $arg.

Special Case
  • If $arg is a zero-length string or the empty sequence, the function returns the empty sequence.

Examples
ExampleReturn value
string-to-codepoints("abc") (97, 98, 99)
string-to-codepoints("a") 97
string-to-codepoints("") ()
Related Function

codepoints-to-string

array:subarray

Extracts a portion of an array, based on a starting position and optional length

Signature
array:subarray($array as array(*), $start as xs:integer, 
               $length as xs:integer) as array(*)
Usage Notes

This function returns an array of $length members of $array, starting at the position $start. The first member in the array is considered to be at position 1, not 0. If no $length is passed, the function includes members to the end of the array.

Special Cases
  • If $start is less than one or greater than the number of members in the array, error FOAY0001 is raised. An exception is that it can be one more than the number of members in the array if $length is zero or omitted. The size of the array can be determined by calling array:size.

  • If $length is less than zero, error FOAY0002 is raised.

  • If a position is requested that does not exist in the array (i.e., $start + $length is greater than the array size + 1), error FOAY0001 is raised.

  • This function is new in XQuery 3.1.

Examples

The examples assume this variable declaration:

declare variable $array1 := ["abc", "def", "ghi", "jkl"];
ExampleReturn value
array:subarray($array1, 2) ["def", "ghi", "jkl"]
array:subarray($array1, 2, 2) ["def", "ghi"]
array:subarray($array1, 2, 1) ["def"]
array:subarray($array1, 2, 0) [ ]
array:subarray($array1, 5) [ ]
array:subarray($array1, 6) Error FOAY0001
array:subarray($array1, 2, 6) Error FOAY0001
array:subarray($array1, 2, -1) Error FOAY0002

subsequence

Extracts a portion of a sequence, based on a starting position and optional length

Signature
subsequence($sourceSeq as item()*, $startingLoc as xs:double,
            $length as xs:double) as item()*
Usage Notes

This function returns a sequence of $length items of $sourceSeq, starting at the position $startingLoc. The first item in the sequence is considered to be at position 1, not 0. If no $length is passed, or if $length is greater than the number of items that can be returned, the function includes items to the end of the sequence. An alternative to calling the subsequence function is using a predicate. For example, subsequence($a, 3, 4) is equivalent to $a[position() = (3 to 6)].

Special Cases
  • If $startingLoc is zero or negative, the subsequence starts at the beginning of the sequence and still goes to $startingLoc plus $length, so the actual length of the subsequence may be less than $length.

  • If $startingLoc is greater than the number of items in the sequence, the function returns the empty sequence.

  • If $sourceSeq is the empty sequence, the function returns the empty sequence.

  • The function will accept xs:double values for $startingLoc and $length, in which case they are rounded to the nearest integer. This is because the result type of many calculations on untyped data is xs:double. Accepting xs:double values allows $startingLoc and $length to be calculated and passed directly to the function.

Examples
ExampleReturn value
subsequence( ("a", "b", "c", "d", "e"), 3) ("c", "d", "e")
subsequence( ("a", "b", "c", "d", "e"), 3, 2) ("c", "d")
subsequence( ("a", "b", "c", "d", "e"), 3, 10) ("c", "d", "e")
subsequence( ("a", "b", "c", "d", "e"), 10) ()
subsequence( ("a", "b", "c", "d", "e"), -2, 5) ("a", "b")
subsequence( (), 3) ()

substring

Extracts part of a string, based on a starting position and optional length

Signature
substring($sourceString as xs:string?, $start as xs:double,
          $length as xs:double) as xs:string
Usage Notes

This function extracts part of a string $sourceString. $start indicates the starting location for the substring, where the first character is at position 1 (not 0). The optional $length indicates the number of characters to include, relative to the starting location. If $length is not provided, the entire rest of the string is included.

The function returns all characters whose position is greater than or equal to $start and less than ($start + $length). The $start number can be zero or negative, in which case the function starts at the beginning of the string, and still only includes characters up to (but not including) the position at ($start + $length). If ($start + $length) is greater than the length of the string, the rest of the string is included.

Special Cases
  • If $sourceString is the empty sequence, the function returns a zero-length string.

  • If $start is greater than the length of the string, the function returns a zero-length string.

  • The function will accept xs:double values for $start and $length, in which case they are rounded to the nearest integer.

Examples
ExampleReturn value
substring("query", 1) query
substring("query", 3) ery
substring("query", 1, 1) q
substring("query", 2, 3) uer
substring("query", 2, 850) uery
substring("query", 6, 2) A zero-length string
substring("query", -2) query
substring("query", -2, 5) qu
substring("query", 1, 0) A zero-length string
substring("", 1) A zero-length string

substring-after

Extracts the substring that is after the first occurrence of another specified string

Signature
substring-after($arg1 as xs:string?, $arg2 as xs:string?,
                $collation as xs:string) as xs:string
Usage Notes

This function extracts all the characters of the string $arg1 that appear after the first occurrence of the string $arg2.

Special Cases
  • If $arg1 does not contain $arg2, the function returns a zero-length string.

  • If $arg2 is a zero-length string or the empty sequence, the function returns $arg1 in its entirety.

  • If $arg1 is a zero-length string or the empty sequence, and $arg2 is not, the function returns a zero-length string.

  • If $collation is provided, the comparison uses that collation; otherwise, it uses the default collation. For more information, see “Collations”.

Examples
ExampleReturn value
substring-after("query", "u") ery
substring-after("queryquery", "ue") ryquery
substring-after("query", "y") A zero-length string
substring-after("query", "x") A zero-length string
substring-after("query", "") query
substring-after("", "x") A zero-length string
Related Functions

substring, substring-before

substring-before

Extracts the substring that is before the first occurrence of another specified string

Signature
substring-before($arg1 as xs:string?, $arg2 as xs:string?,
                 $collation as xs:string) as xs:string
Usage Notes

This function extracts all the characters of the string $arg1 that appear before the first occurrence of the string $arg2.

Special Cases
  • If $arg1 does not contain $arg2, the function returns a zero-length string.

  • If either $arg1 or $arg2 is a zero-length string or the empty sequence, the function returns a zero-length string.

  • If $collation is provided, the comparison uses that collation; otherwise, it uses the default collation. For more information, see “Collations”.

Examples
ExampleReturn value
substring-before("query", "r") que
substring-before("query", "ery") qu
substring-before("queryquery", "ery") qu
substring-before("query", "query") A zero-length string
substring-before("query", "x") A zero-length string
substring-before("query", "") A zero-length string
substring-before("query", ()) A zero-length string
Related Functions

substring, substring-after

sum

Calculates the total value of the items in a sequence

Signature
sum($arg as xs:anyAtomicType*,
    $zero as xs:anyAtomicType?) as xs:anyAtomicType?
Usage Notes

The $arg sequence can contain a mixture of numeric and untyped values. Numeric values are promoted as necessary to make them all the same type. Untyped values are cast as numeric xs:double values.

The function can also be used on duration values, so the $arg sequence can contain all xs:yearMonthDuration values or all xs:dayTimeDuration values (but not a mixture of the two). The $arg sequence cannot contain a mixture of duration and numeric values.

$zero optionally specifies an alternate value for the sum of the empty sequence. If $arg is the empty sequence, and $zero is provided, the function returns $zero. $zero could be the empty sequence, the integer 0, the value NaN, a duration of zero seconds, or any other atomic value. The main use cases of $zero are (a) to supply numeric zero in the desired datatype, e.g., xs:decimal, and (b) to supply a zero duration if you are summing durations. Since the processor, in the absence of static typing, cannot tell the difference between a zero-length sequence of numbers and a zero-length sequence of durations, this is the only way to tell it which kind of value is being totaled.

Special Cases
  • If $arg is the empty sequence, and $zero is not provided, the function returns the xs:integer value 0.

  • If $arg contains any NaN values, the function returns NaN.

  • If $arg contains untyped values that cannot be cast to xs:double, error FORG0001 is raised.

  • If $arg contains values of different types, or values that are not numbers or durations, error FORG0006 is raised.

Examples
ExampleReturn value
sum( (1, 2, 3) ) 6
sum(doc("order.xml")//item/@quantity) 7
sum(doc("order.xml")//item/@dept) Error FORG0001
sum( (xs:yearMonthDuration("P1Y2M"), xs:yearMonthDuration("P2Y3M")) ) P3Y5M
sum( (1, 2, 3, () ) ) 6
sum( (1, 2, xs:yearMonthDuration("P1Y")) ) Error FORG0006
sum( () ) 0
sum( (), () ) ()

tail

Returns all items in a sequence except the first one

Signature
tail($arg as item()*) as item()*
Usage Notes

This function returns all the items in $arg except the first one (the head).

Special Cases
  • If $arg is the empty sequence, the function returns the empty sequence.

  • If $arg contains only one item, the function returns the empty sequence.

  • This function is new in XQuery 3.0.

Examples
ExampleReturn value
tail( ("a", "b", "c" ) ) ("b", "c")
tail("a") ()
tail(1 to 3) (2, 3)
tail(tail(1 to 3)) 3
head(tail(1 to 3)) 2
tail(doc("catalog.xml")//product) The second, third, and fourth product

array:tail

Returns an array without its first member

Signature
array:tail($array as array(*)) as array(*)
Usage Notes

This function returns an array containing all members of $array except for the first one (the head). It is equivalent to array:remove($array, 1).

Special Cases
  • If the array is empty, error FOAY0001 is raised.

  • This function is new in XQuery 3.1.

Examples
ExampleReturn value
array:tail(["abc", "def", "ghi"]) ["def", "ghi"]
array:tail(["abc", "def"]) ["def"]
array:tail(["abc"]) [ ]
array:tail([]) Error FOAY0001
Related Functions

array:head , head , tail

math:tan

Returns the tangent

Signature
math:tan($θ as xs:double?) as xs:double?
Usage Notes

This function finds the tangent of , which is an angle, in radians.

Special Cases
  • If is the empty sequence, the function returns the empty sequence.

  • If is INF, -INF, or NaN, the result is NaN.

  • This function is new in XQuery 3.0.

Examples
ExampleReturn value
math:tan(math:pi() div 4) 1 (approximately)
math:tan(math:pi()) 0 (approximately)
math:tan(0) 0

timezone-from-date

Gets the time zone of a date

Signature
timezone-from-date($arg as xs:date?) as xs:dayTimeDuration?
Usage Notes

This function returns the time zone of an xs:date value, offset from UTC, as an xs:dayTimeDuration value between -PT14H and PT14H, inclusive. If the time zone is UTC, the value PT0S is returned.

Special Cases
  • If $arg is the empty sequence, the function returns the empty sequence.

  • If $arg does not have an explicit time zone, the function returns the empty sequence. It does not return the implicit time zone.

Examples
ExampleReturn value
timezone-from-date( xs:date("2015-08-15-05:00") ) -PT5H
timezone-from-date(xs:date("2015-08-15Z")) PT0S
timezone-from-date(xs:date("2015-08-15")) ()

timezone-from-dateTime

Gets the time zone of a date/time

Signature
timezone-from-dateTime($arg as xs:dateTime?) as xs:dayTimeDuration?
Usage Notes

This function returns the time zone of an xs:dateTime value, offset from UTC, as an xs:dayTimeDuration value between -PT14H and PT14H, inclusive. If the time zone is UTC, the value PT0S is returned.

Special Cases
  • If $arg is the empty sequence, the function returns the empty sequence.

  • If $arg does not have an explicit time zone, the function returns the empty sequence. It does not return the implicit time zone.

Examples
ExampleReturn value
timezone-from-dateTime( xs:dateTime("2015-08-15T10:30:23-05:00") ) -PT5H
timezone-from-dateTime( xs:dateTime("2015-08-15T10:30:23Z") ) PT0S
timezone-from-dateTime(xs:dateTime("2015-08-15T10:30:23")) ()

timezone-from-time

Gets the time zone of a time

Signature
timezone-from-time($arg as xs:time?) as xs:dayTimeDuration?
Usage Notes

This function returns the time zone of an xs:time value, offset from UTC, as an xs:dayTimeDuration value between -PT14H and PT14H, inclusive. If the time zone is UTC, the value PT0S is returned.

Special Cases
  • If $arg is the empty sequence, the function returns the empty sequence.

  • If $arg does not have an explicit time zone, the function returns the empty sequence. It does not return the implicit time zone.

Examples
ExampleReturn value
timezone-from-time(xs:time("09:54:00-05:00")) -PT5H
timezone-from-time(xs:time("09:54:00+05:00")) PT5H
timezone-from-time(xs:time("09:54:00Z")) PT0S
timezone-from-time(xs:time("09:54:00")) ()

tokenize

Breaks a string into a sequence of strings

Signature
tokenize($input as xs:string?, $pattern as xs:string,
         $flags as xs:string) as xs:string*
Usage Notes

This function breaks the string $input into a sequence of strings. The $pattern argument is a regular expression that represents the separator. The regular expression syntax is covered in Chapter 19. The simplest patterns can be a single space, or a string that contains the separator character, such as , (comma). However, certain characters must be escaped in regular expressions, namely . ? * + | ^ $ { } () [ and ]. Table A-9 shows some useful patterns for separators.

Table A-9. Useful separator patterns
PatternMeaning
s A single whitespace character (space, tab, carriage return, or line feed)
s+ One or more consecutive whitespace characters
, Comma
,s* A comma followed by zero or more whitespace characters
[,s]+ One or more consecutive commas and/or whitespace characters
Tab character
[ ]+ One or more consecutive carriage return and/or line-feed characters
W+ One or more non-word characters

The separators are not included in the result strings. If two adjacent separators appear, a zero-length string is included in the result sequence. If the string starts with the separator, a zero-length string is the first value returned. Likewise, if the string ends with the separator, a zero-length string is the last value in the result sequence.

$flags allows for additional options in the interpretation of the regular expression, such as multi-line processing and case insensitivity. It is discussed in detail in “Using Flags”.

If a particular point in the string could match more than one alternative, the first alternative is chosen. This is exhibited in the last row in the Example table, where the function considers the comma to be the separator, even though "-x" also applies.

If $pattern is not provided, the string is tokenized on consecutive whitespace, with leading and trailing spaces ignored. In other words, tokenize($arg) is equivalent to tokenize(normalize-space($arg), ' ')).

Special Cases
  • If $input does not match $pattern, it is returned as is.

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

  • If $pattern is not a valid regular expression, error FORX0002 is raised.

  • If the entire $pattern matches a zero-length string, for example q?, error FORX0003 is raised.

  • If $flags contains unsupported options, error FORX0001 is raised.

  • The one-argument version of the function is new in XQuery 3.1.

Examples
ExampleReturn value
tokenize("a b c", "s") ("a", "b", "c")
tokenize("a   b c", "s") ("a", "", "", "b", "c")
tokenize("a    b c", "s+") ("a", "b", "c")
tokenize(" b c", "s") ("", "b", "c")
tokenize("a-b-c", "-") ("a", "b", "c")
tokenize("a-b--c", "-") ("a", "b", "", "c")
tokenize("a, b, c", "[,s]+") ("a", "b", "c")
tokenize("2015-12-25T12:15:00", "[-T:]") ("2015", "12", "25", "12", "15", "00")
tokenize("Hello, there.", "W+") ("Hello", "there", "")
tokenize( (), "s+") ()
tokenize("abc", "s") abc
tokenize("abcd", "b?") Error FORX0003
tokenize("a-xb-xc", "-|-x") ("a", "xb", "xc")
tokenize(" a b c ") ("a", "b", "c")
Related Function

analyze-string

trace

Traces the value of an item for debugging or logging purposes

Signature
trace($value as item()*, $label as xs:string) as item()*
Usage Notes

This function accepts an item and a label for that item, and returns the item unchanged. The exact behavior of the function is implementation-dependent, but generally the processor puts the label and the value of the item in a log file or user console for debugging purposes. If $label is not provided, an implementation-dependent label might be used.

Special Case
  • The one-argument version of this function is new in XQuery 3.1.

Example

trace($var1, "The value of the variable is: ") will return the value of $var1 and it might write the string The value of the variable is: 4 to a log file.

Related Function

error

transform

Invokes an XSLT to run a transformation

Signature
transform($options as map(*)) as map(*)
Usage Notes

This function invokes an XSLT and returns the result as a map that contains one or more result documents. This is useful for delegating tasks to XSLT that it is better suited to perform, like detailed transformations of narrative content for display.

The result of the function is a map that contains an entry for the principal output document, whose key will be the value of the base-output-uri option, if provided, or the string output otherwise. If any secondary result documents are created using xsl:result-document in the stylesheet, they will each have an entry in the result map, where the key is the absolute URI of the document (derived from the href attribute on xsl:result-document).

$options is a map that has the following possible entries, whose keys are strings. They are all optional, except that:

  • Exactly one of the following must be provided: stylesheet-location, stylesheet-node, stylesheet-text, package-location, package-node, package-text, or package-name.

  • source-node is required unless one of the less common options initial-template, initial-function or initial-match-selection is provided.

KeyType of valueDescription
base-output-uri xs:string URI of the principal result document, used for example for resolving relative URIs in xsl:result-document elements in the stylesheet. If it is relative, it is evaluated relative to the static base URI.
cache xs:boolean Whether the processor should cache the stylesheet for future use, for efficiency. If the stylesheet will be used only once in the query execution, the value false should be used. Otherwise, the default value is true.
delivery-format "document", "raw", or "serialized" If the value is document (the default), the function will return a document node in the results. If the value is raw, the result is returned as a sequence of items, not wrapped in a document node. If the value is serialized, the function will return a serialized string containing the stylesheet output.
enable-assertions xs:boolean Whether xsl:assert instructions should be evaluated. XSLT 3.0 only.
enable-messages xs:boolean Whether xsl:message instructions should be evaluated.
enable-trace xs:boolean Whether fn:trace functions in the stylesheet should generate messages. XSLT 2.0 and 3.0 only.
function-params array(*) Values to be used as arguments to the initial function call. XSLT 3.0 only.
global-context-item item() Value of the global context item. XSLT 3.0 only.
initial-function xs:QName Name of the initial function to be called. XSLT 3.0 only.
initial-match-selection item()* Value of the initial match selection. XSLT 3.0 only.
initial-mode xs:QName Name of the initial processing mode.
initial-template xs:QName Name of the named template that is the starting point for the stylesheet. XSLT 2.0 and 3.0 only.
package-name xs:string Name of the top-level stylesheet package to be invoked, as an absolute URI. XSLT 3.0 only.
package-location xs:string URI (relative or absolute) of the location of the top-level stylesheet package. XSLT 3.0 only.
package-node node() Document or element node containing the top-level stylesheet package. XSLT 3.0 only.
package-text xs:string Top-level stylesheet package as a string that uses valid (unparsed) XML syntax. XSLT 3.0 only.
package-version xs:string Version of the top-level stylesheet package to be invoked. XSLT 3.0 only.
post-process function (xs:string, item()*) as item()* Function to call to post-process each result document. The first argument to the post-process function identifies the result document in the map return by the transform function (for example, the string “output” if no base output URI was supplied). The second argument is the actual value (a document node, a sequence of items, or a string, depending on what value was chosen for delivery-format). The transform function will return the result of the post-process function.
requested-properties map(xs:QName, xs:anyAtomicType) Map requesting an XSLT processor with certain system properties. For example, specifying xsl:xsd-version as a key with the value 1.1 requests a processor that supports XML Schema version 1.1. The allowed map keys are the list of values allowed as the first parameter of the XSLT system-property function.
serialization-params map(xs:anyAtomicType, item()*) Serialization parameters for the principal result document, which will override any parameters set in xsl:output in the stylesheet. Each entry has a key that is the name of a serialization parameter and a value that is the value of the parameter. See “Serialization Parameters” for a complete list and a description of how to specify them as a map.
source-node node() Node that is to be transformed by the stylesheet.
static-params map(xs:QName, item()*) Values of static parameters in the stylesheet. Each entry’s key is the parameter name and its value is the parameter value. XSLT 3.0 only.
stylesheet-base-uri xs:string Static base URI of the principal stylesheet, used for example for resolving relative URIs in xsl:import or xsl:include elements in the stylesheet. If it is relative, it is evaluated relative to the static base URI. If absent, it defaults to the value of stylesheet-location.
stylesheet-location xs:string URI for the location of the principal stylesheet. If it is a relative URI, it is resolved against the static base URI.
stylesheet-node node() Stylesheet supplied as a node, either as an element (e.g., xsl:stylesheet or xsl:transform) or a document node that contains a stylesheet element.
stylesheet-params map(xs:QName, item()*) Map containing parameters to pass to the stylesheet. Each entry’s key is the parameter name and its value is the parameter value.
stylesheet-text xs:string Stylesheet supplied as a text string, which can be parsed as XML into a stylesheet (e.g., xsl:stylesheet or xsl:transform element).
template-params map(xs:QName, item()*) Values of non-tunnel parameters to be supplied to the initial template. Each entry’s key is the parameter name and its value is the parameter value. XSLT 3.0 only.
tunnel-params map(xs:QName, item()*) Values of tunnel parameters to be supplied to the initial template. Each entry’s key is the parameter name and its value is the parameter value. XSLT 3.0 only.
vendor-options map{xs:QName, item()*} Implementation-defined options. Each entry’s key is the name of an option (as an xs:QName in the namespace controlled by the vendor) and its value is interpreted in an implementation-defined way. Implementations will ignore options in namespaces they don’t recognize.
xslt-version xs:decimal Minimum version of XSLT that the processor must support, e.g. 1.0, 2.0, or 3.0. If not specified, the version attribute in the XSLT stylesheet is used.

Additional implementation-defined options can be included in the $options map.

Special Cases
  • If no suitable XSLT processor is available, error FOXT0001 is raised.

  • If the parameters are invalid, for example two mutually exclusive parameters were supplied, error FOXT0002 is raised.

  • If the XSLT fails with a static or dynamic error, the query fails and the error reported by the XSLT is retained. If no specific XSLT error code is available, error FOXT0003 is raised.

  • If XSLT transformation (or a specific transformation option) has been disabled for security or other reasons, error FOXT0004 is raised.

  • This function is new in XQuery 3.1.

Example

A simple example of invoking a stylesheet with the minimum number of options is shown in Example A-19. It passes the document node of catalog.xml and the URI of a stylesheet to the transform function. The result of the function is a map, but the query uses the lookup operator ?output to return the result of the transformation, a p element.

Example A-19. Calling the transform function

Query

xquery version "3.1";
let $result := transform(
  map {
    "stylesheet-location": "render.xsl",
    "source-node": doc("catalog.xml")
  })
return $result?output

Contents of render.xsl

<xsl:stylesheet version="2.0"
                xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:template match="catalog">
    <p>There are <xsl:value-of select="count(product)"/> products.</p>
  </xsl:template>
</xsl:stylesheet>

Results

<p>There are 4 products.</p>

Example A-20 shows a slightly more complex example that passes parameters to the stylesheet. The QName function is used because the keys in the stylesheet-params maps need to be xs:QName values. Since the parameter names are not in a namespace in this case, a zero-length string is passed as the first argument to QName.

Example A-20. Calling the transform function with stylesheet parameters

Query

xquery version "3.1";
let $result := transform(
  map {
    "stylesheet-location": "render2.xsl",
    "source-node": doc("catalog.xml"),
    "stylesheet-params": map { QName("", "label"): "Note",
                               QName("", "msg"): "Hi!"}
  })
return $result?output

Contents of render2.xsl

<xsl:stylesheet version="2.0"
                xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:param name="label"/>              
  <xsl:param name="msg"/>              
  <xsl:template match="catalog">
    <p>
      <xsl:value-of select="$label"/>
      <xsl:text>: </xsl:text>
      <xsl:value-of select="$msg"/>
      <xsl:text>. There are </xsl:text>
      <xsl:value-of select="count(product)"/>
      <xsl:text> products.</xsl:text>
    </p>
  </xsl:template>
</xsl:stylesheet>

Results

<p>Note: Hi! There are 4 products.</p>

translate

Replaces individual characters in a string with other individual characters

Signature
translate($arg as xs:string?, $mapString as xs:string,
          $transString as xs:string) as xs:string
Usage Notes

This function replaces individual characters in the string $mapString with replacement characters in $transString. Each character in $mapString is replaced by the character in the same position in $transString. If $mapString is longer than $transString, the characters in $mapString that have no corresponding character in $transString are not included in the result. Characters in the original string that do not appear in $mapString are copied to the result unchanged.

Note that this function is only for replacing individual characters with other individual characters or for removing individual characters. If you want to replace sequences of characters, you should use the replace function instead. This function has historically been used for translating strings between lowercase and uppercase, but the upper-case and lower-case functions do this more robustly based on Unicode mappings.

Special Cases
  • If $arg is the empty sequence or a zero-length string, the function returns a zero-length string.

  • If $mapString is a zero-length string, the function returns $arg unchanged.

Examples
ExampleReturn value
translate("2015/01/02", "/", "-") 2015-01-02
translate("xml query", "qlmx", "QLMX") XML Query
translate("xml query", "qlmx ", "Q") Query
translate("xml query", "qlmx ", "") uery
translate("xml query", "abcd", "ABCD") xml query
translate("", "qlmx ", "Q") A zero-length string
translate( (), "qlmx ", "Q") A zero-length string
Related Function

replace

true

Constructs a Boolean true value

Signature
true() as xs:boolean
Usage Notes

This function, which takes no arguments, is useful for constructing the Boolean value true. XQuery uses false() and true() function calls instead of keywords false and true. This is most commonly used to supply a value in a function call where a Boolean value is required.

Example

The expression true() returns the xs:boolean value true.

Related Functions

false, boolean

unordered

Signals to the processor that order is insignificant

Signature
unordered($sourceSeq as item()*) as item()*
Usage Notes

In cases where the order of the results does not matter, the processor may be much more efficient if it does not have to keep track of order. This is especially true for FLWORs that perform joins. For example, processing multiple variable bindings in a for clause might be significantly faster if the processor can decide which variable binding controls the join without regard to the order of the results. A query author can tell the processor that order does not matter by enclosing an expression in a call to the unordered function.

Example

The following query returns the value of the FLWOR expression in an implementation-dependent order rather than document order. It may perform faster than if the FLWOR were not enclosed in the function call.

unordered(
for $item in doc("order.xml")//item,
    $prod in doc("catalog.xml")//product
where $item/@num = $prod/number
return
  <item number="{$item/@num}" name="{$prod/name}"
        quantity="{$item/@quantity}"/>
)

unparsed-text

Opens a document as a text string

Signature
unparsed-text($href as xs:string?, $encoding as xs:string) as  xs:string?
Usage Notes

This function opens a document and supplies it as a text string. This is useful for parsing non-XML documents, such as comma-delimited or fixed-width formats. When combined with the analyze-string or tokenize functions, this is a powerful way to include non-XML content in a query.

The $href URI can be absolute or relative, in which case it is resolved against the static base URI. It cannot contain a fragment identifier (indicated by a hash mark #). The detailed rules for how the function resolves the URI in $href are described in “Resolving URIs of input documents”.

The optional $encoding parameter indicates the encoding of the document. This value may be used by the processor if it cannot determine the encoding from external information.

If there is any doubt about whether the document exists or is correctly encoded, it is advisable to call the unparsed-text-available function before this function to avoid fatal errors.

Special Cases
  • If $href is the empty sequence, the function returns the empty sequence.

  • If there is a problem with $href (such as not pointing to a resource, containing a fragment identifier #, or being relative when there is no static base URI), error FOUT1170 is raised.

  • If there is a problem with $encoding (such as not being a valid encoding name, being an unsupported encoding, or not accurately representing the encoding of the document), error FOUT1190 is raised.

  • If $encoding is absent, the document is not encoded as UTF-8, and the processor cannot determine the encoding, error FOUT1200 is raised.

  • This function is new in XQuery 3.0.

Examples

Given a text document dept-filter.txt as follows:

ACC-MEN

the following query will parse this document and return only the products whose department is listed in the text document:

let $deptnames := tokenize(unparsed-text("dept-filter.txt"), '-')
return doc("catalog.xml")//product[@dept = $deptnames]

unparsed-text-available

Determines whether a text document is available

Signature
unparsed-text-available($href as xs:string?, 
                        $encoding as xs:string) as xs:boolean
Usage Notes

This function is a way to avoid errors returned by the unparsed-text, unparsed-text-lines, or json-doc functions if a text document is not available or has encoding errors. This function will return true if calling the unparsed-text function on the same URI will succeed and result in a text string. It will return false if the unparsed-text function will fail for any reason.

Special Cases
  • If $href is the empty sequence, the function returns false.

  • This function is new in XQuery 3.0.

Examples

This query will check if a text document named dept-filter.txt is available:

if (unparsed-text-available("dept-filter.txt"))
then unparsed-text("dept-filter.txt")
else ()

If a document is available, it will return it as a string. Otherwise, it will return the empty sequence. If the unparsed-text function had been called without verifying the existence of the document first, an error might have been raised.

unparsed-text-lines

Opens a document as a sequence of text strings, one per line

Signature
unparsed-text-lines($href as xs:string?, $encoding as xs:string) as xs:string*
Usage Notes

This function opens a document and supplies it as one or more text strings, one for each line of the document. This is useful for parsing non-XML documents, such as comma-delimited or fixed-width formats. When combined with the analyze-string or tokenize functions, this is a powerful way to include non-XML content in a query.

It is similar to the unparsed-text function except that it tokenizes the document on line breaks. For the purposes of this function, a line break is either a carriage return, a line feed, or a carriage return followed by a line feed. If the document contains two line breaks in a row, a zero-length string is included in the result sequence.

If the document ends in a line break, it does not include a zero-length string as the last string. Therefore, unparsed-text-lines($href) is equivalent to:

tokenize(unparsed-text($href), '
|
|
')[not(position()=last() and .='')]

The interpretation of the $href and $encoding parameters is the same as for the unparsed-text function.

If there is any doubt about whether the document exists or is correctly encoded, it is advisable to call the unparsed-text-available function before this function to avoid fatal errors.

Special Cases
  • This function has the same special cases as the unparsed-text function.

  • This function is new in XQuery 3.0.

Examples

Given a text document deptnames.txt as follows:

ACC-Accessories
MEN-Men's
WMN-Women's

the following query will parse this document and return the product numbers with their full department names:

let $deptnames := unparsed-text-lines("deptnames.txt")
for $prod in doc("catalog.xml")//product
let $deptnameline := $deptnames[substring-before(., '-') = $prod/@dept]
return concat($prod/number, ': ', substring-after($deptnameline, '-'))

upper-case

Converts a string to uppercase

Signature
upper-case($arg as xs:string?) as xs:string
Usage Notes

The mappings between lowercase and uppercase characters are determined by Unicode case mappings. If a character in $arg does not have a corresponding uppercase character, it is included in the result string unchanged.

For English, you can do a case-blind comparison by writing upper-case($A)=upper-case($B) (or use lower-case instead). However this doesn’t always work well for other languages. It’s better to use a case-insensitive collation.

Special Case
  • If $arg is the empty sequence, the function returns a zero-length string.

Examples
ExampleReturn value
upper-case("query") QUERY
upper-case("QUERY") QUERY
upper-case("Query") QUERY
upper-case("query-123") QUERY-123
upper-case("Schlo&#223;") SCHLOSS
Related Function

lower-case

uri-collection

Lists all the URIs in a collection

Signature
uri-collection($arg as xs:string?) as xs:anyURI*
Usage Notes

This function returns a list of the URIs of resources in the collection whose URI is $arg. It provides a more efficient way of determining what is in a collection without having to retrieve the whole collection by using the collection function, which may take time and memory. It can be used to trap errors (by using doc-available) in the case where a collection may contain non-well-formed, non-XML, or missing documents. It is also useful if the intent is to only work with a subset of the collection, for example, the first 100 documents or the ones whose URI matches a particular pattern.

If $arg is a relative URI, it is resolved based on the static base URI.

Most typically, this function returns URIs of XML documents, but it is possible for the function to return URIs of non-XML documents that could be retrieved by the unparsed-text function.

By default, the uri-collection function is deterministic. This means that if you call it more than once with the exact same argument, within the same query, the result is the same, even if somehow the resources associated with the URI have changed. Implementations may, however, offer users a way to indicate that determinism is not important, for performance reasons.

Special Cases
  • If $arg is not a collection URI known to the processor, error FODC0002 is raised.

  • If $arg is a relative URI and there is no static base URI to use to resolve the relative URI, error FODC0002 is raised.

  • If $arg is not provided, or is the empty sequence, the function uses the default collection. In those cases, if the default collection is absent, error FODC0002 is raised.

  • If $arg is not a lexically valid URI, error FODC0004 may be raised.

  • If the processor cannot return deterministic results, error FODC0003 is raised.

  • This function is new in XQuery 3.0.

Examples

The expression uri-collection("myXMLdocs") will return the URIs of all the documents associated with the collection myXMLdocs. The following query could be used to parse only the first 100 documents in the collection, if they are well-formed XML:

for $uri in uri-collection("myXMLdocs")[position() < 101]
where doc-available($uri)
return doc($uri)
Related Function

collection

xml-to-json

Converts XML to JSON

Signature
xml-to-json($input as node()?, $options as map(*)) as xs:string?
Usage Notes

This function takes an XML node and converts it into a string in JSON syntax. It is not a generic XML-to-JSON converter; the $input XML must conform to a particular schema that has elements such as map, array, and string that map cleanly onto JSON constructs. Details of how JSON constructs are mapped to the XML are provided in “Converting Between JSON and XML”.

$options is a map that can be used to control the parsing. It has only one possible entry, whose key is a string:

indent

Boolean value indicating whether the JSON should be indented to improve readability. If the value is true, an implementation may choose to insert insignificant whitespace into the JSON string.

Additional implementation-defined options can be included in the $options map.

Special Cases
  • If $input is the empty sequence, the function returns the empty sequence.

  • If $options contains an invalid value, error FOJS0005 is raised.

  • If $input is not a valid document or element node, error FOJS0006 is raised.

  • If $input contains an element with escaped="true" or escaped-key="true", and the content of the string or key contains an invalid JSON escape sequence, error FOJS0007 is raised.

  • This function is new in XQuery 3.1.

Examples

Calling the function with an XML element as follows:

xml-to-json(<map xmlns="http://www.w3.org/2005/xpath-functions">
  <number key="number">557</number>
  <string key="name">Fleece Pullover</string>
  <array key="colorChoices">
    <string>navy</string>
    <string>black</string>
  </array>
  <boolean key="is-current">true</boolean>
  <null key="other"/>
</map>,
map{"indent":true()})

might return the following JSON string:

{  "number": 557,
   "name": "Fleece Pullover",
   "colorChoices": ["navy", "black"],
   "is-current": true,
   "other": null }

Additional examples of converting XML to JSON can be found in “Converting Between JSON and XML”.

Related Function

json-to-xml

year-from-date

Gets the year portion of a date

Signature
year-from-date($arg as xs:date?) as xs:integer?
Usage Notes

This function returns the year portion of an xs:date value as an integer.

Special Cases
  • If the year is negative, the function returns a negative number.

  • If $arg is the empty sequence, the function returns the empty sequence.

Example

year-from-date(xs:date("2015-08-15")) returns 2015.

Related Function

year-from-dateTime

year-from-dateTime

Gets the year portion of a date/time

Signature
year-from-dateTime($arg as xs:dateTime?) as xs:integer?
Usage Notes

This function returns the year portion of an xs:dateTime value as an integer.

Special Cases
  • If the year is negative, the function returns a negative number.

  • If $arg is the empty sequence, the function returns the empty sequence.

Example

year-from-dateTime(xs:dateTime("2015-08-15T10:30:23")) returns 2015.

Related Function

year-from-date

years-from-duration

Gets the number of years in a duration

Signature
years-from-duration($arg as xs:duration?) as xs:integer?
Usage Notes

This function calculates the years component of an xs:duration value. This is not necessarily the same as the integer that appears before the Y in the value. For example, if the duration is P1Y18M, the function returns 2 rather than 1. This is because 18 months is equal to 1.5 years, and the canonical value is therefore P2Y6M.

Special Cases
  • If $arg is a negative duration, the function returns a negative value.

  • If $arg is the empty sequence, the function returns the empty sequence.

Examples
ExampleReturn value
years-from-duration(xs:duration("P3Y")) 3
years-from-duration(xs:duration("P3Y11M")) 3
years-from-duration(xs:duration("-P18M")) -1
years-from-duration(xs:duration("P1Y18M")) 2
years-from-duration(xs:duration("P12M")) 1

zero-or-one

Verifies that a sequence does not contain more than one item

Signature
zero-or-one($arg as item()*) as item()?
Usage Notes

If $arg contains zero or one items, $arg is returned. Otherwise, error FORG0003 is raised.

This function is useful when static typing is in effect, to avoid apparent static type errors. For example, to use the number function on a particular price, you might be tempted to write the expression:

number (doc("prices.xml")//prod[@num = 557]/price)

However, if static typing is used, this expression causes a static error. This is because there could be more than one price element that matches that criterion, while the number function requires that zero or one item be provided. A static error can be avoided by using the expression:

number (zero-or-one(doc("prices.xml")//prod[@num = 557]/price))

In this case, no static error is raised. Rather, a dynamic error is raised if more than one price element is returned by the path expression. For more information on static typing, see Chapter 15.

If static typing is not in effect, calling zero-or-one is not usually necessary, but it does no harm. The effect is usually to make explicit a runtime type check that would otherwise have been done automatically.

Examples
ExampleReturn value
zero-or-one( () ) ()
zero-or-one("a") a
zero-or-one( ("a", "b") ) Error FORG0003
Related Functions

one-or-more, exactly-one

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.19.211.134