Appendix C. Function Reference

Introduction

This appendix describes all of the built-in XQuery functions, listed alphabetically for convenient reference. Each function description begins with a one-line summary of the function's purpose followed by its function signature(s). Next comes an explanation of the arguments and their default values (if any), exceptional and error cases, and finally the function's normal behavior with examples. Each function is also cross-referenced to related functions.

The type syntax used in the function signature is the sequence type syntax described in Chapter 2 and Appendix A, with the same meaning. For example, xs:string? means zero or one string values.

All XQuery built-in functions belong to the default function namespace, http://www.w3.org/2003/11/xpath-functions, which is associated with the built-in namespace prefix fn. For example, the true() function can also be written fn:true(). For brevity, I omitted these prefixes everywhere except section headers.

In addition to the functions listed here, XQuery also defines constructor functions for the built-in types. See Chapter 2 and Appendix A for information.

The return value has the same type as the argument.

If the argument is the empty sequence, then abs() returns the empty sequence. Otherwise, abs() returns the absolute value of the argument. (Negative values are negated, non-negative values are returned unchanged.)

Example C.1. abs examples

abs(2)        =>  2
abs(-2)       =>  2
abs(-1.5)     =>  1.5
abs(-1 div 0) =>  INF

See also: Chapter 5.

The first parameter is the date to be adjusted. The optional second parameter is the time zone to use; when omitted, the implicit time zone is used.

If the first argument is the empty sequence, then the empty sequence is returned. An error is raised if the time zone is less than -PT14H00M or greater than PT14H00M.

Otherwise, this function returns a date value with its time zone replaced by the provided time zone. If the provided time zone is the empty sequence, then the date is returned without a time zone (removing the time zone from the original date, if it had one).

Example C.2. adjust-date-to-timezone example

adjust-date-to-timezone(xs:date('2004-05-13'),
                        xdt:dayTimeDuration('PT6H00M'))

See also: adjust-dateTime-to-timezone(), adjust-time-to-timezone(), and implicit-timezone().

The first argument is the xs:dateTime value to be adjusted. The optional second argument is the time zone to use; when omitted, the implicit time zone is used.

If the first argument is the empty sequence, then the empty sequence is returned. An error is raised if the time zone is less than -PT14H00M or greater than PT14H00M.

Otherwise, this function returns a dateTime value with its time zone replaced by the provided time zone. If the provided time zone is the empty sequence, then the dateTime is returned without a time zone (removing the time zone from the original dateTime, if it had one).

Example C.3. adjust-dateTime-to-timezone example

adjust-dateTime-to-timezone(xs:dateTime('2004-05-13T09:55:00'),
                        xdt:dayTimeDuration('PT6H00M'))

See also: adjust-date-to-timezone(), adjust-time-to-timezone(), and implicit-timezone().

The adjust-time-to-timezone function can be used to construct a time with a particular time zone value.

The first argument is the time to be adjusted. The optional second argument is the time zone to use; when omitted, the implicit time zone is used.

If the first argument is the empty sequence, then the empty sequence is returned. An error is raised if the time zone is less than -PT14H00M or greater than PT14H00M.

Otherwise, this function returns a time value with its time zone replaced by the provided time zone. If the provided time zone is the empty sequence, then the time is returned without a time zone (removing the time zone from the original time, if it had one).

Example C.4. adjust-time-to-timezone example

adjust-time-to-timezone(xs:time('09:55:00'),
                        xdt:dayTimeDuration('PT6H00M'))

See also: adjust-date-to-timezone(), adjust-dateTime-to-timezone(), and implicit-timezone().

The argument is the sequence of values to be averaged.

If the sequence is empty, then the empty sequence is returned. Untyped items are converted to xs:double. If all items in the sequence cannot be promoted to a common type, or don't have types that can be summed and divided by an integer, then an error occurs.

Otherwise, all items in the sequence are promoted to a common type, summed, and divided by the number of items in the sequence to produce the average result. If any value in the sequence is NaN, then the result is NaN.

Example C.5. avg examples

avg((1.0, 2, 3.0E0)) => 2.0E0
avg(())              => ()
avg(0)               => 0
avg(1, 3)            => 2

See also: count(), max(), min(), and sum().

The optional first argument specifies the node to use. When omitted, the base-uri is selected from the static context.

If the node doesn't have a base-uri, or its base-uri is empty, then the base-uri of its parent (if it has one) is returned. If it doesn't have a parent, then the empty sequence is returned. Only document, element, and processing-instruction nodes may have a non-empty base-uri.

Example C.6. base-uri examples

base-uri()
base-uri(doc('input.xml'))

See also: declare base-uri in Appendix B.

The argument specifies an arbitrary sequence to be converted to xs:boolean. The argument is converted to boolean as follows: If the expression is the empty sequence, the empty string, zero (in any numeric type), or the special number NaN (floating-point types only), then it is converted to false. Otherwise, it is converted to true.

This conversion was used by XPath 1.0, and in the context of XQuery is usually called the Effective Boolean Value. It is implicitly applied in many contexts, including path predicates; the boolean() function provides a way to apply the conversion explicitly.

Example C.7. boolean examples

boolean('')                 => false()
boolean('false')            => true()
cast as xs:boolean('')      => error
cast as xs:boolean('false') => false

The boolean() function differs from cast as xs:boolean in its handling of strings and non-singleton sequences, both of which are converted to true if they are non-empty. In contrast, cast as xs:boolean inspects the value of the string (treating "true" and "1" as true, "false" and "0" as false, and all other values as errors) and errors on non-singleton sequences.

See also: number()and string(), and cast as in Appendix B.

The argument specifies the value to be rounded. The return value has the same type as the argument.

If the argument is the empty sequence, then ceiling() returns the empty sequence. If the argument type is xs:float or xs:double and is one of the special values positive zero, negative zero, positive infinity, negative infinity, or NaN, then it is returned unchanged.

Otherwise, ceiling() returns the least integer greater than the argument. (Negative values that round up to zero result in negative zero.) This process is also commonly known as “round toward positive infinity.”

Example C.8. ceiling examples

ceiling(2)       =>  2
ceiling(1.5)     =>  2.0
ceiling(1.2)     =>  2.0
ceiling(-1.5)    => -1.0
ceiling(1 div 0) =>  INF
See also: floor(), round(), and round-half-to-even().

The argument specifies a sequence of integer Unicode code points.

If an integer in the sequence doesn't correspond to a legal XML character (the Char production from the XML 1.0 standard), then an error is raised. If the sequence is empty, then codepoints-to-string() returns the empty string. Otherwise, codepoints-to-string() returns the string that results from concatenating the Unicode characters corresponding to these code points.

Example C.9. codepoints-to-string examples

codepoints-to-string((72,101,108,108,111)) => "Hello"
codepoints-to-string(())                   => ""

See also: string-to-codepoints().

The first argument specifies the collection name. An error occurs if it cannot be converted to xs:anyURI. Otherwise, if it is a relative URI, then it is first resolved into an absolute URI using the base URI property of the static context (as returned by base-uri()).

If there isn't a collection corresponding to this URI, then an error is raised. Otherwise, collection() returns the node sequence corresponding to the named collection. Like the doc() function, the same node (by identity) is returned every time this function is invoked with the same argument.

Example C.10. collection examples

collection("items")
collection("http://www.w3.org/TR/XQuery")

See also: base-uri(), doc(), and input().

The first two arguments are the strings to be compared. The optional third argument specifies a collation to use for the comparison; if omitted, the default collation of the static context is used.

If either argument is the empty sequence, then compare() returns the empty sequence. Otherwise, it returns -1, 0, or 1 if the first string is less than, equal to, or greater than the second string (respectively).

One way to remember the return value of compare() is to think of its correspondence with the general comparison operators. For every general comparison operator op, the expression $L op $R has the same result as compare(L, R) op 0. For example, $L <= $R is the same as compare($L, $R) <= 0.

Example C.11. compare examples

compare("abc", () )              => ()
compare( (), "abc" )             => ()
compare("abc", "abc")            =>  0 (equal)
compare("abc", "xyz")            => -1 (less-than)
compare("xyz", "abc")            =>  1 (greater-than)
compare("Hello, world", "Hello") =>  1

See also: The section “Collations” in Chapter 8.

The concat() function is special among all the XQuery functions in that it accepts a variable number of arguments (zero or more). Each argument must be a singleton string or the empty sequence (which is treated like the empty string).

The concat() function returns the string concatenation of all its arguments. When called without any arguments, it returns the empty string.

Example C.12. concat examples

concat()                  => ""
concat(())                => ""
concat("a", "b", "", "c") => "abc"
concat("x", 2)            => error (: 2 is not a string :)
concat(("a", "b", "c"))   => error (: argument contains more than one item :)

To concatenate sequences containing more than one string (for example, FLWOR statements returning strings), or to insert spaces, commas, or other characters in between strings, use the string-join() function.

See also: string-join().

The first argument specifies the string to search, and the second argument specifies the substring to seek. The optional third argument specifies the collation to use; it defaults to the Unicode code point collation.

If the second argument is the empty sequence or the empty string, then contains() returns true. Otherwise, if the first argument is the empty sequence or the empty string, it returns false.

Otherwise, contains() returns true if the string contains the substring, and returns false otherwise. The collation is used to perform substring comparisons.

Example C.13. contains examples

contains('hello', () )  => true
contains('hello', 'll') => true
contains('hello', 'x')  => false
contains('hello', '')   => true
contains('', 'll')      => false

See also: matches() and substring().

The first argument specifies the sequence to be counted.

The count() function returns the number of items in the sequence.

Example C.14. count examples

count(())       => 0
count("xyz")    => 1
count((1, "a")) => 2

See also: last() and string-length().

Selects the date part of the current dateTime of the static context. Within a query, every invocation of this function returns the same value. The value of the current dateTime is implementation-dependent.

Example C.15. current-date example

current-date() => "2004-02-06"

See also: current-dateTime(), current-time(), and implicit-timezone().

Selects the current dateTime of the static context. Within a query, every invocation of this function returns the same value. The value of the current dateTime is implementation-dependent.

Example C.16. current-dateTime example

current-dateTime() => "2004-02-06T12:00:00"

See also: current-date(), current-time(), and implicit-timezone().

Select the time part of the current dateTime of the static context. Within a query, every invocation of this function returns the same value. The value of the current dateTime is implementation-dependent.

Example C.17. current-time example

current-time() => "12:00:00"

See also: current-date(), current-dateTime(), and implicit-timezone().

The argument specifies the sequence of items to be atomized. For each item in the sequence, if it's an atomic value then it's returned unchanged; if it's a node, then it's replaced by its typed value. The data() function then returns the resulting sequence.

If the typed value of a node is a list type (for example, xs:IDREFS) or the empty sequence, then the returned sequence may have a different length than the original.

Example C.18. data examples

data(<x xsi:type="xs:integer">{1}</x>) => 1
data("a", 2.5, <x>hello</x>)           => ("a", 2.5, "hello")

See also: The section “Atomization” in Chapter 2.

The first two arguments specify the sequences to be compared. The optional third argument specifies a collation to use for string comparisons; if omitted, the default collation is used.

If both sequences are empty, then deep-equal() returns true. If the lengths of the two sequences differ, then deep-equal() returns false.

Otherwise, deep-equal() iterates through the two sequences together and compares the members at the same positions. If each such pair of members compare equal (using the eq operator for values, or deep equality for nodes as explained below), then deep-equal() returns true, otherwise it returns false.

Example C.19. deep-equal examples

deep-equal((), ())                        => true
deep-equal((1,2), (1,2))                  => true
deep-equal((1,2,3), (1,2))                => false
deep-equal(<x/>, <x/>)                    => true
deep-equal(<x a="1"><y>2</y></x>,
           <x a="1"><y>2</y></x>)         => true
deep-equal(<x a="1"><y>2</y></x>,
           <x a="3"><y>4</y></x>)         => false

Deep equality of nodes is determined using a recursive definition—two nodes are deep-equal when all of the following conditions hold:

  • They have the same node kind.

  • They either both lack names, or else have the same expanded QName.

  • If they are text, comment, processing-instruction, or namespace nodes, then they have equal string values (using the collation for comparison).

  • If they are element nodes, then neither node has an attribute that isn't deep-equal to an attribute on the other.

  • If they are attribute, element, or document nodes, then either:

  • Neither has element content, both have simple content, and their typed content compares equal using deep-equal()with the supplied collation.

  • Both have element content, and all their child nodes are pairwise in order of appearance, ignoring comment and processing-instruction nodes, and compare equal using deep-equal() with the supplied collation.

This process can also be written as a recursive XQuery function (in which node-kind() is a hypothetical function that returns the node kind of a node as a string value).

Example C.20. A user-defined deep-equal function equivalent to the built-in one

declare function my:deep-equal($seq0 as item*, $seq1 as item*,
                              $collation as xs:string) {
count($seq0) eq count($seq1)
and
empty (
  for $i in $seq0 at $pos
  let $j := $seq1[$pos]
  let $inode := $i instance of node()
  let $jnode := $j instance of node()
  where
    if ($inode and $jnode)
    then (
      (: both nodes, perform complex test :)
      let $ii := treat as node() ($i)
      let $jj := treat as node() ($j)
      return
           node-kind($ii) ne node-kind($jj)
        or node-name($ii) != node-name($jj)
        or if (node-kind($ii)=("element", "attribute", "document"))
           then not(
             count($ii/@*) eq count($jj/@*) and (
               every $attr in $ii/@* satisfies
                 (some $attr2 in $jj/@* satisfies
                  my:deep-equal(data($attr), data($attr2), $collation))
             ) and (
                 my:deep-equal(($ii/(*|text()), data($ii)),
                               ($jj/(*|text()), data($jj)),
                               $collation)
             )
           )
           else compare(string($ii), string($jj), $collation) ne 0
    )
    else if ($inode or $jnode)
    then true()     (: different item kinds, so always fail :)
    else $i ne $j   (: both atomic values, just use ne :)
  return $i
)
};

See also: eq in Appendix B.

Selects the default collation from the static context, or the empty sequence if no default collation is defined.

Example C.21. default-collation example

default-collation() =>
"http://www.w3.org/2003/11/xpath-functions/collation/codepoint"

See also: declare default collation in Appendix B, and the section “Collations” in Chapter 8.

The first argument specifies a sequence of atomic values. The optional second argument specifies the collation to use for string comparisons; if omitted, the default collation is used.

If the second argument isn't a valid URI or doesn't specify a valid collation, then an error is raised. If the first argument is empty, then the empty sequence is returned.

Otherwise, distinct-values() returns the sequence of values with duplicates (by value equality) removed. All members of the sequence must be the same type (or subtypes of it), and equality must be defined for that type. NaN is considered equal to itself, and positive zero is considered equal to negative zero. Types with an empty time zone component are adjusted to the implicit time zone before comparison.

The order of the result and in some cases the values themselves are implementation-defined, and may vary even when given the same arguments as input.

Example C.22. distinct-values examples

distinct-values((1,2,3,2,2))
=> (1,2,3) (: in any order :)

distinct-values(("example", "example"),
"http://www.w3.org/2003/11/xpath-functions/collation/codepoint")
=> "a"

distinct-values((1, 1.0))
=> 1 or 1.0 (: implementation-defined :)

The first argument specifies a document location. If it is the empty sequence, then the empty sequence is returned.

Otherwise, it is converted to xs:anyURI; if it cannot be converted, then an error is raised. If it is a relative URI, then it is first resolved to an absolute URI using the base URI property of the static context.

The behavior of the doc() function is essentially implementation-defined, although XQuery guarantees that within a particular query, every invocation of doc() with the same value results in the same node (by identity). Implementations may choose to return the same node (by identity) under other circumstances, such as if they determine that two different URI values refer to the same underlying document.

Implementations may also choose how to handle cases such as if the document doesn't exist, exists but isn't well-formed, or exists and is well-formed but is invalid according to its schema. In such cases, implementations may choose to raise an error, return the empty sequence, return another document, or provide some other implementation-defined fallback.

Implementations may also statically type the result of this function if the location is known to it at compile-time.

Example C.23. doc examples

doc(())
doc("input.xml")
doc("http://www.w3.org/TR/xquery/XQuery.xml")

See also: base-uri(), collection(), and input().

The argument specifies the node to use. This function selects the document-uri property of the node if it has one and it is an absolute URI, otherwise document-uri() returns the empty sequence.

Example C.24. document-uri example

document-uri(doc("input.xml"))

See also: resolve-uri() and Appendix A.

The first argument specifies the sequence to be tested. The empty() function returns true if the sequence is empty, and returns false otherwise.

Example C.25. empty examples

empty(()) => true
empty(1)  => false

See also: exists().

The first argument specifies the string to be searched; the second argument specifies the substring to seek. The optional third argument specifies the collation to use for comparisons; it defaults to the Unicode code point collation.

If the second argument is the empty sequence or the empty string, then ends-with() returns true. Otherwise, if the first argument is the empty sequence or the empty string, then ends-with() returns false.

Otherwise, ends-with() returns true if the string ends with the substring, and false otherwise. This function is redundant with the more powerful matches() function, but is retained for compatibility with XPath 1.0 and convenience.

Example C.26. ends-with examples

ends-with("Hello, world", ())      => true
ends-with("Hello, world", "Hello") => false
ends-with("Hello, world", "world") => true
ends-with("Hello, world", "")      => true
ends-with("", "world")             => false

See also: contains(), matches(), and starts-with().

The optional argument has implementation-defined meaning, although usually it is used as a message to the user. The error() function terminates execution of the XQuery at the point where it is invoked. This function can be used to create user-defined error conditions.

Example C.27. error examples

error("Internal error, abort, abort!")
error(err:message142)
error(<log time="{current-time()}" msg="query failed"/>)

See also: trace().

The first argument specifies the URI to be escaped. The second argument specifies whether to escape reserved characters.

The escape-uri() function escapes URI characters according to the URI standards (RFC 2396 and RFC 2732). Each special character in the string will be replaced by a URI escape sequence %NN where NN is the hexadecimal value of the character (returned using uppercase hexadecimal characters). Characters already escaped in this form are unchanged. The string argument isn't required to be a valid URI.

If the second argument is true, then all characters are escaped except lowercase and uppercase ASCII letters, the digits 0 to 9, and the punctuation characters hyphen (-), underscore (_), period (.), exclamation mark (!), tilde (~), asterisk (*), apostrophe ('), and parentheses ( ( and ) ). The percent sign (%) is escaped only if it isn't followed by two hexadecimal digits. This mode is useful when encoding most of the URI, including the domain and path.

If the second argument is false, then in addition to the exceptions listed above, the following characters are also exempted from escaping: semicolon (;), slash (/), question mark (?), colon (:), at sign (@), ampersand (&), equals (=), plus (+), dollar sign ($), comma (,), number sign (#), and square brackets ( [ and ] ). This mode is useful when encoding the part of a URI containing parameters.

Example C.28. escape-uri examples

escape-uri("%20abcABC123+*$%", true())  => "%20abcABC123%2B*%24%25"
escape-uri("%20abcABC123+*$%", false()) => "%20abcABC123+*$%25"

Returns the sequence unchanged if it has length exactly one, otherwise it raises an error.

Example C.29. exactly-one examples

exactly-one(())    => error
exactly-one(1)     => (1)
exactly-one((1,2)) => error

Many functions and operators in XQuery require singletons. One way to ensure that a sequence has the required length is to use the exactly-one() function.

Example C.30. Using exactly-one to pass static typing

collection(base-uri(exactly-one(..))

See also: one-or-more() and zero-or-one().

The first argument specifies the sequence to be tested. The exists() function returns true if the sequence is non-empty, and false otherwise.

Example C.31. exists examples

exists(()) => false
exists(1)  => true

See also: empty().

The first argument specifies the namespace URI, and the second argument specifies the local name. If the namespace is the empty string, then it doesn't represent a namespace. If the local name isn't a valid xs:NCName, then an error is raised.

The expanded-QName() function returns an xs:QName value with the given namespace and local name parts.

Example C.32. expanded-QName example

expanded-QName("http://www.awprofessional.com/", "example")

See also: resolve-QName(), and xs:QName in Appendix A.

Returns the boolean constant false.

XQuery defines the false constant using a function mainly for backwards compatibility with XPath 1.0 and to eliminate the need for reserved keywords.

Example C.33. false example

false()   => false

See also: true().

The argument specifies the value to be rounded. The return value has the same type as the argument.

If the argument is the empty sequence, then floor() returns the empty sequence. If the argument type is xs:float or xs:double and is one of the special values positive zero, negative zero, positive infinity, negative infinity, or NaN, then it is returned unchanged. Otherwise, floor() returns the greatest integer less than the argument. This process is also commonly known as “round toward negative infinity.”

Example C.34. floor examples

floor(2)       =>  2
floor(1.5)     =>  1.0
floor(1.2)     =>  1.0
floor(-1.5)    => -2.0
floor(1 div 0) =>  INF

See also: ceiling(), round(), and round-half-to-even().

The argument specifies the date value. If the argument is the empty sequence, then the function returns the empty sequence. Otherwise, it returns the integer day part of the date.

Example C.35. get-day-from-date examples

get-day-from-date(xs:date("2004-09-08")) => 8
get-day-from-date(())                    => ()

See also: get-month-from-date(), get-timezone-from-date(), and get-year-from-date().

The argument specifies the xs:dateTime value. If the argument is the empty sequence, then the function returns the empty sequence. Otherwise, it returns the integer day part of the xs:dateTime value.

Example C.36. get-day-from-dateTime examples

get-day-from-dateTime(xs:dateTime("2004-09-08T04:30:00")) => 8
get-day-from-dateTime(())                                 => ()

See also: get-hours-from-dateTime(), get-minutes-from-dateTime(), get-month-from-dateTime(), get-seconds-from-dateTime(), get-timezone-from-dateTime(), and get-year-from-dateTime().

The argument specifies the duration value. If the argument is the empty sequence, then the function returns the empty sequence. Otherwise, it returns the integer number of days in the duration.

Example C.37. get-days-from-dayTimeDuration examples

get-days-from-dayTimeDuration(xdt:dayTimeDuration("P5D")) => 5
get-days-from-dayTimeDuration(())                         => ()

See also: get-hours-from-dayTimeDuration(), get-minutes-from-dayTimeDuration(), and get-seconds-from-dayTimeDuration().

The argument specifies the xs:dateTime value. If the argument is the empty sequence, then the function returns the empty sequence. Otherwise, it returns the integer hours part of the xs:dateTime value.

Example C.38. get-hours-from-dateTime examples

get-hours-from-dateTime(xs:dateTime("2004-05-13T08:41:00")) => 8
get-hours-from-dateTime(())                                 => ()

See also: get-day-from-dateTime(), get-minutes-from-dateTime(), get-month-from-dateTime(), get-seconds-from-dateTime(), get-timezone-from-dateTime(), and get-year-from-dateTime().

The argument specifies the duration value. If the argument is the empty sequence, then the function returns the empty sequence. Otherwise, it returns the integer number of hours in the duration.

Example C.39. get-hours-from-dayTimeDuration examples

get-hours-from-dayTimeDuration(xdt:dayTimeDuration("PT5H")) => 5
get-hours-from-dayTimeDuration(())                          => ()

See also: get-days-from-dayTimeDuration(), get-minutes-from-dayTimeDuration(), and get-seconds-from-dayTimeDuration().

The argument specifies the time value. If the argument is the empty sequence, then the function returns the empty sequence. Otherwise, it returns the integer hours part of the time.

Example C.40. get-hours-from-time examples

get-hours-from-time(xs:time("08:41:03.1")) => 8
get-hours-from-time(())                    => ()

See also: get-minutes-from-time(), get-seconds-from-time(), and get-timezone-from-time().

The argument specifies the element to use for the namespace scope. The get-in-scope-prefixes() function returns a list of all the namespace prefixes in scope on that element. If there is a default namespace in scope, it is returned as the empty string.

Example C.41. get-in-scope-prefixes example

get-in-scope(<x/>) => ("xs", "fn", "xdt", "xsi", "xml")

Note that elements constructed in an XQuery automatically have several namespace definitions in scope, as the example in Listing C.41 demonstrates.

See also: get-namespace-uri-for-prefix(), and declare namespace in Appendix B.

The first argument specifies the QName value to use. If the argument is the empty sequence, then the empty sequence is returned. Otherwise, get-local-name-from-QName() returns the local part of the QName value.

Example C.42. get-local-name-from-QName examples

get-local-name-from-QName(())                        => ()
get-local-name-from-QName(node-name(<x/>))           => "x"
get-local-name-from-QName(node-name(<x xmlns="y"/>)) => "x"

See also: get-namespace-uri-from-QName(), and xs:QName in Appendix A.

The argument specifies the xs:dateTime value. If the argument is the empty sequence, then the function returns the empty sequence. Otherwise, it returns the integer minutes part of the xs:dateTime value.

Example C.43. get-minutes-from-dateTime examples

get-minutes-from-dateTime(xs:dateTime("2003-09-08T08:41:00")) => 41
get-minutes-from-dateTime(())                                 => ()

See also: get-day-from-dateTime(), get-hours-from-dateTime(), get-month-from-dateTime(), get-seconds-from-dateTime(), get-timezone-from-dateTime(), and get-year-from-dateTime().

The argument specifies the duration value. If the argument is the empty sequence, then the function returns the empty sequence. Otherwise, it returns the integer number of minutes in the duration.

Example C.44. get-minutes-from-dayTimeDuration examples

get-minutes-from-dayTimeDuration(xdt:dayTimeDuration("PT5M")) => 5
get-minutes-from-dayTimeDuration(())                          => ()

See also: get-days-from-dayTimeDuration(), get-hours-from-dayTimeDuration(), and get-seconds-from-dayTimeDuration().

The argument specifies the time value. If the argument is the empty sequence, then the function returns the empty sequence. Otherwise, it returns the integer minutes part of the time.

Example C.45. get-minutes-from-time examples

get-minutes-from-time(xs:time("08:55:03.1")) => 55
get-minutes-from-time(())                    => ()

See also: get-hours-from-time(), get-seconds-from-time(), and get-timezone-from-time().

The argument specifies the date value. If the argument is the empty sequence, then the function returns the empty sequence. Otherwise, it returns the integer month part of the date.

Example C.46. get-month-from-date examples

get-month-from-date(xs:date("2004-09-08")) => 9
get-month-from-date(())                    => ()

See also: get-day-from-date(), get-timezone-from-date(), and get-year-from-date().

The argument specifies the xs:dateTime value. If the argument is the empty sequence, then the function returns the empty sequence. Otherwise, it returns the integer month part of the xs:dateTime value.

Example C.47. get-month-from-dateTime examples

get-month-from-dateTime(xs:dateTime("2004-09-08T08:41:00")) => 9
get-month-from-dateTime(())                                 => ()

See also: get-day-from-dateTime(), get-hours-from-dateTime(), get-minutes-from-dateTime(), get-seconds-from-dateTime(), get-timezone-from-dateTime(), and get-year-from-dateTime().

The argument specifies the duration value. If the argument is the empty sequence, then the function returns the empty sequence. Otherwise, it returns the integer number of months in the duration.

Example C.48. get-months-from-yearMonthDuration examples

get-months-from-yearMonthDuration(xdt:yearMonthDuration("P5M"))=> 5
get-months-from-yearMonthDuration(())                         => ()

See also: get-years-from-yearMonthDuration().

The first argument specifies an element to use for the namespace scope. The second argument specifies the prefix to look up.

If the element has an in-scope namespace with that prefix, then get-namespace-uri-for-prefix() returns that namespace URI (the empty string prefix corresponds to the default namespace). Otherwise, it returns the empty sequence.

Example C.49. get-namespace-uri-for-prefix examples

get-namespace-uri-for-prefix(<x xmlns="y"/>, "")    => "y"
get-namespace-uri-for-prefix(<x xmlns:p="y"/>, "p") => "y"

See also: get-in-scope-prefixes() and get-namespace-uri-from-QName().

The first argument specifies the QName value to use. If the argument is the empty sequence, or if the QName doesn't have a namespace, then the empty sequence is returned. Otherwise, get-namespace-uri-from-QName() returns the namespace part of the QName value.

Example C.50. get-namespace-uri-from-QName examples

get-namespace-uri-from-QName(())                        => ()
get-namespace-uri-from-QName(node-name(<x/>))           => ()
get-namespace-uri-from-QName(node-name(<x xmlns="y"/>)) => "y"

See also: get-local-name-from-prefix() and get-local-name-from-QName().

The argument specifies the dateTime value. If the argument is the empty sequence, then the function returns the empty sequence. Otherwise, it returns the decimal seconds part of the dateTime.

Example C.51. get-seconds-from-dateTime examples

get-day-from-dateTime(xs:dateTime("2004-09-08T08:41:00")) => 0.0
get-day-from-dateTime(())                                 => ()

See also: get-day-from-dateTime(), get-hours-from-dateTime(), get-minutes-from-dateTime(), get-month-from-dateTime(), get-timezone-from-dateTime(), and get-year-from-dateTime().

The argument specifies the duration value. If the argument is the empty sequence, then the function returns the empty sequence. Otherwise, it returns the decimal number of the seconds in the duration.

Example C.52. get-seconds-from-dayTimeDuration examples

get-seconds-from-dayTimeDuration(xdt:dayTimeDuration("PT5S")) => 5.0
get-seconds-from-dayTimeDuration(())                          => ()

See also: get-days-from-dayTimeDuration(), get-hours-from-yearMonthDuration(), and get-minutes-from-dayTimeDuration().

The argument specifies the time value. If the argument is the empty sequence, then the function returns the empty sequence. Otherwise, it returns the decimal seconds part of the time.

Example C.53. get-seconds-from-time examples

get-seconds-from-time(xs:time("08:55:03.1")) => 3.1
get-seconds-from-time(())                    => ()

See also: get-hours-from-time(), get-minutes-from-time(), and get-timezone-from-time().

The argument specifies the date value. If the argument is the empty sequence, then the function returns the empty sequence. Otherwise, it returns the time zone part of the date as an xdt:dayTimeDuration value.

Example C.54. get-timezone-from-date examples

get-timezone-from-date(xs:date("2004-05-30"))
get-timezone-from-date(())                    => ()

See also: get-day-from-date(), get-month-from-date(), and get-year-from-date().

The argument specifies the dateTime value. If the argument is the empty sequence, then the function returns the empty sequence. Otherwise, it returns the time zone part of the dateTime as an xdt:dayTimeDuration value.

Example C.55. get-timezone-from-dateTime examples

get-timezone-from-dateTime(xs:dateTime("2004-05-13T08:55:03.1"))
get-timezone-from-dateTime(())                                   => ()

See also: get-day-from-dateTime(), get-hours-from-dateTime(), get-minutes-from-dateTime(), get-month-from-dateTime(), get-seconds-from-dateTime(), and get-year-from-dateTime().

The argument specifies the time value. If the argument is the empty sequence, then the function returns the empty sequence. Otherwise, it returns the time zone part of the time as an xdt:dayTimeDuration value.

Example C.56. get-timezone-from-time examples

get-timezone-from-time(xs:time("08:55:03.1"))
get-timezone-from-time(())                    => ()

See also: get-hours-from-time(), get-minutes-from-time(), and get-seconds-from-time().

The argument specifies the date value. If the argument is the empty sequence, then the function returns the empty sequence. Otherwise, it returns the integer year part of the date.

Example C.57. get-year-from-date examples

get-year-from-date(xs:date("2004-09-08")) => 2004
get-year-from-date(())                    => ()

See also: get-day-from-date(), get-month-from-date(), and get-timezone-from-date().

The argument specifies the dateTime value. If the argument is the empty sequence, then the function returns the empty sequence. Otherwise, it returns the integer year part of the dateTime.

Example C.58. get-year-from-dateTime examples

get-year-from-dateTime(xs:dateTime("2004-09-08T08:41:00")) => 2004
get-year-from-dateTime(())                                 => ()

See also: get-day-from-dateTime(), get-hours-from-dateTime(), get-minutes-from-dateTime(), get-month-from-dateTime(), get-seconds-from-dateTime(), and get-timezone-from-dateTime().

The argument specifies the duration value. If the argument is the empty sequence, then the function returns the empty sequence. Otherwise, it returns the integer number of years in the duration.

Example C.59. get-years-from-yearMonthDuration examples

get-years-from-yearMonthDuration(xdt:yearMonthDuration("P5Y")) => 5
get-years-from-yearMonthDuration(())                           => ()

See also: get-months-from-yearMonthDuration().

The first argument specifies a sequence of string values to be looked up.

If there isn't a context node, then an error is raised. If the sequence is empty, then the result is the empty sequence. Otherwise, each string value in the sequence is parsed as a space-separated sequence of IDREF values. Values that cannot be cast to xs:IDREF are ignored. All of these IDREF values are looked up, and the sequence of corresponding elements are returned in document order without duplicates (by node identity). An element is matched if it is in the same document as the current context node and either it has an attribute of type xs:ID equal to one of the IDREF values or else the element itself is type xs:ID and its value is equal to one of the IDREF values.

The ID/IDREF string matching uses Unicode code points only, ignoring collation. Also, it is possible to match against a well-formed but schema-invalid document, in which case multiple elements could have the same ID or values could be declared as type xs:ID but invalid according to that type. In these cases, the first matching element is selected and invalid ID values are ignored.

Example C.60. id examples

id("x y")            => look up elements with IDs x and y
id(("a", "b", "c d") => look up elements with IDs a, b, c, and d.
id(())               => ()
id("3")              => () (: 3 is not a valid xs:IDREF :)

See also: idref().

The first argument specifies a sequence of string values to be looked up.

If there isn't a current context node, then an error is raised. If the sequence is empty, then the empty sequence is returned. Otherwise, as with the id() function, each string in the sequence is parsed as a space-separated list of ID values. Invalid ID values are ignored. For each ID value, idref() finds all xs:IDREF and xs:IDREFS-typed nodes in the same document as the current context node that refer to that ID value. String equality is determined by Unicode code points, irrespective of collation. The nodes are returned in document order without duplicates (by node identity).

Example C.61. idref examples

idref("x") => all nodes in the current context document that refer to x
idref("3") => () (: 3 is not a valid xs:ID :)
idref(())  => ()

See also: id().

Select the time zone part of the current dateTime of the static context. Returns the empty sequence if the time zone is undefined.

Within a query, every invocation of this function returns the same value. The value of the current dateTime is implementation-dependent.

Example C.62. implicit-timezone example

implicit-timezone()

See also: current-date(), current-dateTime(), and current-time().

The first argument specifies a sequence of values, and the second argument specifies a value to search for in that sequence. The optional third argument specifies a collation to use for string comparisons; if omitted, the default collation is used.

If the collation is specified and isn't a valid URI or doesn't name a valid collation, then an error is raised. If the sequence is empty, then the empty sequence is returned.

Otherwise, index-of() finds all the positions in the sequence where the item occurs, and returns those positions in increasing order. (Remember, 1 is the first position.) If it doesn't occur in the sequence, then index-of() returns the empty sequence.

Example C.63. index-of examples

index-of((1,2,3), 2)             => 2
index-of((), 'anything')         => ()
index-of(('a','b',1,2,'a'), 'a') => (1, 5)

The first argument specifies the original sequence, and the second argument specifies the insertion position. (Remember, the first item occurs at position 1.) The third argument specifies a sequence of items to be inserted.

If the first argument is the empty sequence, then the third argument is returned. If the third argument is the empty sequence, then the first argument is returned. If the position is less than 1, then insert-before() returns the sequence of items to be inserted followed by the original sequence. If the position is greater than the length of the original sequence, then insert-before() returns the original sequence followed by the sequence to be inserted.

Otherwise, insert-before() returns a new sequence formed from three parts: the subsequence of the original up to but not including the item at the specified position, the items to be inserted, and the remaining items from the original sequence.

In other words, the expression insert-before($seq, $pos, $items) is equivalent to the expression (subsequence($seq, 1, $pos-1), $items, subsequence($seq, $pos)).

Example C.64. insert-before examples

insert-before((1,4), 2, (2,3)) => (1,2,3,4)
insert-before((1,4), 1, (2,3)) => (2,3,1,4)
insert-before((1,4), 3, (2,3)) => (1,4,2,3)

See also: remove() and subsequence().

The argument specifies the language string. If there isn't a context item, or it isn't a node, then lang() returns false.

Otherwise, lang() returns true if the language of the current context node (that is, the value of the last xml:lang attribute in scope) is the same as, or a sublanguage of, the given string, ignoring case.

Example C.65. lang examples

lang("en-gb")
lang("SP")

The lang() function is equivalent to the user-defined function in Listing C.66.

Example C.66. A user-defined lang() function equivalent to the built-in one

declare function my:lang(string $s) as xs:boolean {
  let $u := lower-case($s)
  let $x := lower-case( string( 
                       (ancestor-or-self::*/@xml:lang)[last()] ) )
  return $u = $x or $u = substring-before($x, "-")
};

See also: xml:lang in Appendix A.

Selects the length of the current context sequence. Returns the empty sequence when the context is empty.

Example C.67. last example

(1,2,4)[last()]   => 4

See also: count() and position().

The optional argument specifies the node to use; when omitted, it defaults to the current context node. If the current context item isn't a node, an error is raised.

The result is the local part of the node's name. If the node doesn't have a name, then local-name() returns the empty string.

Example C.68. local-name examples

local-name(<x/>)                   => "x"
local-name(<x:y xmlns:x="hello"/>) => "y"
local-name(<!-- comment -->)       => ""

See also: name(), namespace-uri(), and node-name().

The argument specifies the string to be converted to lowercase.

If the argument is the empty sequence, lower-case() returns the empty sequence. Otherwise, lower-case() returns the string with all characters translated into their lowercase forms. Characters without uppercase forms are unchanged.

Note that changing case can alter the length of the string.

Example C.69. lower-case examples

lower-case("Hello, world") => "hello, world"
lower-case("")             => ""
lower-case(())             => ()

See also: upper-case().

The first argument specifies the input string, and the second argument specifies a regular expression match pattern. The optional third argument specifies flags that modify how the match is performed; if omitted, it defaults to the empty string.

If the first argument is the empty sequence, then matches() returns the empty sequence. If the second argument isn't a valid match pattern, or if the third argument contains invalid flags, then matches() returns an error. Otherwise, matches() returns true if the string matches the regular expression and false if it does not.

Unless the match pattern uses anchors (^ or $), it can match anywhere in the string. See Appendix D for more information about the regular expression syntax and flags used by matches() and replace().

Example C.70. matches examples

matches("Hello, world", "hello")       => false
matches("Hello, world", "hello", "i")  => true
matches("Hello, world", "hello$", "i") => false
matches("Hello, world", "w, w")      => true

See also: replace() and Appendix D.

The first argument specifies the sequence to use. The optional second argument specifies the collation to use for string comparisons; if omitted, the default collation is used.

If the sequence is empty, then the empty sequence is returned. If the sequence doesn't contain values all of the same type or types that can be promoted to a common type, then an error is raised. Only types that can be compared using gt are allowed.

If there are any NaN values in the sequence, then max() returns NaN. Otherwise, max() returns the greatest value in the sequence.

Example C.71. max examples

max((1.0, 2, 3.0E0)) => 3.0E0
max(())              => ()
max(0)               => 0
max(1, 3)            => 3

See also: min().

The first argument specifies the sequence to use. The optional second argument specifies the collation to use for string comparisons; if omitted, the default collation is used.

If the sequence is empty, then the empty sequence is returned. If the sequence doesn't contain values all of the same type or types that can be promoted to a common type, then an error is raised. Only types that can be compared using gt are allowed.

If there are any NaN values in the sequence, then min() returns NaN. Otherwise, min() returns the least value in the sequence.

Example C.72. min examples

min((1.0, 2, 3.0E0)) => 1.0
min(())              => ()
min(0)               => 0
min(1, 3)            => 1

See also: max().

The optional argument specifies the node to use; when omitted, it defaults to the current context node. If the current context item isn't a node, an error is raised.

The result is the name of the node as an xs:string value (that is, the prefix and local name parts). If the node doesn't have a name, then name() returns the empty string. The name() function is mainly retained for backwards compatibility with XPath 1.0.

The name() function differs slightly from the node-name() function, which returns the name as an xs:QName value (namespace and local name parts) and returns the empty sequence for nodes with no name.

Example C.73. name examples

name(<x/>)                   => "x"
name(<x:y xmlns:x="hello"/>) => "x:y"
name(<!-- comment -->)       => ""

See also: local-name(), namespace-uri(), and node-name()

The optional argument specifies the node to use; when omitted, it defaults to the current context node. If the current context item isn't a node, an error is raised.

The result is the namespace part of the node's name. If the node doesn't have a name, or if the name doesn't have a namespace, then namespace-uri() returns the empty string.

Example C.74. namespace-uri examples

namespace-uri(<x/>)                   => ""
namespace-uri(<x:y xmlns:x="hello"/>) => "hello"
namespace-uri(<!-- comment -->)       => ""

See also: local-name(), name(), and node-name().

The argument specifies the node to use.

The result is the name of the node as an xs:QName value (that is, the namespace and local name parts, without a prefix). If the node doesn't have a name, then node-name() returns the empty sequence.

The node-name() function differs slightly from the name() function, which returns the name as a string value (prefix and local name parts) and returns the empty string for nodes with no name.

Example C.75. node-name examples

node-name(<x/>)                   => xs:QName((), "x")
node-name(<x:y xmlns:x="hello"/>) => xs:QName("hello", "y")
node-name(<!-- comment -->)       => ()

See also: local-name(), name(), and namespace-uri().

The optional first argument specifies the input string; if omitted, it defaults to the string value of the current context item (in other words, string(.)).

If the argument is the empty sequence, then the empty sequence is returned. Otherwise, normalize-space() performs XML whitespace normalization to the string value. This process strips leading and trailing whitespace characters (&#x9;, &#xA;, &#xD;, and &#x20;) and replaces consecutive sequences of more than one whitespace character by a single space character (&#x20;).

Example C.76. normalize-space examples

normalize-space(" Hello,   world  ") => "Hello, world"
normalize-space(())                  => ()

See also: normalize-unicode().

The first argument specifies the input string. The optional second argument specifies the Unicode normalization rule to be applied; if omitted, it defaults to the string "NFC".

If the first argument is the empty sequence, then the empty sequence is returned. The second argument has leading and trailing whitespace removed and is converted to uppercase. If the result is the empty string, then the input string is returned unchanged. If the resulting normalization rule isn't supported by the implementation, then an error is raised.

Otherwise, normalize-unicode() returns the string that results from performing the requested normalization. Implementations are required to support only the default normalization form ("NFC"), may support four others defined by the Unicode Standard and W3C character model ("NFD", "NFKC", "NFKD", and "W3C"), and may support other normalization forms.

Example C.77. normalize-unicode examples

normalize-unicode("&#x97;&#x769;")        => "&#x225;"
normalize-unicode("&#x97;&#x769;", "NFC") => "&#x225;"
normalize-unicode("&#x97;&#x769;", "")    => "&#x97;&#x769;"

See also: codepoints-to-string(), normalize-space(), and string-to-codepoints().

The first argument is the expression to be negated. It is first converted to boolean as if by a call to the boolean() function. Then not() turns true into false and vice versa.

XQuery expresses this operator as a function mainly for backwards compatibility with XPath 1.0; the other logical operators are keywords.

Example C.78. not examples

not(true())    => false
not(false())   => true
not(1)         => false
not(0)         => true
not(())        => true

See also: boolean(), and the entries and and or in Appendix B.

The optional argument specifies an item to be converted to xs:double; when omitted, it defaults to the current context item.

If the item is the empty sequence, then NaN is returned. If the item is atomic, or a node with an atomic type, then its value is converted to double exactly like cast as xs:double. Otherwise, the string value of the item is computed as if by a call to the string() function, and then that value is converted to double using the same rules as cast as xs:double.

Note, however, that if the conversion to double fails, then instead of raising an error like cast as xs:double would, number() instead returns NaN.

Example C.79. number examples

number("1.0")   => 1.0E0
number(false()) => 0.0E0
number(())     => NaN

See also: boolean()and string(), and cast as in Appendix B.

The argument specifies the sequence to use. Returns the sequence unchanged if it has length of at least one, otherwise it raises an error.

Example C.80. one-or-more examples

one-or-more(())    => error
one-or-more(1)     => (1)
one-or-more((1,2)) => (1,2)

See also: exactly-one() and zero-or-one().

Selects the position of the current context item within its sequence. Returns the empty sequence when the context is empty.

Example C.81. position examples

()[error(position())] => error invoked with empty sequence
(1,2,4)[position()]   => (1, 2)

See also: count(), FLWOR, and last() in Appendix B.

The first argument specifies the sequence to use. The second argument specifies the position of the item to be removed.

If the sequence is empty, then the empty sequence is returned. If the position is less than 1 or greater than the length of the sequence, then the sequence is returned unchanged.

Otherwise, the remove() function returns all the items in the sequence not at that position.

Example C.82. remove examples

remove(('a','b','c','d'), 1) => ('b', 'c', 'd')
remove(('a','b','c','d'), 3) => ('a', 'b', 'd')
remove(('a','b','c','d'), 0) => ('a', 'b', 'c', 'd')
remove((), 1)                => ()

See also: subsequence().

The first argument specifies the input string, the second argument specifies a regular expression match pattern, and the third argument specifies the replacement pattern. The optional fourth argument specifies flags that modify how the match is performed; if omitted, it defaults to the empty string.

If the first argument is the empty sequence, then replace() returns the empty sequence. If the second argument isn't a valid match pattern, the third argument isn't a valid replacement pattern, or the fourth argument contains invalid flags, then replace() returns an error. Otherwise, replace() returns the string that results from performing the requested regular expression match and replacement.

Unless the match pattern uses anchors (^ or $), it can match anywhere in the string. See Appendix D for more information about the regular expression syntax and flags used by matches() and replace().

Example C.83. replace examples

replace("Hello, world", "hello", "Bye")         => "Hello, world"
replace("Hello, world", "hello", "Bye", "i")    => "Bye, world"
replace("Hello, world", "l.", "")               => "Heo, world"
replace("Hello, world", "(H)(.*)(w)", "$3$2$1") => "wello, Horld"

See also: matches(), translate(), and Appendix D.

The first argument specifies a string to be parsed as a qualified name. The second argument specifies an element whose in-scope namespaces are to be used when parsing the qualified name (to resolve its prefix or default namespace).

If the string isn't a valid QName, or has a prefix for which there isn't an in-scope namespace defined on the element, then an error is raised.

Otherwise, if the string has a prefix, then the corresponding namespace is used. If the string doesn't have a prefix and the element has a default namespace in scope, then that namespace is used. If the string doesn't have a prefix, then no namespace is used.

Example C.84. resolve-QName examples

resolve-QName("hello", <x/>)              => xs:QName((), "hello")
resolve-QName("hello", <x xmlns="hi"/>)   => xs:QName("hi","hello")
resolve-QName("x:hello",<x/>)             => error
resolve-QName("x:hello",<x xmlns:x="hi"/>)=> xs:QName("hi","hello")

See also: expanded-QName() and get-in-scope-prefixes().

The first argument specifies an optional relative URI string. The optional second argument specifies an absolute URI; when omitted, it defaults to the base URI of the static context (if there isn't one, then an error is raised).

If the base URI isn't an absolute URI, then an error is raised. If the relative URI is already absolute, then it is returned unchanged. If the relative URI is the empty string, then the string value of the provided base URI is returned. Otherwise, the relative URI is resolved against the base URI to produce an absolute URI, and the string value of this URI is returned.

Example C.85. resolve-uri examples

resolve-uri("", xs:anyURI("http://www.awprofessional.com"))
=> "http://www.awprofessional.com"
resolve-uri("http://www.awprofessional.com")
=> "http://www.awprofessional.com"
resolve-uri("cseng", xs:anyURI("http://www.awprofessional.com"))
=> "http://www.awprofessional.com/cseng"

See also: base-uri().

The reverse() function takes a single argument that specifies a sequence of items, and returns a new sequence with those items in reverse order. If the argument is the empty sequence, then reverse() returns the empty sequence.

Example C.86. reverse examples

reverse (())        => ()
reverse (1 to 3)    =>  (3,2,1)

See also FLWOR (order by).

The optional first argument specifies a node; it defaults to the current context node. If there isn't a current context node and an argument isn't provided, then an error is raised.

Otherwise, root() returns the root node in the same tree as the supplied context node. There is always exactly one such root node, and it is always an element or document node.

Example C.87. root examples

root()
root(<x/>)

See also: / (slash) in Appendix B.

The argument specifies the value to be rounded. The return value has the same type as the argument.

If the argument is the empty sequence, then round() returns the empty sequence. If the argument type is xs:float or xs:double and is one of the special values positive or negative zero, positive or negative infinity, or NaN, then it is returned unchanged.

Otherwise, round() returns the integer closest to the argument. (Negative values that round up to zero result in negative zero.) Ties are broken by rounding up. This process is also commonly known as “round to closest, round half up.”

Example C.88. round examples

round(2)       =>  2
round(1.5)     =>  2.0
round(1.2)     =>  1.0
round(-1.5)    => -1.0
round(1 div 0) =>  INF

See also: ceiling(), floor(), and round-half-to-even().

The first argument specifies the value to be rounded. The return value has the same type as this argument. The optional second argument specifies a precision to be used when rounding; the default value is zero.

If the first argument is the empty sequence, then round-half-to-even() returns the empty sequence. If the argument type is xs:float or xs:double and is one of the special values positive or negative zero, positive or negative infinity, or NaN, then it is returned unchanged.

Otherwise, round-half-to-even() rounds to the integer closest to the argument. (Negative values that round up to zero result in negative zero.) Ties are broken by rounding to even integers. This process is also commonly known as “round to closest, round half to even” or “banker's rounding” (because it is commonly used by financial applications to evenly distribute rounding errors).

Example C.89. round-half-to-even examples

round-half-to-even(2)       =>  2
round-half-to-even(1.5)     =>  2.0
round-half-to-even(1.2)     =>  1.0
round-half-to-even(-1.5)    => -2.0
round-half-to-even(1 div 0) =>  INF

Before rounding takes place, the value is first divided by ten to the power of the precision; after rounding takes place, the argument is multiplied by ten to the power of the precision. The overall effect is to control the digit position at which rounding occurs.

Example C.90. round-half-to-even with precision examples

round-half-to-even(123.456, 0)  => 123
round-half-to-even(123.456, 1)  => 123.4
round-half-to-even(123.456, 2)  => 123.46
round-half-to-even(123.456, 3)  => 123.456
round-half-to-even(123.456, -1) => 120.0
round-half-to-even(123.456, -2) => 100.0
round-half-to-even(123.456, -3) => 0.0

See also: ceiling(), floor(), and round().

The first argument specifies the string to be searched and the second argument specifies the substring to seek. The optional third argument specifies the collation to use for comparisons; it defaults to the Unicode code point collation.

If the second argument is the empty sequence or the empty string, then starts-with() returns true. Otherwise, if the first argument is the empty sequence or the empty string, then starts-with() returns false.

Otherwise, starts-with() returns true if the first argument begins with the second argument and returns false otherwise. This function is redundant with the more powerful matches() function, but is retained for compatibility with XPath 1.0 and convenience.

Example C.91. starts-with examples

starts-with("Hello, world", ())      => true
starts-with("Hello, world", "Hello") => true
starts-with("Hello, world", "world") => false
starts-with("Hello, world", "")      => true
starts-with("", "world")             => false

See also: contains(), ends-with(), and matches().

The optional argument specifies an arbitrary item to be converted to xs:string; when omitted, it defaults to the current context item.

If the argument is the empty sequence, then the empty string is returned. If the argument is a node, then its string value is returned. If the argument is xs:anyURI, then the URI is converted to string without escaping special characters. Otherwise, string($expr) returns the same result as cast as xs:string ($expr).

The string() function is from XPath 1.0; XQuery has just extended it to cover its additional types. In the process, XQuery has also changed how the string() function converts values of type xs:double to string. In XPath 1.0, doubles didn't use scientific notation and the special values positive and negative infinity converted to the strings "Infinity" and "-Infinity", respectively. In XQuery, doubles do use scientific E-notation, and the infinities are converted to "INF" and "-INF", respectively (matching the string representation used by XML Schema).

Example C.92. string examples

string(())                    => ""
string(true())                => "true"
string(1.0)                   => "1.0"
string(xs:double(1.0))        => "1.0E0"
string(1 div 0)               => INF
string(<x>a<y>b</y><x>)       => "ab"
string(xs:date("2004-09-08")) => "2004-09-08"

See also: boolean() and number(), Appendix A, and cast as in Appendix B.

The first argument specifies the sequence of strings to join. The second argument specifies a delimiter to insert between strings.

If the first argument is the empty sequence, then the empty string is returned. If the second argument is the empty string, then the strings are concatenated together like with the concat() function. Otherwise, string-join() concatenates the strings together, inserting the delimiter between them (when there are two or more strings in the sequence).

Example C.93. string-join examples

string-join(("a", "b", "c"), "")   => "abc"
string-join(("a", "b", "c"), " ")  => "a b c"
string-join(("a", "b", "c"), ", ") => "a, b, c"
string-join((), "x")               => ""
string-join("a", "x")              => "a"
string-join(("a", "b", "c"))  => error (: requires two arguments :)
string-join("a", "b", "c")    => error (: requires two arguments :)

See also: concat().

The optional argument specifies the string expression to measure. If omitted, then string-length() is applied to the current context item, converting it to string as if by calling the string() function.

If the argument is the empty sequence, then string-length() returns zero. Otherwise, string-length() returns the integer length of the string. It is exactly the same as count(string-to-codepoints($theString)).

Example C.94. string-length examples

string-length(())             => 0
string-length('')             => 0
string-length("Hello, world") => 12
string-length(1)              => error()

See also: count() and string().

The argument specifies a string. If the argument is the empty string, then string-to-codepoints() returns the empty sequence. Otherwise, string-to-codepoints() returns the sequence of integer Unicode code points corresponding to the characters in the string.

Example C.95. string-to-codepoints examples

string-to-codepoints("Hello") => (72, 101, 108, 108, 111)
string-to-codepoints("")      => ()

See also: codepoints-to-string().

The first argument specifies the sequence to use and the second argument specifies a start position (remember, the first item is at position 1). The optional third argument specifies the length of the subsequence; when omitted, subsequence()returns all items from the start position to the end of the original sequence.

If the sequence is empty, then subsequence() returns the empty sequence. Otherwise, subsequence() first applies round() to the position and length arguments, and then returns the subsequence of items starting at the rounded position value and continuing for the rounded length. If the rounded starting position is less than 1, then the subsequence starts from the beginning of the sequence. If the rounded length plus the rounded starting position exceeds the length of the sequence, then the subsequence includes all items from the start position to the end of the sequence.

In this way, subsequence($seq $start, $len) is equivalent to the path ($seq)[round($start) <= position() and position() < round($start) + round($len)] and, similarly, the expression subsequence($sequence, $start) is equivalent to the path ($sequence)[round($start) < position()].

Example C.96. subsequence examples

subsequence((1,2,4), 2)    => (2, 4)
subsequence((1,2,4), 2, 1) => 2
subsequence((1,2,4), 0, 3) => (1, 2)
subsequence((1,2,4), -1)   => (1, 2, 4)

See also: remove().

The first argument specifies the original string, and the second argument specifies the index at which to begin the substring. The optional third argument specifies the length of the substring; when omitted, the substring continues to the end of the string. The second and third arguments are rounded to an integer as if by the round() function.

If the first argument is the empty sequence, then substring() returns the empty string. Otherwise, substring returns a (possibly empty) substring of the original string. If the start index is less than 1 after rounding, then the substring begins at the first character. Remember that XQuery uses 1-based indices, so the first character is at position 1. If the length after rounding is greater than the number of remaining characters, then the substring continues to the end of the string.

As in XPath 1.0, substring() uses the Unicode code point collation to perform the substring comparison.

Example C.97. substring examples

substring((), 1, 2)                 => ""
substring("Hello, world", 8, 0)     => ""
substring("Hello, world", 8, 5)     => "world"
substring("Hello, world", 8)        => "world"
substring("Hello, world", 8, 100)   => "world"
substring("Hello, world", 7.5, 4.5) => "world"
substring("Hello, world", 7.4, 4.4) => " wor"
substring("Hello, world", -1)       => "Hello, world"
substring("Hello, world", 1)        => "Hello, world"
substring("Hello, world", 2)        => "ello, world"
substring("abc", -1 div 0)          => "abc"
substring("abc", -1 div 0, 3)       => ""

See also: substring-after() and substring-before().

The first argument specifies the original string and the second argument specifies the substring match pattern. The optional third argument specifies the collation to use for comparisons; it defaults to the Unicode code point collation.

If the first argument is the empty sequence or the empty string, then substring-after() returns the empty string. Otherwise, if the second argument is the empty sequence or the empty string, then substring-after() returns the first argument.

Otherwise, substring-after() searches from the beginning of the original string for the first occurrence of the substring match pattern (using the collation to perform comparisons). If no match is found, or the first match occurs at the end of the original string, then substring-after() returns the empty string. Otherwise, it returns the substring of the original string from the first character after the match to the end of the original string.

Example C.98. substring-after examples

substring-after((), "x")              => ""
substring-after("x", ())              => "x"
substring-after("Hello, world", "")   => "Hello, world"
substring-after("Hello, world", " ")  => "world"
substring-after("Hello, world", "ll") => "o, world"
substring-after("Hello, world", "x")  => ""

See also: substring() and substring-before(), and collation in Appendix B.

The first argument specifies the original string, and the second argument specifies the substring match pattern. The optional third argument specifies the collation to use for comparisons; it defaults to the Unicode code point collation.

If the first argument is the empty sequence or the empty string, then substring-before() returns the empty string. Otherwise, if the second argument is the empty sequence or the empty string, then substring-before() returns the first argument.

Otherwise, substring-before() searches from the beginning of the original string for the first occurrence of the substring match pattern (using the collation to perform comparisons). If no match is found, or the first match occurs at the beginning of the original string, then substring-before() returns the empty string. Otherwise, it returns the substring of the original string from the first character of the original string to the beginning of the match.

Example C.99. substring-before examples

substring-before((), "x")              => ""
substring-before("x", ())              => "x"
substring-before("Hello, world", "")   => "Hello, world"
substring-before("Hello, world", " ")  => "Hello,"
substring-before("Hello, world", "ll") => "He"
substring-before("Hello, world", "x")  => ""

See also: substring() and substring-after(), and collation in Appendix B.

The first argument specifies the initial xs:dateTime value; the second argument specifies the xs:dateTime value to subtract from the first argument. If either argument is the empty sequence, then the empty sequence is returned.

Both arguments are first normalized, including adjusting to the implicit time zone if necessary (see adjust-dateTime-to-timezone()). Then the second is subtracted from the first, producing some (possibly negative) number of seconds. From this value, the number of days, hours, minutes, and seconds are calculated and returned as an xdt:dayTimeDuration, and the remainder (years and months) is discarded.

Example C.100. subtract-dateTimes-yielding-dayTimeDuration example

subtract-dateTimes-yielding-dayTimeDuration(
    xs:dateTime("2004-06-20T18:05:13.8"),
    xs:dateTime("2002-02-18T11:42:00")
) => xdt:dayTimeDuration("P2DT6H23M13.8S")

See also: adjust-dateTime-to-timezone() and subtract-dateTimes-yielding-yearMonthDuration().

The first argument specifies the initial xs:dateTime value; the second argument specifies the xs:dateTime value to subtract from the first argument. If either argument is the empty sequence, then the empty sequence is returned.

Both arguments are first normalized, including adjusting to the implicit time zone if necessary (see adjust-dateTime-to-timezone()). Then the second is subtracted from the first, producing some (possibly negative) number of seconds. From this value, the number of years and months are calculated and returned as an xdt:yearMonthDuration, and the remainder (days, hours, minutes, and seconds) is discarded.

Example C.101. subtract-dateTimes-yielding-yearMonthDuration example

subtract-dateTimes-yielding-yearMonthDuration(
    xs:dateTime("2004-06-20T18:05:13.8"),
    xs:dateTime("2002-02-18T11:42:00")
) => xdt:yearMonthDuration("P2Y4M")

See also: adjust-dateTime-to-timezone() and subtract-dateTimes-yielding-dayTimeDuration().

The argument is the sequence of values to be summed.

If the sequence is empty, then the double value 0.0E0 is returned. Any untyped items are promoted to xs:double. If all items in the sequence cannot be promoted to a common type, or don't have types that can be summed, then an error occurs.

Otherwise, all items in the sequence are promoted to a common type and added together to produce the result. If any value is NaN, then sum() returns NaN.

Example C.102. sum examples

sum((1.0, 2, 3.0E0)) => 6.0E0
sum(())              => 0.0E0
sum(0)               => 0
sum(1, 3)            => 4

See also: avg(), count(), max(), and min().

The first argument specifies the input string, and the second argument specifies the delimiter that separates tokens. An optional third string can be used to specify flags that control how the tokenization is performed; if omitted, it defaults to the empty string.

If the first argument is the empty sequence, then the empty sequence is returned. If the third argument contains invalid flags, then an error is raised. Otherwise, tokenize() splits the string at every occurrence of the delimiter, resulting in a sequence of substrings (tokens), excluding the delimiter itself. Whenever the delimiter appears twice in a row or at the beginning or end of the input string, an empty string is used in the return sequence.

The same flags that are used to modify matches() and replace() are used by tokenize(). See Appendix D for details.

The tokenize() function is essentially the opposite of the string-join() function.

Example C.103. tokenize examples

tokenize("Hello, world", ", ")     => ("Hello", "world")
tokenize("Hello, world", "l")      => ("He", "", "o, wor", "d")
tokenize("Hello, world", "h", "i") => ("", "ello, world")

Unfortunately, the pattern used by tokenize() isn't a regular expression. However, you can achieve a similar effect by first applying replace() to match the regular expression of interest and replace it with some pattern that doesn't otherwise occur in the string, and then applying tokenize() to the replaced string.

Example C.104. tokenize can be combined with regular expressions

tokenize(replace("Hello, world", "l.", "X"), "X") => ("He", "o, wor", "")

See also: matches(), replace(), string-join(), and Appendix D.

The first argument is the return value for this function, and may also be used by the implementation during tracing. The second argument is a trace message.

The effect of the trace() function is implementation-defined; the idea is to provide the ability to emit messages during execution without terminating the query (similar to the <xsl:message> instruction in XSLT), but implementations are free to do anything, including nothing. The return value of the trace function is its first argument.

Also note that implementations may reorder or eliminate instructions; for example, trace(true(), "x") and trace(false(), "y") might execute neither, one, or both trace methods, in any order, depending on how the query is optimized and executed.

Example C.105. trace example

trace(("x", $x), "The value of {1} is {2}.")

See also: error().

The first argument is the original string. The second and third arguments specify the characters to be replaced.

If any argument is the empty sequence, then translate() returns the empty sequence. If the third argument is longer than the second argument, extra characters are ignored. Otherwise, translate() replaces in the original string all occurrences of characters in the second argument by the corresponding characters in the third argument. When there isn't a corresponding character in the third argument (because the second argument is longer), then the character is removed.

Example C.106. translate examples

translate("Hello, world", "le", "pix")           => "Hippo, worpd"
translate("Hello, world", "elo w", "")           => "Herd"
translate("Hello", "abcdefghijklmnopqrstuvwxyz",
                   "ABCDEFGHIJKLMNOPQRSTUVWXYZ") => "HELLO"
translate("Hello", (), "x")                      => ()

The translate() function is in XQuery primarily for backwards compatibility with XPath 1.0 (where it was used mainly as a poor-man's upper-case() and lower-case()).

See also: lower-case(), replace(), and upper-case().

Returns the boolean constant true.

XQuery defines the true constant using a function mainly for backwards compatibility with XPath 1.0 and to eliminate the need for reserved keywords.

Example C.107. true example

true()   => true

See also: false().

The first argument specifies the sequence to use. The unordered() function then returns this sequence in any order (often in the same order as the original).

This function is really useful only as an optimization hint to the query processor that the expression order doesn't need to be maintained. For example, most path expressions implicitly sort by document order, but if this is unimportant to your application, then applying the unordered() function to such expressions may improve performance (depending on the implementation).

Example C.108. unordered example

unordered(doc('orders.xml')//order)

See also: Chapter 13.

The argument specifies the string to be converted to uppercase.

If the argument is the empty sequence, upper-case() returns the empty sequence. Otherwise, upper-case() returns the string with all characters translated into their uppercase forms. Characters without uppercase forms are unchanged.

Note that changing case can alter the length of the string.

Example C.109. upper-case examples

upper-case("Hello, world") => "HELLO, WORLD"
upper-case("")             => ""
upper-case(())             => ()

See also: lower-case().

The argument specifies the sequence to use. This function returns the sequence unchanged if it has length at most one, otherwise it raises an error.

Example C.110. zero-or-one examples

zero-or-one(())    => ()
zero-or-one(1)     => (1)
zero-or-one((1,2)) => error

Many functions and operators in XQuery work only on sequences with a length of at most one. One way to ensure that a sequence has the required length is to use the zero-or-one() function, as shown in Listing C.111.

Example C.111. Applying an operator to a sequence using zero-or-one

doc(zero-or-one(locations/@href))

A different way to achieve a similar effect is to iterate over the sequence with FLWOR and apply the operator to each member of the sequence individually, as shown in Listing C.112. Note that this can result in a sequence of more than one value; the choice of this approach versus zero-or-one() depends on the desired effect.

Example C.112. Applying an operator to a sequence memberwise

for $i in locations/@href
return doc($i)

See also: exactly-one() and one-or-more().

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.217.203.172