The presentation of this document has been augmented to identify changes from a previous version. Three kinds of changes are highlighted: new, added text, changed text, and deleted text.
Copyright © 2002 W3C® (MIT, INRIA, Keio), All Rights Reserved. W3C liability, trademark, document use, and software licensing rules apply.
This document defines basic operators and functions on the datatypes defined in [XML Schema Part 2: Datatypes] for use in XQuery, XPath, XSLT and other related XML standards. It also discusses operators and functions on nodes and node sequences as defined in the [XQuery 1.0 and XPath 2.0 Data Model] for use in XQuery, XPath, XSLT and other related XML standards.
This section describes the status of this document at the time of its publication. Other documents may supersede this document. The latest status of this document series is maintained at the W3C.
This is a Public Working Draft of this document for review by W3C Members and other interested parties. It is a draft document and may be updated, replaced, or made obsolete by other documents at any time. It is inappropriate to use W3C Working Drafts as reference material or to cite them as other than "work in progress". This is work in progress and does not imply endorsement by the W3C membership.
This document describes constructor functions, operators, and functions that are used in [XPath 2.0], [XQuery 1.0: An XML Query Language], and [XSLT 2.0] and possibly other W3C specifications.
Among the more important changes from the previous version of this document is that an error function has been added (see 3 The Error Function) and there has been some amplification of the rules for constructing simple types and for casting (see section 4 Constructor Functions and section 16 Casting Functions). This work is not yet complete and will be further elaborated in forthcoming versions of this specification. Another area currently under discussion is whether the input timezone on date and time types needs to be preserved. This also impacts the functions to add and remove timezones from date and time values that is discussed in 8.6 Timezone Functions on dateTime, date, and time.
This document has been produced following the procedures set out for the W3C Process. This document was produced through the efforts of a joint task force of the W3C XML Query Working Group and the W3C XML Schema Working Group (both part of the W3C XML Activity) and a second joint task force of the W3C XML Query Working Group and the W3C XSL Working Group (part of the W3C Style Activity). It is designed to be read in conjunction with the following documents: [XQuery 1.0 and XPath 2.0 Data Model], [XPath 2.0], [XQuery 1.0: An XML Query Language] and [XSLT 2.0].
The following are identified as high priority issues. Reviewers are requested to provide feedback on these issues using the address below.
[Issue 186: Preserve original timezone in date/time values.]
[Issue 185: Remove op:duration-equal]
Public comments on this document and its open issues are welcome. Comments should be sent to the W3C XPath/XQuery mailing list, public-qt-comments@w3.org (archived at http://lists.w3.org/Archives/Public/public-qt-comments/).
Patent disclosures relevant to this specification may be found on the XML Query Working Group's patent disclosure page and the XSL Working Group's patent disclosure page.
A list of current W3C Recommendations and other technical documents can be found at http://www.w3.org/TR/.
1 Introduction
    1.1 Terminology
    1.2 Datatypes
    1.3 Syntax
    1.4 Notations
    1.5 Namespace
Prefix
2 Accessors
    2.1 fn:node-kind
    2.2 fn:node-name
    2.3 fn:string
    2.4 fn:data
    2.5 fn:base-uri
    2.6 fn:unique-ID
3 The Error Function
    3.1 Examples
4 Constructor Functions
    4.1 Constructor Functions for XML
Schema Built-in Types
    4.2 Constructor Functions
for User-Defined Types
5 Functions and Operators on Numerics
    5.1 Numeric Types
    5.2 Operators on Numeric
Values
        5.2.1 op:numeric-add
        5.2.2 op:numeric-subtract
        5.2.3 op:numeric-multiply
        5.2.4 op:numeric-divide
        5.2.5 op:numeric-integer-divide
        5.2.6 op:numeric-mod
        5.2.7 op:numeric-unary-plus
        5.2.8 op:numeric-unary-minus
    5.3 Comparison of Numeric
Values
        5.3.1 op:numeric-equal
        5.3.2 op:numeric-less-than
        5.3.3 op:numeric-greater-than
    5.4 Functions on Numeric
Values
        5.4.1 fn:floor
        5.4.2 fn:ceiling
        5.4.3 fn:round
6 Functions on Strings
    6.1 String Types
    6.2 Functions to Assemble and
Disassemble Strings
        6.2.1 fn:codepoints-to-string
        6.2.2 fn:string-to-codepoints
    6.3 Equality and Comparison
of Strings
        6.3.1 fn:compare
    6.4 Functions on String
Values
        6.4.1 fn:concat
        6.4.2 fn:string-join
        6.4.3 fn:starts-with
        6.4.4 fn:ends-with
        6.4.5 fn:contains
        6.4.6 fn:substring
        6.4.7 fn:string-length
        6.4.8 fn:substring-before
        6.4.9 fn:substring-after
        6.4.10 fn:normalize-space
        6.4.11 fn:normalize-unicode
        6.4.12 fn:upper-case
        6.4.13 fn:lower-case
        6.4.14 fn:translate
        6.4.15 fn:string-pad
        6.4.16 fn:matches
        6.4.17 fn:replace
        6.4.18 fn:tokenize
        6.4.19 fn:escape-uri
7 Functions and Operators on Booleans
    7.1 Boolean Constructor
Functions
        7.1.1 fn:true
        7.1.2 fn:false
    7.2 Operators on Boolean
Values
        7.2.1 op:boolean-equal
        7.2.2 op:boolean-less-than
        7.2.3 op:boolean-greater-than
    7.3 Functions on Boolean
Values
        7.3.1 fn:not
8 Functions and Operators on Durations,
Dates, and Times
    8.1 Duration, Date, and Time
Types
    8.2 Two Totally Ordered
Subtypes of Duration
        8.2.1 yearMonthDuration
        8.2.2 dayTimeDuration
    8.3 Comparisons of
Duration, Date and Time Values
        8.3.1 op:duration-equal
        8.3.2 op:yearMonthDuration-equal
        8.3.3 op:yearMonthDuration-less-than
        8.3.4 op:yearMonthDuration-greater-than
        8.3.5 op:dayTimeDuration-equal
        8.3.6 op:dayTimeDuration-less-than
        8.3.7 op:dayTimeDuration-greater-than
        8.3.8 op:dateTime-equal
        8.3.9 op:dateTime-less-than
        8.3.10 op:dateTime-greater-than
        8.3.11 op:date-equal
        8.3.12 op:date-less-than
        8.3.13 op:date-greater-than
        8.3.14 op:time-equal
        8.3.15 op:time-less-than
        8.3.16 op:time-greater-than
        8.3.17 op:gYearMonth-equal
        8.3.18 op:gYear-equal
        8.3.19 op:gMonthDay-equal
        8.3.20 op:gMonth-equal
        8.3.21 op:gDay-equal
    8.4 Component Extraction Functions
on Duration, Date and Time Values
        8.4.1 fn:get-years-from-yearMonthDuration
        8.4.2 fn:get-months-from-yearMonthDuration
        8.4.3 fn:get-days-from-dayTimeDuration
        8.4.4 fn:get-hours-from-dayTimeDuration
        8.4.5 fn:get-minutes-from-dayTimeDuration
        8.4.6 fn:get-seconds-from-dayTimeDuration
        8.4.7 fn:get-year-from-dateTime
        8.4.8 fn:get-month-from-dateTime
        8.4.9 fn:get-day-from-dateTime
        8.4.10 fn:get-hours-from-dateTime
        8.4.11 fn:get-minutes-from-dateTime
        8.4.12 fn:get-seconds-from-dateTime
        8.4.13 fn:get-timezone-from-dateTime
        8.4.14 fn:get-year-from-date
        8.4.15 fn:get-month-from-date
        8.4.16 fn:get-day-from-date
        8.4.17 fn:get-timezone-from-date
        8.4.18 fn:get-hours-from-time
        8.4.19 fn:get-minutes-from-time
        8.4.20 fn:get-seconds-from-time
        8.4.21 fn:get-timezone-from-time
    8.5 Arithmetic Functions on
yearMonthDuration and dayTimeDuration
        8.5.1 op:add-yearMonthDurations
        8.5.2 op:subtract-yearMonthDurations
        8.5.3 op:multiply-yearMonthDuration
        8.5.4 op:divide-yearMonthDuration
        8.5.5 op:add-dayTimeDurations
        8.5.6 op:subtract-dayTimeDurations
        8.5.7 op:multiply-dayTimeDuration
        8.5.8 op:divide-dayTimeDuration
    8.6 Timezone Functions
on dateTime, date, and time
        8.6.1 fn:add-timezone-to-dateTime
        8.6.2 fn:remove-timezone-from-dateTime
        8.6.3 fn:add-timezone-to-date
        8.6.4 fn:add-timezone-to-time
        8.6.5 fn:remove-timezone-from-time
    8.7 Adding and
Subtracting Durations From dateTime, date and   time
        8.7.1 fn:subtract-dateTimes-yielding-yearMonthDuration
        8.7.2 fn:subtract-dateTimes-yielding-dayTimeDuration
        8.7.3 op:subtract-dates
        8.7.4 op:subtract-times
        8.7.5 op:add-yearMonthDuration-to-dateTime
        8.7.6 op:add-dayTimeDuration-to-dateTime
        8.7.7 op:subtract-yearMonthDuration-from-dateTime
        8.7.8 op:subtract-dayTimeDuration-from-dateTime
        8.7.9 op:add-yearMonthDuration-to-date
        8.7.10 op:add-dayTimeDuration-to-date
        8.7.11 op:subtract-yearMonthDuration-from-date
        8.7.12 op:subtract-dayTimeDuration-from-date
        8.7.13 op:add-dayTimeDuration-to-time
        8.7.14 op:subtract-dayTimeDuration-from-time
9 Functions Related to QNames
    9.1 Constructor Functions for
QNames
        9.1.1 fn:QName-in-context
    9.2 Functions Related to
QNames
        9.2.1 op:QName-equal
        9.2.2 fn:get-local-name-from-QName
        9.2.3 fn:get-namespace-from-QName
        9.2.4 fn:get-namespace-uri-for-prefix
        9.2.5 fn:get-in-scope-namespaces
10 Functions and Operators for anyURI
    10.1 Constructor Functions for
anyURI
        10.1.1 fn:resolve-uri
    10.2 Functions on anyURI
        10.2.1 op:anyURI-equal
11 Functions and Operators on base64Binary and
hexBinary
    11.1 Comparisons of base64Binary
and hexBinary Values
        11.1.1 op:hexBinary-equal
        11.1.2 op:base64Binary-equal
12 Functions and Operators on NOTATION
    12.1 Functions on NOTATION
        12.1.1 op:NOTATION-equal
13 Functions and Operators on Nodes
    13.1 Functions and Operators on
Nodes
        13.1.1 fn:name
        13.1.2 fn:local-name
        13.1.3 fn:namespace-uri
        13.1.4 fn:number
        13.1.5 fn:lang
        13.1.6 op:node-equal
        13.1.7 fn:deep-equal
        13.1.8 op:node-before
        13.1.9 op:node-after
        13.1.10 fn:root
14 Functions and Operators on Sequences
    14.1 Constructor Functions on
Sequences
        14.1.1 op:to
    14.2 Functions and Operators on
Sequences
        14.2.1 fn:boolean
        14.2.2 op:concatenate
        14.2.3 fn:item-at
        14.2.4 fn:index-of
        14.2.5 fn:empty
        14.2.6 fn:exists
        14.2.7 fn:distinct-nodes
        14.2.8 fn:distinct-values
        14.2.9 fn:insert
        14.2.10 fn:remove
        14.2.11 fn:subsequence
        14.2.12 fn:unordered
    14.3 Equals, Union, Intersection
and Except
        14.3.1 fn:sequence-deep-equal
        14.3.2 fn:sequence-node-equal
        14.3.3 op:union
        14.3.4 op:intersect
        14.3.5 op:except
    14.4 Aggregate Functions
        14.4.1 fn:count
        14.4.2 fn:avg
        14.4.3 fn:max
        14.4.4 fn:min
        14.4.5 fn:sum
    14.5 Functions
that Generate Sequences
        14.5.1 fn:id
        14.5.2 fn:idref
        14.5.3 fn:document
        14.5.4 fn:collection
        14.5.5 fn:input
15 Context Functions
    15.1 fn:context-item
    15.2 fn:position
    15.3 fn:last
    15.4 fn:current-dateTime
        15.4.1 Examples
    15.5 fn:current-date
        15.5.1 Examples
    15.6 fn:current-time
        15.6.1 Examples
    15.7 fn:default-collation
    15.8 fn:implicit-timezone
16 Casting Functions
    16.1 Casting from primitive types to
primitive types
    16.2 Casting   
to derived types
    16.3 Casting from derived types to parent
types
    16.4 Casting within
a branch of the type hierarchy
    16.5 Casting
across the type hierarchy
    16.6 Casting from
string and anySimpleType
    16.7 Casting to string
and anySimpleType
    16.8 Casting to
numeric types
    16.9 Casting to duration and date and time
types
    16.10 Casting to boolean
    16.11 Casting to base64Binary and
hexBinary
    16.12 Casting to anyURI 
    16.13 Casting to
NOTATION
A References
    A.1 Normative
    A.2 Non-normative
B Compatibility with XPath 1.0
(Non-Normative)
C Illustrative User-written Functions
(Non-Normative)
    C.1 eg:if-empty() and
eg:if-absent()
        C.1.1 eg:if-empty()
        C.1.2 eg:if-absent()
    C.2 union, intersect and except on
sequences of values
        C.2.1 eg:value-union()
        C.2.2 eg:value-intersect()
        C.2.3 eg:value-except()
D Functions and Operators Issues List
(Non-Normative)
E ChangeLog since Last Public Version on 2002-08-16
(Non-Normative)
F Function and Operator Quick Reference
(Non-Normative)
    F.1 Functions and Operators by
Section
    F.2 Functions and Operators
Alphabetically
[XML Schema Part 2: Datatypes] defines a number of primitive and derived datatypes, collectively known as built-in datatypes. This document defines operations on those datatypes for use in XQuery, XPath, XSLT and related XML standards. This document also discusses operators and functions on nodes and node sequences as defined in the [XQuery 1.0 and XPath 2.0 Data Model] for use in XQuery, XPath, XSLT and other related XML standards.
The terminology used to describe the functions and operators on [XML Schema Part 2: Datatypes] is defined in the body of this specification. The terms defined in the following list are used in building those definitions:
A feature of this specification included to ensure that implementations that use this feature remain compatible with [XPath 1.0]
Conforming documents and processors are permitted to but need not behave as described.
Conforming documents and processors are required to behave as described; otherwise, they are non-conformant or in error.
Possibly differing between implementations, but specified by the implementor for each particular implementation.
Possibly differing between implementations, but not specified by this or other W3C specification, and not required to be specified by the implementor for any particular implementation.
The diagram below shows the built-in [XML Schema Part 2: Datatypes]. Solid lines connect a base datatype above to a derived datatype below. Dashed lines connect a datatype created as a list of an item type above.
 
Diagram courtesy Asir Vedamuthu, webMethods
The purpose of this document is to catalog the functions and operators required for XPath 2.0, XML Query 1.0, and XSLT 2.0. The exact syntax used to invoke these functions and operators is specified in [XPath 2.0], [XQuery 1.0: An XML Query Language], and [XSLT 2.0].
In general, the above specifications do not support function overloading. 
Consequently, there are no overloaded functions in this document except for
legacy [XPath 1.0] functions such as
string() which takes a single argument of a variety of types and
concat() which takes a variable number of string arguments. 
This does not apply to operators such as "+" which may be overloaded. 
Functions with optional arguments are allowed. If optional arguments are
omitted, omissions are assumed to begin from the right.
This document defines, among other things, constructor functions and other functions that apply to one or more data types. Each function is defined by specifying its signature, a description of each of its arguments, and its semantics. For many functions, examples are included to illustrate their use.
Each function's signature is presented in a form like this:
fn:function-name($parameter-name as parameter-type, ...) as return-typeIn this notation, function-name is the name of the function
whose signature is being specified.  If the function takes no parameters,
then the name is followed by an empty set of parentheses: ();
otherwise, the name is followed by a parenthesized list of parameter
declarations, each declaration specifying the static type of the parameter
and a non-normative name used to reference the parameter when the function's
semantics are specified.  If there are two or more parameter declarations,
they are separated by a comma. The return-type specifies the
static type of the value returned by the function.  In
most cases, the dynamic type returned by the function is the same as its
static type.  The few exceptions to this rule are documented in specific
functions.
The function name is a QName as defined in [XML 1.0 Recommendation (Second Edition)] and must adhere to
its syntactic conventions. Following [XPath 1.0],
function names are composed of English words separated by hyphens,"-".  If a
function name contains a [XML Schema Part 2:
Datatypes] datatype name, this may have intercapitalized spelling and is
used in the function name as such. For example, fn:get-timezone-from-dateTime.
As is customary, the parameter type name indicates that the function accepts arguments of that type, or types derived from it, in that position. This is called subtype substitution. Details of the semantics of passing parameters to functions are discussed in Appendix B of [XQuery 1.0: An XML Query Language].
Some functions accept the empty sequence as an argument and some may return the empty sequence. This is indicated in the function signature by following the parameter type name with a question mark:
fn:function-name($parameter-name as parameter-type?) as return-type?The functions and operators discussed in this document are contained in
three namespaces (see [Namespaces in XML]) and referenced using a QName.
Constructor functions for the built-in datatypes
defined in [XML Schema Part
2: Datatypes] discussed in 4 Constructor
Functions are in the XML Schema
namespace and named in this document using the xs: prefix.   The namespace prefix used in this document   is
fn: for the user functions
and op: for the operator functions. The namespace prefix for
these functions can vary, as long as the prefix is bound to the correct URI.
The URIs of the namespaces are:
http://www.w3.org/2001/XMLSchema-datatypes
    for constructors
http://www.w3.org/2002/11/xquery-operators
      for operators
http://www.w3.org/2002/11/xquery-functions
    for functions.
The functions defined with an fn: prefix are callable by the user. Functions
defined with the op: prefix are described here to underpin the
definitions of the operators in [XPath 2.0], [XQuery 1.0: An XML Query Language], and  [XSLT 2.0]. These functions are not available directly to
users, and there is no requirement that implementations should actually
provide these functions. For example, multiplication is generally associated
with the * operator, but it is described as a function in this
document. For example:
op:multiply($operand1 as numeric, $operand2 as numeric) as numericThe [XQuery 1.0 and XPath 2.0 Data Model] describes accessors on different types of nodes and defines their semantics. Some of these accessors are exposed to the user through the functions described below.
| Function | Accessor | Accepts | Returns | 
|---|---|---|---|
| fn:node-kind | node-kind | any kind of node | string | 
| fn:node-name | name | any kind of node | zero or one QName | 
| fn:string | string-value | item | string | 
| fn:data | typed-value | any kind of node | a sequence of atomic values | 
| fn:base-uri | class="diff-add"base-uri | Element or Document node or no argument | 
fn:unique-IDunique-IDfn:node-kind($srcval as node) as stringThis function returns a string value representing the node's kind: either "document", "element", "attribute", "text", "namespace", "processing-instruction", or "comment".
fn:node-name($srcval as node) as QName?This function returns an expanded-QName for node kinds that can have names. For other node kinds, it returns the empty sequence. Expanded-QName is defined in [XQuery 1.0 and XPath 2.0 Data Model], and consists of a namespace URI and a local name.
fn:string() as stringfn:string($srcval as item?) as stringReturns the value of $srcval represented as a string. If no
argument is supplied, $srcval defaults to the context item
(.).
If $srcval is the empty sequence, the zero-length string is
returned.
If $srcval is a node, the function returns the string value
of the node, as obtained using the string-value accessor defined in the [XQuery 1.0 and XPath 2.0 Data Model].
If $srcval is an atomic value, then the function returns the
same string as is returned by the expression cast as xs:string
($srcval), except in the cases listed below:
If the type of $srcval is xs:anyURI, the
    URI is converted to a string without any escaping of special
    characters.
NOTE: The reason for the special rule for xs:anyURI is that,
although XML Schema strongly discourages the use of spaces within URI values,
the escaping of spaces can cause problems with legacy applications (for
example, this applies to spaces within fragment identifiers in many HTML
browsers), and should therefore be under user control.
NOTE: The string representation of double values is not backwards-compatible with the representation of number values in [XPath 1.0]. Ordinary double values are now represented using scientific notation; the representations of positive and negative infinity are now 'INF' and '-INF' rather than 'Infinity' and '-Infinity'. (It should be observed that '+INF' is not supported as a lexical form of infinity in [XML Schema Part 2: Datatypes] and is thus not supported by this specification; if that lexical form is added in a future version of [XML Schema Part 2: Datatypes], then it will be supported by a future version of this specification that aligns with that future version of [XML Schema Part 2: Datatypes].) However, most expressions that would have produced a number in [XPath 1.0] will produce a decimal (or integer) in [XPath 2.0], so unless there is a loss of precision caused by numeric approximation, the result of the expression will in most simple cases be the same after conversion to a string.
fn:data($srcval as node) as atomic
value*If $srcval is a text node, an element node, or an attribute
node, fn:data returns the typed
value of $srcval, as defined by the accessor function
dm:typed-value defined for that kind of node in [XQuery 1.0 and XPath 2.0 Data Model].
Specifically:
If $srcval is a text node, then its typed value is equal to
its string value, as an instance of xs:anySimpleType.
If $srcval is an attribute node with type annotation
xs:anySimpleType, then its typed value is equal to its string
value, as an instance of xs:anySimpleType. The typed value of
any other attribute node is derived from its string value and type annotation
in a way that is consistent with XML Schema
validation, as described in [XQuery 1.0 and XPath
2.0 Data Model].
If $srcval is an element node with type annotation
xs:anyType, then its typed value
is equal to its string value, as an instance of
xs:anySimpleType. The typed value of an element node with a type annotation other than xs:anyType is derived from its string value
and type annotation in a way that is consistent with XML Schema validation, as described in [XQuery 1.0 and XPath 2.0 Data Model]. If $srcval is an
element node whose type annotation denotes a type with complex content (i.e.,
a type that permits subelements), fn:data raises
an error (Node has complex content).
If $srcval is not a text node, an attribute node, or an
element node, then fn:data causes
a  type error.
fn:base-uri($srcval as node) as anyURI?For document and element nodes, this function returns the value of the base-uri property. For other kinds of node, it returns the empty sequence.
fn:base-uri() as anyURI?This version of the function returns the base-uri from the static context.
fn:unique-ID($srcval as node) as ID?This function accepts an element node and returns the identifier (ID) which may have been assigned by the user. It corresponds to the normalized value property of the attribute information item in the attributes property that has a type ID, if one exists. If no ID attribute exists the empty sequence is returned.
In this document, as well as in [XQuery 1.0: An XML
Query Language], [XPath 2.0],and [XQuery 1.0 and XPath 2.0 Formal Semantics], the
phrase "an error is raised" is used whenever the semantics being described
encounter an error other than a static type error.  The occurrence of that
phrase implicitly causes the invocation of the fn:error function defined in this section. 
Whenever the raising of an error is accompanied by a specific error, the
phrase "an error is raised (name-of-error)" is used, and the value
name-of-error is passed as an argument to the fn:error function invocation.
The fn:error function may also
be invoked from XQuery and XPath 2.0 applications.
fn:error() as nonefn:error($srcval as item?) as noneThe fn:error function accepts
any item (e.g., an atomic value or an element) as an argument.  An alternate
version of the function takes no arguments. 
The fn:error function never
returns a value.
Note that "none" is a special type defined in the [XQuery 1.0 and XPath 2.0 Formal Semantics] and is not available to the user. It indicates that the function never returns and ensures that it has the correct static type.
Every built-in type that is defined in [XML Schema Part
2: Datatypes], except xs:QName, as
well as each of the two derived types fn:yearMonthDuration and fn:dayTimeDuration defined in this
specification, has an associated constructor function. The form of that
function for a type TYP is:
xs:TYP($srcval as item) as TYPFor example, the signature of the constructor function corresponding to
the unsignedInt type defined in [XML Schema Part 2: Datatypes] is:
xs:unsignedInt($srcval as item) as unsignedIntInvoking   the
constructor function   xs:unsignedInt(12) returns the
unsignedInt value 12. Another invocation of that constructor
function that returns the same unsignedInt value is
xs:unsignedInt("12").
If the argument to a constructor function is a string literal, the literal must be a valid lexical form for its type, as specified in [XML Schema Part 2: Datatypes] and the semantics of the function are identical to XML Schema validation. Whitespace normalization is applied before validation as indicated by the value of the whitespace facet for the datatype.
If the argument to a constructor function is a literal, the result of the function may be evaluated statically; if an error is found during such evaluation, it may be reported as a static error.
The semantics of the constructor function
xs:TYP(item) are identical to the semantics of "cast as xs:TYP (item)".  See  16 Casting Functions
The following constructor functions for the built-in types are supported:
xs:string($srcval as item) as stringxs:boolean($srcval as item) as booleanxs:decimal($srcval as item) as decimalxs:float($srcval as item) as floatxs:double($srcval as item) as doublexs:duration($srcval as item) as durationxs:dateTime($srcval as item) as dateTimexs:time($srcval as item) as timexs:date($srcval as item) as datexs:gYearMonth($srcval as item) as gYearMonthxs:gYear($srcval as item) as gYearxs:gMonthDay($srcval as item) as gMonthDayxs:gDay($srcval as item) as gDayxs:gMonth($srcval as item) as gMonthxs:hexBinary($srcval as item) as hexBinaryxs:base64Binary($srcval as item) as base64Binaryxs:anyURI($srcval as item) as anyURIxs:NOTATION($srcval as item) as NOTATIONxs:normalizedString($srcval as item) as normalizedStringxs:token($srcval as item) as tokenxs:language($srcval as item) as languagexs:NMTOKEN($srcval as item) as NMTOKENxs:NMTOKENS($srcval as item) as NMTOKENSxs:Name($srcval as item) as Namexs:NCName($srcval as item) as NCNamexs:ID($srcval as item) as IDxs:IDREF($srcval as item) as IDREFxs:IDREFS($srcval as item) as IDREFSxs:ENTITY($srcval as item) as ENTITYxs:ENTITIES($srcval as item) as ENTITIESxs:integer($srcval as item) as integerxs:nonPositiveInteger($srcval as item) as nonPositiveIntegerxs:negativeInteger($srcval as item) as negativeIntegerxs:long($srcval as item) as longxs:int($srcval as item) as intxs:short($srcval as item) as shortxs:byte($srcval as item) as bytexs:nonNegativeInteger($srcval as item) as nonNegativeIntegerxs:unsignedLong($srcval as item) as unsignedLongxs:unsignedInt($srcval as item) as unsignedIntxs:unsignedShort($srcval as item) as unsignedShortxs:unsignedByte($srcval as item) as unsignedBytexs:positiveInteger($srcval as item) as positiveIntegerfn:yearMonthDuration($srcval as item) as yearMonthDurationfn:dayTimeDuration($srcval as item) as dayTimeDurationFor every type defined in the static query context (See [XQuery 1.0: An XML Query Language] that is derived by restriction from a primitive type, there is a construction function (whose name is the same as the type name), whose effect is to create a value of that type from the supplied argument. The rules are defined in the same way as for built-in derived types 4.1 Constructor Functions for XML Schema Built-in Types.
Consider a situation where the static context
contains a type called hatSize defined in a
schema that is bound to the prefix my.  In such a case the
constructor function:
my:hatSize($srcval as item) as hatSizeis available to users.
This section discusses arithmetic operators on the numeric datatypes defined in [XML Schema Part 2: Datatypes]. It uses an approach that permits lightweight operations whenever possible.
The operators described in this section are defined on the following numeric types. Each type whose name is indented is derived from the type whose name appears nearest above with one less level of indent.
| decimal | |
| integer | |
| float | |
| double | 
They also apply to types derived by restriction from these types.
The following functions are defined to back up operators defined in [XQuery 1.0: An XML Query Language] and [XPath 2.0] on these numeric types.
| Operators | Meaning | Source | 
|---|---|---|
| op:numeric-add | Addition | XPath 1.0 | 
| op:numeric-subtract | Subtraction | XPath 1.0 | 
| op:numeric-multiply | Multiplication | XPath 1.0 | 
| op:numeric-divide | Division | XPath 1.0 | 
| op:numeric-integer-divide | Integer division | XPath 1.0 | 
| op:numeric-mod | Modulus | XPath 1.0 | 
| op:numeric-unary-plus | Unary plus | XPath 2.0 Req 1.7 Should | 
| op:numeric-unary-minus | Unary minus (negation) | XPath 1.0 | 
The arguments and return types for the arithmetic operators are the basic
numeric types: integer, decimal,
float, and double, and types derived from them. 
For simplicity, each operator is defined to operate on operands of the same
datatype and to return the same datatype. (The one exception is op:numeric-divide, which returns
a double if called with two integer operands.) If the two operands are not of
the same type, subtype substitution and type promotion may
be used to obtain
two operands of the same type. Appendix B of
[XQuery 1.0: An XML Query
Language] describes the semantics of
these operations in detail.
Subtype
    substitution: A derived
    type may substitute  for its base type. In particular,
    integer may be used where
    decimal is expected.
Type
    promotion:
    decimal may be promoted to float, and
    float may be promoted to double.
The result type of operations depends on their argument datatypes and is defined in the following table:
| Operator | Returns | 
|---|---|
| op:operation(integer,
      integer) | integer (except for op:numeric-divide(integer,
        integer), which returns a double) | 
| op:operation(decimal,
      decimal) | decimal | 
| op:operation(float, float) | float | 
| op:operation(double,
      double) | double | 
| op:operation(integer) | integer | 
| op:operation(decimal) | decimal | 
| op:operation(float) | float | 
| op:operation(double) | double | 
These rules define any operation on any pair of arithmetic types. Consider the following example:
op:operation(int, double) => op:operation(double, double)
For this operation, int must be converted to
double. This can be done, since by the rules above:
int can be substitutued for
integer,  integer can be promoted to
decimal, decimal can be promoted to
float, and float can be promoted to
double. As far as possible, the promotions should be done in a
single step.  Specifically, when a decimal is promoted to a double, it must
not be converted to a float and then to double as this will lose
precision.
As another example, a user may define height as a derived
type of integer with a minimum value of 20 and a maximum value
of 100.  He may then derive oddHeight using a pattern to
restrict the value to odd integers.
op:operation(oddHeight, integer) => op:operation(integer, integer)
oddHeight can be substituted for
its base type height and  
height can be substitutued for its base type
integer.
[Issue 177: Must overflow and underflow always be reported?]
Overflow and underflow behavior is ·implementation-defined·. See [ISO 10967]. That is, implementations may determine that, when overflow or underflow is detected in any of the above operations, an error is raised ("overflow or underflow error"). However, implementations are not required to catch or report such errors.
Finally, consider some examples involving special IEEE 754 numerics.
If either argument is "NaN", the result is "NaN".
If neither argument is "NaN", but either argument is "INF", the result is "INF".
If neither argument is "NaN" or "INF", but either argument is "-INF", the result is "-INF".
Note that in some cases such as subtraction, multiplication and division, "INF" may become "-INF", and vice versa, as appropriate.
The functions op:numeric-add,
op:numeric-subtract, op:numeric-multiply, op:numeric-divide, op:numeric-integer-divide,
and op:numeric-mod are each
defined for pairs of numeric operands, each of which has the same type:
integer, decimal, float, or double.  The functions op:numeric-unary-plus and op:numeric-unary-minus are
defined for a single operand whose type is one of those same numeric
types.
op:numeric-add($operand1 as numeric, $operand2 as numeric) as numericBacks up the "+" operator and returns the arithmetic sum of its operands:
($operand1 + $operand2).
op:numeric-subtract($operand1 as numeric, $operand2 as numeric) as numericBacks up the "-" operator and returns the arithmetic difference of its
operands: ($operand1 - $operand2).
op:numeric-multiply($operand1 as numeric, $operand2 as numeric) as numericBacks up the "*" operator and returns the arithmetic product of its
operands: ($operand1 * $operand2).
op:numeric-divide($operand1 as numeric, $operand2 as numeric) as numericBacks up the "div" operator and returns the arithmetic quotient of its
operands: ($operand1 div $operand2).
Note:
For compatibility with [XPath 1.0], if the types of
both $operand1 and $operand2 are
xs:integer, then the return type is xs:double.
For xs:decimal and xs:integer operands, if the
divisor is 0, then an error is raised ("Division by zero").  For
xs:float and xs:double operands, performs floating
point division as specified in [IEEE 754-1985].
| op:numeric-integer-divide( | $operand1 |  as integer, | 
| $operand2 |  as integer) as integer | 
Backs up the "idiv" operator and returns the arithmetic quotient of its
operands: ($operand1 idiv $operand2). If the numerator is not evenly divided by the divisor, then
the quotient is the integer value obtained, ignoring any remainder that
results from the division (that is, no rounding is performed).
If the divisor is 0, then an error is raised ("Division by
zero").
op:numeric-mod($operand1 as numeric, $operand2 as numeric) as numericBacks up the "mod" operator and returns the remainder after dividing the
first operand by the second operand: ($operand1 mod $operand2).
The result is of the same type as the operands after type promotion.  The
following rules apply:
For xs:decimal and xs:integer operands, if
    the divisor is 0, then an error is raised ("Division by
    zero").
For xs:float and xs:double operands:
If either operand is NaN, the result is NaN.
If the dividend is positive or negative infinity, or the divisor is positive or negative zero (0), or both, the result is NaN.
If not NaN, the sign of the result equals the sign of the dividend.
If the dividend is finite and the divisor is an infinity, the result equals the dividend.
If the dividend is positive or negative zero and the divisor is finite, the result is the same as the dividend.
In the remaining cases, where neither positive or negative infinity, nor positive or negative zero, nor NaN is involved, the float or double remainder r from a dividend n and a divisor d is defined by the mathematical relation r = n-(d * q) where q is an integer that is negative only if n/d is negative and positive only if n/d is positive, and whose magnitude is as large as possible without exceeding the magnitude of the true mathematical quotient of n and d. This is truncating division, analogous to integer division, not [IEEE 754-1985] rounding division.
We define the following comparison operators on numeric values.
Comparisons take two arguments of the same type.  If the arguments are of
different types, one argument is promoted to the type of the other. Each
comparison operator returns a boolean value.  If either, or both, operands
are "NaN", false is returned.
| Operator | Meaning | Source | 
|---|---|---|
| op:numeric-equal | Equality comparison | XPath 1.0 | 
| op:numeric-less-than | Less-than comparison | XPath 1.0 | 
| op:numeric-greater-than | Greater-than comparison | XPath 1.0 | 
op:numeric-equal($operand1 as numeric, $operand2 as numeric) as booleanReturns true if and only if $operand1 is exactly equal to
$operand2. For xs:float and xs:double
values, 0 (zero), +0 (positive zero), and
-0 (negative zero) all compare equal. NaN does not
equal itself.
This function backs up the "eq" and "ne" operators on numeric values.
op:numeric-less-than($operand1 as numeric, $operand2 as numeric) as booleanReturns true if and only if $operand1 is less than
$operand2.  For xs:float and xs:double
values, positive infinity is greater than all other non-NaN values; negative
infinity is less than all other non-NaN values. NaN is not comparable with
(neither greater than nor less than) any other value including itself.
This function backs up the "lt" and "ge" operators on numeric values.
op:numeric-greater-than($operand1 as numeric, $operand2 as numeric) as booleanReturns true if and only if $operand1 is greater than
$operand2.  For xs:float and xs:double
values, positive infinity is greater than all other non-NaN values; negative
infinity is less than all other non-NaN values. NaN is not comparable with
(neither greater than nor less than) any other value including itself.
This function backs up the "gt" and "le" operators on numeric values.
The following functions are defined on these numeric types. Each function returns an integer except:
If the argument is the empty sequence, the empty sequence is returned.
If the argument is "NaN", "NaN" is returned.
If the argument is positive or negative infinity, positive or negative infinity is returned.
| Function | Meaning | Source | 
|---|---|---|
| fn:floor | Returns the largest integer less than or equal to the argument | XPath 1.0 | 
| fn:ceiling | Returns the smallest integer greater than or equal to the argument | XPath 1.0 | 
| fn:round | Rounds to the nearest integer | XPath 1.0 | 
[Issue 79: How many digits of precision (etc.) are returned from certain functions?]
[Issue 142: Should floor ceiling and round return the same type as their argument? ]
[Issue 179: What is the appropriate return type for fn:floor, fn:celing, and fn:round?]
fn:floor($srcval as double?) as double?Returns the largest (closest to positive infinity) integer that is not
greater than the value of $srcval.  If the argument is the empty
sequence, returns the empty sequence.
fn:ceiling($srcval as double?) as double?Returns the smallest (closest to negative infinity) integer that is not
smaller than the value of $srcval. If the argument is the empty
sequence, returns the empty sequence.
fn:round($srcval as double?) as double?Returns the number that is closest to the argument. If there are two such
numbers, then the one that is closest to positive infinity is returned. More
formally, fn:round(x) produces the
same result as fn:floor(x+0.5). If the argument is NaN,
then NaN is returned. If the argument is positive infinity, then positive
infinity is returned. If the argument is negative infinity, then negative
infinity is returned. If the argument is positive zero (+0), then positive
zero (+0) is returned. If the argument is negative zero (-0), then negative
zero (-0) is returned. If the argument is less than zero (0), but greater
than or equal to -0.5, then negative zero (-0) is returned. If the argument
is the empty sequence, then the empty sequence is returned.
This section discusses functions and operators on the [XML Schema Part 2: Datatypes] string datatype and the datatypes derived from string.
The operators described in this section are defined on the following string types. Each type whose name is indented is derived from the type whose name appears nearest above with one less level of indent.
| string | |||||
| normalizedString | |||||
| token | |||||
| language | |||||
| NMTOKEN | |||||
| Name | |||||
| NCName | |||||
| ID | |||||
| IDREF | |||||
| ENTITY | 
They also apply to user-defined types derived by restriction from these types.
NOTE: This document uses the term "code point" as a synonym for "Unicode scalar value". [The Unicode Standard] sometimes spells this term "codepoint". Code points range from #x0000 to #x10FFFF inclusive. The use of the word 'character' in this document is in the sense of production [2] of [XML 1.0 Recommendation (Second Edition)].
| Function | Meaning | 
|---|---|
| class="diff-add"fn:codepoints-to-string | Creates a string from a sequence of codepoints. | 
fn:string-to-codepointsWhen values whose type is string or some type derived from string are compared (or, equivalently, sorted), the comparisons are inherently performed according to some collation (even if that collation is defined entirely on code point values or on the binary representations of the characters of the string). The [Character Model for the World Wide Web 1.0] observes that some applications may require different comparison and ordering behaviors than other applications. Similarly, some users having particular linguistic expectations may require different behaviors than other users. Consequently, the collation must be taken into account when comparing strings in any context. Several functions in this and the following section make use of a collation.
Collations can indicate that some characters that are rendered differently are, in fact equal for collation purpose (e.g., "uve" and "uwe" are considered equivalent in some European languages). Strings can be compared character-by-character or in a logical manner, as defined by the collation.
Some collations, especially those based on the [Unicode Collation Algorithm] can be "tailored" for various purposes. This document does not discuss such tailoring. Instead, it assumes that the collation argument to the various functions below is a tailored and named collation. A specific collation with a distinguished name, http://www.w3.org/2002/11/query-operators/collation/codepoint, provides the ability to compare strings based on code point values. Every implementation of XQuery must support the collation based on code point values.
While the [Character Model for the World Wide Web 1.0] recommends that all strings be subjected to early Unicode normalization, it is not possible to guarantee that all strings in all XML documents are, in fact, normalized, or that they are normalized in the same manner. In order to maximize interoperable results of operations on XML documents in general, there may be collations that operate on unnormalized strings, other collations that raise runtime errors when unnormalized strings are encountered, and still other collations that implicitly normalize strings for the purposes of collating them. For alignment with the [Character Model for the World Wide Web 1.0], applications may choose collations that treat unnormalized strings as though they were normalized (that is, that implicitly normalize the strings). Note that collations based on the Unicode collation algorithm produce equivalent results regardless of a string's normalization.
This document assumes that collations are named and that the collation name may be provided as an argument to string comparison functions. Functions that allow specification of a collation do so with an argument whose type is anyURI. This document also defines the manner in which a default collation is determined when the collation argument is not specified in invocations of the functions that allow it to be omitted.
The XQuery/XPath static context includes provision for a default collation that can be used for string comparisons (including ordering operations). However, the static context is not required to have a default collation specified; an implementation might choose to provide a default collation only under certain circumstances, or not at all. The static context default collation, if provided, is determined by ·implementation-defined· means. Such means might include determination from the host operating system environment, determination during XQuery/XPath installation, determination when the XQuery/XPath implementation was created, determination from the locale of some user environment, or even ·implementation-defined· language through which the user can specify that collation.
The decision of what collation to use for a given comparison or ordering operation is determined by the following algorithm:
If the operation specifies an explicit collation CollationA (e.g.,
    if the optional collation argument is specified in an invocation of the
    fn:compare() function), then:
If CollationA is supported by the implementation, then CollationA is used.
Otherwise, an error is raised ("Unsupported collation").
If no collation is explicitly specified for the operation and the XQuery/XPath static context specifies a collation CollationB, then:
If CollationB is supported by the implementation, then CollationB is used.
Otherwise, an error is raised ("Unsupported collation").
NOTE: There might be several ways in which a collation might be specified in the XQuery/XPath static context. For example, XQuery might provide syntax that specifies a default collation as part of the query prolog.
Otherwise, the Unicode codepoint collation (http://www.w3.org/2002/11/query-operators/collation/codepoint) is used.
XML allows elements to specify the xml:lang attribute to indicate the language associated with the content of such an element. This specification does not use xml:lang to identify the default collation, in part because collations should be determined by the user of the data, not (normally) the data itself, and because using xml:lang does not produce desired effects when the two strings to be compared have different xml:lang values or when a string is multilingual.
NOTE: Some data management environments allow collations to be associated with the definition of string items (that is, with the metadata that describes items whose type is string). While such association may be appropriate for use in environments in which data is held in a repository tightly bound to its descriptive metadata, it is not appropriate in the XML environment in which different documents being processed by a single query may be described by differing schemas.
NOTE: all collations support the capability of
deciding whether two strings are considered equal, and if not, which of the
strings should be regarded as preceding the other. For functions such as
fn:compare(), this is all that is required. For other functions, such as
fn:contains() and fn:starts-with(), the collation needs to support an
additional property: it must decompose the string into a sequence of units,
each unit consisting of one or more characters, such that two strings can be
compared by pairwise comparison of these units. The functions fn:contains(),
fn:starts-with(), and fn:ends-with() first use the collation to decompose the
string provided in the first argument into such a sequence of units, then
examine this sequence to determine if there is a subsequence that matches the
units obtained by decomposing the string supplied in the second argument.
Substrings might not be matched if they start or end in the middle of a unit.
For example, if a collation treats "Jaeger" and "Jäger" [ed note, second
character is "a with umlaut"] as equal, then it is probably treating "ae" as
one unit, which means that under this collation, the expression
contains("Jaeger", "eg")
is likely to return false.
It is possible to define collations that do not have this property, for example a collation that attempts to sort "ISO 8859" before "ISO 10646", or "January" before "February". Such collations may fail, or give unexpected results, when used with functions such as fn:contains().
[Issue 44: Collations: URIs and URI references or short names?]
| Function | Meaning | Source | 
|---|---|---|
| fn:compare | Compares two character strings; a collation may optionally be specified | XSLT 2.0, Req. 2.13 (Could) | 
[Issue 73: Is a "between" function needed?]
fn:compare($comparand1 as string?, $comparand2 as string?) as integer?| fn:compare( | $comparand1 |  as string?, | 
| $comparand2 |  as string?, | |
| $collationLiteral |  as anyURI) as integer? | 
Returns -1, 0, or 1, depending on whether the value of the
$comparand1 is respectively less than, equal to, or greater than
the value of $comparand2, according to the rules of the
collation that is used.
The collation used by the invocation of this function is determined according to the rules in 6.3 Equality and Comparison of Strings.
If the value of $comparand2 begins with a string that is
equal to the value of $comparand1 (according to the collation
that is used) and has additional characters following that beginning string,
then the result is -1.  If the value of $comparand1 begins with
a string that is equal to the value of $comparand2 (according to
the collation that is used) and has additional characters following that
beginning string, then the result is 1.
If either argument is the empty sequence, the result is the empty sequence.
This function backs up the "eq", "ne", "gt", "lt", "le" and "ge" operators on string values.
fn:compare('abc', 'abc')
    returns 0.
fn:compare('Strasse',
    'Straße') returns 0 if and only if the default collation
    includes provisions that equate "ss" and the (German) character "ß"
    ("sharp-s").  (Otherwise, the returned value depends on the semantics of
    the default collation.)
fn:compare('Strasse', 'Straße',
    anyURI('deutsch')) returns 0 if and only if the collation
    identified by the relative URI constructed from the string
    value "deutsch" includes provisions that equate "ss" and the (German)
    character "ß" ("sharp-s").  (Otherwise, the returned value depends on the
    semantics of that collation.)
fn:compare('Strassen',
    'Straße') returns 1 if and only if the default collation
    includes provisions that equate "ss" and the (German) character "ß"
    ("sharp-s").  (Since the value of $comparand1 has an
    additional character, an "n", following the string that is equal to
    "Straße", it is greater than the value of $comparand2.)
The following functions are defined on these string types. Several of these function use a collation. See 6.3 Equality and Comparison of Strings for a discussion of collations.
| Function | Meaning | Source | 
|---|---|---|
| fn:concat | Concatenates two or more character strings. | XPath 1.0 | 
| class="diff-add"fn:string-join | Accepts a sequence of strings and returns the strings concatenated together with an optional separator. | 
fn:starts-withfn:ends-withfn:containsfn:substringfn:string-lengthfn:substring-beforefn:substring-afterfn:normalize-spacefn:normalize-unicodefn:upper-casefn:lower-casefn:translatefn:string-padfn:matchesfn:replacefn:tokenizefn:escape-uri[Issue 21: What is the precise type returned by each function?]
Note also that when the above operators and functions are applied to
datatypes derived from string, they are guaranteeed to return
legal strings, but they may not return legal value for the particular subtype
to which they were applied.
fn:concat() as stringfn:concat($op1 as string?) as stringfn:concat($op1 as string?, $op2 as string?, ...) as stringAccepts zero or more strings as arguments. Returns the string that is the concatenation of the values of its arguments. The resulting string might not be normalized in any Unicode or W3C normalization. If called with no arguments, returns the zero-length string. If any of the arguments is the empty sequence, it is treated as the zero-length string.
The concat() function is specified to allow an arbitrary
number of string arguments that are concatenated together.  This capability
is retained for compatibility with [XPath 1.0] and is
the only function specified in this document that has that characteristic.
[Issue 144: Should the concat function accept sequences as arguments?]
fn:string-join($operand1 as string*, $operand2 as string*) as stringReturns a (possibly empty) string created by
concatenating the members of the $operand1 sequence
using $operand2 as a separator.  If the value of $operand2 is the
zero-length string, then the members of $operand1 are concatenated without a
separator.
If the value of $operand1 is the empty
sequence, the empty string is returned.
fn:starts-with($operand1 as string?, $operand2 as string?) as boolean?| fn:starts-with( | $operand1 |  as string?, | 
| $operand2 |  as string?, | |
| $collationLiteral |  as anyURI) as boolean? | 
Returns a boolean indicating whether or not the value of
$operand1 starts with a string that is equal to the value of
$operand2 according to the collation that is used.
If the value of $operand2 is the zero-length string, then the
function returns true.  If the value of $operand1
is the zero-length string and the value of $operand2 is not the
zero-length string, then the function returns false.
If the value of $operand1 or $operand2 is the
empty sequence, the empty sequence is returned.
The collation used by the invocation of this function is determined according to the rules in 6.3 Equality and Comparison of Strings.
fn:ends-with($operand1 as string?, $operand2 as string?) as boolean?| fn:ends-with( | $operand1 |  as string?, | 
| $operand2 |  as string?, | |
| $collationLiteral |  as anyURI) as boolean? | 
Returns a boolean indicating whether or not the value of
$operand1 ends with a string that is equal to the value of
$operand2 according to the specified collation.
If the value of $operand2 is the zero-length string, then the
function returns true.  If the value of $operand1
is the zero-length string and the value of $operand2 is not the
zero-length string, then the function returns false.
If the value of $operand1 or $operand2 is the
empty sequence, the empty sequence is returned.
The collation used by the invocation of this function is determined according to the rules in 6.3 Equality and Comparison of Strings.
fn:contains($operand1 as string?, $operand2 as string?) as boolean?| fn:contains( | $operand1 |  as string?, | 
| $operand2 |  as string?, | |
| $collationLiteral |  as anyURI) as boolean? | 
Returns a boolean indicating whether or not the value of
$operand1 contains (at the beginning, at the end, or anywhere
within) a string equal to the value of $operand2 according to
the collation that is used.
If the value of $operand2 is the zero-length string, then the
function returns true.  If the value of $operand1
is the zero-length string and the value of $operand2 is not the
zero-length string, then the function returns false.
If the value of $operand1 or $operand2 is the
empty sequence, the empty sequence is returned.
The collation used by the invocation of this function is determined according to the rules in 6.3 Equality and Comparison of Strings.
fn:substring($sourceString as string?, $startingLoc as double?) as string?| fn:substring( | $sourceString |  as string?, | 
| $startingLoc |  as double?, | |
| $length |  as double?) as string? | 
Returns the portion of the value of $sourceString beginning
at the position indicated by the value of $startingLoc and
continuing for the number of characters indicated by the value of
$length.   More specifically, returns the characters in
$sourceString whose position $p obeys:
fn:round($startingLoc)
<= $p < fn:round($startingLoc +
fn:round($length))
If $length is not specified, the substring identifies
characters to the end of $sourceString.
If $length is greater than the number of characters in the
value of $sourceString following $startingLoc, the
substring identifies characters to the end of $sourceString.
The first character of a string is located at position 1 (not position 0).
If the value of any of the three parameters is the empty sequence, the empty sequence is returned.
Note: The position and length given in the second and (optional) third argument relate to the number of XML characters in the string (or equivalently, the number of Unicode codepoints). Some implementations may represent a codepoint above xFFFF using two 16-bit values known as a surrogate pair. A surrogate pair counts as one character, not two.
fn:string-length($srcval as string?) as integer?Returns an integer equal to the length in characters of the value of
$srcval. If the value of $srcval is the empty
sequence, the empty sequence is returned.
Note: The value returned is the number of XML characters in the string (or equivalently, the number of Unicode codepoints). Some implementations may represent a codepoint above xFFFF using two 16-bit values known as a surrogate pair. A surrogate pair counts as one character, not two.
fn:substring-before($operand1 as string?, $operand2 as string?) as string?| fn:substring-before( | $operand1 |  as string?, | 
| $operand2 |  as string?, | |
| $collationLiteral |  as anyURI) as string? | 
Returns the substring of the value of $operand1 that precedes
in the value of $operand1 the first occurrence of a string that
is equal to the value of $operand2 according to the collation
that is used.
If the value of $operand2 is the zero-length string, then the
function returns the value of $operand1.
If the value of $operand1 does not contain a string that is
equal to the value of $operand2, then the function returns the
zero-length string.
If the value of  $operand1 or $operand2 is the
empty sequence, returns the empty sequence.
The collation used by the invocation of this function is determined according to the rules in 6.3 Equality and Comparison of Strings.
fn:substring-after($operand1 as string?, $operand2 as string?) as string?| fn:substring-after( | $operand1 |  as string?, | 
| $operand2 |  as string?, | |
| $collationLiteral |  as anyURI) as string? | 
Returns the substring of the value of $operand1 that follows
in the value of $operand1 the first occurrence of a string that
is equal to the value of $operand2 according to the collation
that is used.
If the value of $operand2 is the zero-length string, then the
function returns the value of $operand1.
If the value of $operand1 does not contain a string that is
equal to the value of $operand2, then the function returns the
zero-length string.
If the value of  $operand1 or $operand2 is the
empty sequence, returns the empty sequence.
The collation used by the invocation of this function is determined according to the rules in 6.3 Equality and Comparison of Strings.
fn:normalize-space($srcval as string?) as string?Returns the value of the string argument with whitespace normalized by
stripping leading and trailing whitespace and replacing sequences of more
than one whitespace character by a single space. If the value of 
$srcval is the empty sequence, returns the empty sequence.
fn:normalize-unicode($srcval as string?) as string?fn:normalize-unicode($srcval as string?, $normalizationForm as string) as string?Returns the value of $srcval normalized according to the
normalization criteria for a normalization form identified by the value of
$normalizationForm.  The effective value of the
$normalizationForm is computed by removing leading and trailing
blanks, if present, and converting to upper case:
If the $normalizationForm is absent, as in the first format
above, it shall be assumed to be "NFC"
If the effective value of $normalizationForm is "NFC",
    then the value returned by the function is the value of
    $srcval in Unicode Normalization Form C (NFC).
If the effective value of $normalizationForm is "NFD",
    then the value returned by the function is the value of
    $srcval in Unicode Normalization Form D (NFD).
If the effective value of $normalizationForm is "NFKC",
    then the value returned by the function is the value of
    $srcval in Unicode Normalization Form KC (NFKC).
If the effective value of $normalizationForm is "NFKD",
    then the value returned by the function is the value of
    $srcval in Unicode Normalization Form KD (NFKD).
If the effective value of $normalizationForm is "W3C",
    then the value returned by the function is the value of
    $srcval is the fully normalized form. See [Character Model for the World Wide Web 1.0].
If the effective value of $normalizationForm is the
    zero-length string then no normalization is performed and
    $srcval is returned.
Implementations may choose to support other normalization forms in addition to the normalization forms discussed above.
If the effective value of the $normalizationForm is other
than one of the values supported by the implementation, then an error is
raised ("Invalid normalization form").
If the value of  $srcval is the empty sequence, returns the
empty sequence.
fn:upper-case($srcval as string?) as string?Returns the value of $srcval after translating every
lower-case letter to its upper-case correspondent.  Every lower-case letter
that does not have an upper-case correspondent, and every character that is
not a lower-case letter, is included in the returned value in its original
form.
A "lower-case letter" is a character whose Unicode General Category class includes "Ll". The corresponding upper-case letter is determined using [Unicode Case Mappings].
If the value of  $srcval is the empty sequence, returns the
empty sequence.
fn:lower-case($srcval as string?) as string?Returns the value of $srcval after translating every
upper-case letter to its lower-case correspondent.  Every upper-case letter
that does not have a lower-case correspondent, and every character that is
not an upper-case letter, is included in the output in its original form.
An "upper-case letter" is a character whose Unicode General Category class includes "Lu". The corresponding lower-case letter is determined using [Unicode Case Mappings].
If the value of  $srcval is the empty sequence, returns the
empty sequence.
| fn:translate( | $srcval |  as string?, | 
| $mapString |  as string?, | |
| $transString |  as string?) as string? | 
Returns the value of $srcval modified so that every character
in the value of $srcval that occurs at some position N
in the value of $mapString has been replaced by the character
that occurs at position N in the value of
$transString.
Every character in the value of $srcval that does not appear
in the value of $mapString is unchanged.
Every character in the value of $srcval that appears at some
position M in the value of $mapString, where the value
of $transString is less than M characters in length, is
omitted from the returned value.
If the value of  $srcval or $mapString or
$transString is the empty sequence, returns the empty
sequence.
Note: This functions operates on XML characters in the string (or equivalently, Unicode codepoints). Some implementations may represent a codepoint above xFFFF using two 16-bit values known as a surrogate pair. A surrogate pair counts as one character, not two.
fn:string-pad($padString as string?, $padCount as integer?) as string?Returns a string consisting of $padCount copies of
$padString concatenated together. Returns the zero-length string
if $padCount is zero (0).
If the value of $padCount is less than zero (0), then an
error is raised ("Invalid string-pad count").
If the value of  $padString or $padCount is the
empty sequence, returns the empty sequence.
fn:matches($input as string?, $pattern as string?) as boolean?fn:matches($input as string?, $pattern as string?, $flags as string?) as boolean?The effect of calling the first version of this function (omitting the
argument $flags) is the same as the effect of calling the second
version with the $flags argument set to a zero-length string.
The function returns true if $input matches the regular
expression supplied as $pattern; otherwise, it returns false.
If any of the arguments is an empty sequence, the result is an empty sequence.
Unless the metacharacters ^ and $ are used as
anchors, the string is considered to match the pattern if any substring
matches the pattern. But if anchors are used, the anchors must match the
start/end of the string (in string mode), or the start/end of a line (in
multiline mode).
Note:
This is different from the behavior of patterns in XML Schema, where regular expressions are implicitly anchored.
An error is raised ("Invalid matches argument") if the value of
$pattern or of $flags does not conform to the
required syntax defined in section 6.4.16.1
Regular Expression Syntax.
The regular expression syntax used by these functions is defined in terms of the regular expression syntax specified in XML Schema (see [XML Schema Part 2: Datatypes]), which in turn is based on the established conventions of languages such as Perl. However, because XML Schema uses regular expressions only for validity checking, it has omitted some facilities that are widely-used with languages such as Perl, and this section therefore describes extensions to the XML Schema regular expressions syntax that re-instate these capabilities.
The regular expression syntax and semantics for these functions are identical to those defined in [XML Schema Part 2: Datatypes] [add reference] with the following additions:
Two modes are defined, string mode and multiline mode.
Two meta-characters, ^ and $ are added. In
    string mode, the metacharacter ^ matches the start of the
    entire string, while $ matches the end of the entire string.
    In multiline mode, ^ matches the start of any line (that is,
    the start of the entire string, and the position immediately after a
    newline character), while $ matches the end of any line
    (that is, the end of the entire string, and the position immediately
    before a newline character).
In string mode, the metacharacter . matches any
    character whatsoever. In multiline mode, the metacharacter .
    matches any character except a newline character.
Reluctant quantifiers are supported, specifically:
X?? matches X, once or not at all
X*? matches X, zero or more times
X+? matches X, one or more times
X{n}? matches X, exactly n times
X(n,}? matches X, at least n times
X{n,m}? matches X, at least n times, but not more
        than m times
The effect of these quantifiers is that the regular expression matches the shortest possible substring (consistent with the match as a whole succeeding). In the absence of these quantifiers, the regular expression matches the longest possible substring.
To achieve this, the production in XML Schema:
[4]    quantifier    ::=    [?*+] | ( '{' quantity '}'
    )
is changed to:
[4]    quantifier    ::=    ( [?*+] | ( '{' quantity '}' ) )
    '?'?
Sub-expressions (groups) within the regular expression are recognized. The regular expression syntax defined by XML Schema allows a regular expression to contain parenthesized sub-expressions, but attaches no special significance to them. Some functions described here allow access to the parts of the input string that matched a sub-expression (called captured substrings). The sub-expressions are numbered according to the position of the opening parenthesis in left-to-right order within the top-level regular expression: the first opening parenthesis identifies group 1, the second group 2, and so on. If a sub-expression matches more than one substring (because it is within a construct that allows repetition) then only the last substring that it matched will be captured.
Note:
Reluctant quantifiers have no effect on the results of the boolean
fn:matches function, since this is
only interested in discovering whether a match exists, and not where it
exists.
To enable conforming implementations to make use of existing regular expression library routines, this specification does not disallow extensions to the regular expression syntax described here. However, such extensions should only be provided if they conform to an existing recognized specification. All regular expressions that conform to the syntax described here must be accepted, and must implement the semantics described here.
[Issue 176: Should implementations be allowed to extend the regular expression syntax?]
All these functions provide an optional parameter, flags, to
set options for the interpretation of the regular expression. The parameter
is a string, in which individual letters are used to set options. The
presence of a letter within the string indicates that the option is on, its
absence indicates that the option is off. Letters may appear in any order and
may be repeated. If there are letters present that are not defined here, then
an error is raised ("Invalid regular expression syntax").
The following options are defined:
m: If present, the match operates in multiline mode.
    Otherwise, the match operates in string mode.
i: If present, the match operates in case-insensitive
    mode. Otherwise, the match operates in case-sensitive mode. The detailed
    rules for character matching in case-insensitive mode are
    implementation-dependent (and they may be locale-dependent).
fn:matches("abracadabra",
    "bra") returns true
fn:matches("abracadabra",
    "^a.*a$") returns true
fn:matches("abracadabra",
    "^bra") returns false
Given the source document:
<poem author="Wilhelm Busch"> Kaum hat dies der Hahn gesehen,
Fängt er auch schon an zu krähen: «Kikeriki! Kikikerikih!!» Tak, tak, tak! -
da kommen sie. </poem>
the following function calls produce the following results, with the
poem element as the context node:
fn:matches(.,
    "Kaum.*krähen") returns true
fn:matches(., "Kaum.*krähen",
    "m") returns false
fn:matches(.,
    "^Kaum.*gesehen,$", "m") returns true
fn:matches(.,
    "^Kaum.*gesehen,$") returns false
fn:matches(., "kiki",
    "i") returns true
Note:
Regular expression matching is defined on the basis of Unicode code-points, it takes no account of collations.
fn:replace($input as string?, $pattern as string?, $replacement as string?) as string?| fn:replace( | $input |  as string?, | 
| $pattern |  as string?, | |
| $replacement |  as string?, | |
| $flags |  as string?) as string? | 
The effect of calling the first version of this function (omitting the
argument $flags) is the same as the effect of calling the second
version with the $flags argument set to a zero-length string.
The function returns the string that is obtained by replacing all
non-overlapping substrings of $input that match the given
$pattern with an occurrence of the $replacement
string. The $flags argument is interpreted in the same way as
for the fn:matches function.
If any of the arguments is an empty sequence, the result is an empty sequence.
Within the $replacement string, the variables $1 to
$9 may be used to refer to the substring captured by each of the
first nine parenthesized sub-expressions in the regular expression. A literal
$ symbol must be written as \$.
An error is raised ("Invalid replace argument") if the value of
$pattern or $flags is invalid according to the
rules described in section 6.4.16.1 Regular
Expression Syntax.
An error is raised ("Pattern matches zero-length string") if the pattern matches a zero-length string.
fn:tokenize($input as string?, $pattern as string?) as string*fn:tokenize($input as string?, $pattern as string?, $flags as string?) as string*The effect of calling the first version of this function (omitting the
argument $flags) is the same as the effect of calling the second
version with the $flags argument set to a zero-length string.
This function breaks the $input string into a sequence of
strings, treating any substring that matches $pattern as a
separator. The separators themselves are not returned. The
$flags argument is interpreted in the same way as for the fn:matches function.
If any of the arguments is an empty sequence, the result is an empty sequence.
If a separator occurs at the start of the $input string, the
result sequence will start with a zero-length string. Zero-length strings
will also occur in the result sequence if a separator occurs at the end of
the $input string, or if two adjacent substrings match the
supplied $pattern.
fn:escape-uri($uri-part as string, $escape-reserved as boolean) as stringThis function applies the URI escaping rules defined in section 2 of [RFC 2396] as amended by
[RFC 2732] to the
string supplied as $uri-part, which typically represents all or
part of a URI. The effect of the function is to replace any special character
in the string by an escape sequence of the form %xx%yy..., where xxyy... is
the hexadecimal representation of the octets used to represent the character
in UTF-8.
The set of characters that are escaped depends on the setting of the boolean argument $escape-reserved.
If $escape-reserved is true, all characters are escaped other
than lower case letters a-z, upper case letters A-Z, digits 0-9, and the
characters referred to in [RFC 2396] as "marks":
specifically, "-" | "_" | "." | "!" | "~" | "*" | "'" | "(" | ")". The "%"
character itself is escaped only if it is not followed by two hexadecimal
digits (that is, 0-9, a-f, and A-F).
If $escape-reserved is false, the behavior differs in that
characters referred to in [RFC 2396] and [RFC
2732] as reserved characters, together with
the '#' character, are not escaped. These characters are ";" | "/" |
"?" | ":" | "@" | "&" | "=" | "+" | "$" | "," |
"#", "[", "]".
[RFC 2396] does not define whether escaped URIs should use lower case or upper case for hexadecimal digits. To ensure that escaped URIs can be compared using string comparison functions, this function must always use the upper-case letters A-F.
Generally, $escape-reserved should be set to true when
escaping a string that is to form a single part of a URI, and to false when
escaping an entire URI or URI reference.
fn:escape-uri
    ("gopher://spinaltap.micro.umn.edu/00/Weather/California/Los%20Angeles#ocean",
    true()) returns
    "gopher%3A%2F%2Fspinaltap.micro.umn.edu%2F00%2FWeather%2FCalifornia%2FLos%20Angeles%23ocean"
fn:escape-uri
    ("gopher://spinaltap.micro.umn.edu/00/Weather/California/Los%20Angeles#ocean",
    false()) returns "gopher://spinaltap.micro.umn.edu/00/Weather/California/Los%20Angeles#ocean"
This section discusses operators on the [XML Schema Part 2: Datatypes] boolean datatype.
The following constructor functions are defined on the boolean type.
| Function | Meaning | Source | 
|---|---|---|
| fn:true | boolean | XPath 1.0 | 
| fn:false | boolean | XPath 1.0 | 
The following functions are defined on boolean values to back up operators defined in [XQuery 1.0: An XML Query Language] and [XPath 2.0]:
| Operator | Meaning | Source | 
|---|---|---|
| op:boolean-equal | Equality comparison | XPath 1.0 | 
| op:boolean-less-than | A less-than operator for boolean vales: falseis less-thantrue. | XPath 1.0 | 
| op:boolean-greater-than | A greater-than operator for boolean vales: trueis greater-thanfalse. | XPath 1.0 | 
op:boolean-equal($value1 as boolean, $value2 as boolean) as booleanThe arguments and return type are all boolean. The result is
true if both arguments are true or if both
arguments are false.  The result is false if one of
the arguments is true and the other argument is
false.
This function backs up the "eq" operator on boolean values.
The following functions are defined on boolean values:
| Function | Meaning | Source | 
|---|---|---|
| fn:not | Inverts the boolean value of the argument. | XPath 1.0 | 
This section discusses operations on the [XML Schema Part 2: Datatypes] duration, date and time types. In addition, it discusses operations on two subtypes of the duration datatype that are defined in 8.2 Two Totally Ordered Subtypes of Duration.
The functions described in this section follow the principle of locale-independent storage for these datatypes that originated with [XML Schema Part 2: Datatypes]. Thus, a single calendar (Gregorian) and a single timezone (UTC) is chosen to represent date and time values. Applications and other processing systems are free to present this information in locale-specific representations.
[Issue 136: Should we allow casting a date/time from one timezone to another?]
The operators described in this section are defined on the following duration date and time types:
duration
dateTime
date
time
gYearMonth
gYear
gMonthDay
gMonth
gDay
In addition, they are defined on the 8.2 Two Totally Ordered Subtypes of Duration:
yearMonthDuration
dayTimeDuration
CONFORMANCE NOTE
For a number of the above datatypes [XML Schema Part 2: Datatypes] extends the basic [ISO 8601] lexical representations, such as YYYY-MM-DDThh:mm:ss.s for dateTime, by allowing more than four digits to represent the year field -- no maximum is specified -- and an unlimited number of digits for fractional seconds.
For this specification, all minimally conforming processors must support year values with a minimum of 4 digits (i.e., YYYY) and a minimum fractional second precision of 100 nanoseconds or seven digits (i.e. s.sssssss). However, conforming processors may set larger application-defined limits on the maximum number of digits they support in these two situations, in which case those application-defined maximum numbers must be clearly documented.
[Issue 159: For fractional seconds precision use 6 digits to match SQL TIMESTAMP.]
These two totally ordered subtypes of duration are defined in this
specification using the mechanisms described in [XML
Schema Part 2: Datatypes] for defining user-defined types. They are
available in the namespace http://www.w3.org/2002/11/xquery-functions.
The W3C XML Query Working Group has requested the W3C XML Schema Working
Group that these two subtypes of duration be included in the built-in
datatypes described in [XML Schema Part 2: Datatypes].
 If the W3C XML Schema Working Group agrees to this request, these two
datatypes will be removed from the above name space and moved into the XML
Schema namespace http://www.w3.org/2001/XMLSchema.
[Definition:] yearMonthDuration is derived from duration by restricting its lexical representation to contain only the year and month components. The value space of yearMonthDuration is the set of integer month values. The year and month components of yearMonthDuration correspond to the Gregorian year and month components defined in section 5.5.3.2 of [ISO 8601], respectively.
yearMonthDuration is derived from duration as follows:
<simpleType name='yearMonthDuration'>
    <restriction base='duration'>
        <xsd:pattern value="[\-]?P[0-9]+(Y([0-9]+M)?|M)"/>
    </restriction>
</simpleType>
The lexical representation for yearMonthDuration is the [ISO 8601] reduced format PnYnM, where nY represents the number of years and nM the number of months. The values of the years and months components are not restricted but allow an arbitrary unsigned integer.
An optional preceding minus sign ('-') is allowed to indicate a negative duration. If the sign is omitted a positive duration is indicated. To indicate a yearMonthDuration of 1 year, 2 months, one would write: P1Y2M. One could also indicate a yearMonthDuration of minus 13 months as: -P13M.
Reduced precision and truncated representations of this format are allowed provided they conform to the following:
If the number of years or months in any expression equals zero (0), the number and its corresponding designator may be omitted. However, at least one number and its designator must be present. For example, P1347Y and P1347M are all allowed; P-1347M is not allowed although -P1347M is allowed. P1Y2MT is not allowed.
The value of a yearMonthDuration lexical form is obtained by multiplying the value of the year component by 12 and adding the value of the month component. The value is positive or negative depending on the preceding sign.
The canonical representation of yearMonthDuration restricts the value of the months component to integer values between 0 and 11, both inclusive. To convert from a non-canonical representation to the canonical representation, the lexical representation is first converted to a value in integer number of months as defined above. This value is then divided by 12 to obtain the value of the years component of the canonical representation. The remaining number of months is the value of the months component of the canonical representation. If a component has the value zero (0) then the number and the designator for that component must be omitted. If the value is zero (0) months, the canonical form is "P0M".
[Definition:] dayTimeDuration is derived from duration by restricting its lexical representation to contain only the day, hour, minute, and second components. The value space of dayTimeDuration is the set of fractional second values. The components of dayTimeDuration correspond to the day, hour, minute and second components defined in Section 5.5.3.2 of [ISO 8601], respectively. dayTimeDuration is derived from duration as follows:
<simpleType name='dayTimeDuration'>
    <restriction base='duration'>
              <xsd:pattern value="[\-]?P([0-9]+D(T([0-9]+(H([0-9]+(M([0-9]+(\.[0-9]*)?S
                      |\.[0-9]+S)?|(\.[0-9]*)?S)|(\.[0-9]*)?S)?|M([0-9]+
                      (\.[0-9]*)?S|\.[0-9]+S)?|(\.[0-9]*)?S)|\.[0-9]+S))?
                      |T([0-9]+(H([0-9]+(M([0-9]+(\.[0-9]*)?S|\.[0-9]+S)?
                      |(\.[0-9]*)?S)|(\.[0-9]*)?S)?|M([0-9]+(\.[0-9]*)?S|\.[0-9]+S)?
                      |(\.[0-9]*)?S)|\.[0-9]+S))"/>
    </restriction>
</simpleType>
The lexical representation for dayTimeDuration is the [ISO 8601] truncated format PnDTnHnMnS, where nD represents the number of days, T is the date/time separator, nH the number of hours, nM the number of minutes and nS the number of seconds.
The values of the days, hours and minutes components are not restricted but allow an arbitrary unsigned integer. Similarly, the value of the seconds component allows an arbitrary unsigned decimal number. An optional minus sign ('-') is allowed to precede the 'P', indicating a negative duration. If the sign is omitted, the duration is positive. See also [ISO 8601] Date and Time Formats.
For example, to indicate a duration of 3 days, 10 hours, and 30 minutes, one would write: P3DT10H30M. One could also indicate a duration of minus 120 days as: -P120D. Reduced precision and truncated representations of this format are allowed, provided they conform to the following:
If the number of days, hours, minutes, or seconds in any expression equals zero (0), the number and its corresponding designator may be omitted. However, at least one number and its designator must be present.
The seconds part may have a decimal fraction.
The designator 'T' must be absent if and only if all of the time items are absent. The designator 'P' must always be present.
For example, P13D, PT47H and P3DT2H are all allowed. P-134D is not allowed (invalid location of minus sign), although -P134D is allowed.
The value of a dayTimeDuration lexical form in fractional seconds is obtained by converting the day, hour minutes and seconds value to fractional seconds using the conversion rules: 24 hours = 1 day, 60 minutes = 1 hour and 60 seconds = 1 minute.
The canonical representation of dayTimeDuration restricts the value of the hours component to integer values between 0 and 23, both inclusive; the value of the minutes component to integer values between 0 and 59; both inclusive; and the value of the seconds component to decimal valued from 0.0 to 60.999... (see [XML Schema Part 2: Datatypes], Appendix D). The value can be greater than 60 seconds to accomodate occasional leap seconds used to keep human time synchronized with the rotation of the planet.
To convert from a non-canonical representation to the canonical representation, the value of the lexical form in fractional seconds is first calculated in the manner described above. The value of the days component in the canonical form is then calculated by dividing the value by 24*60*60. The remainder is in fractional seconds. The value of the hours component in the canonical form is calculated by dividing this remainder by 60*60. The remainder is again in fractional seconds. The value of the minutes component in the canonical form is calculated by dividing this remainder by 60. The remainder in fractional seconds is the value of the seconds component in the canonical form. If a component has the value zero (0) then the number and the designator for that component must be omitted. If all the components of the lexical form are zero (0), the canonical form is PT0S.
| Operator | Meaning | 
|---|---|
| op:duration-equal | Equality comparison on duration values | 
| op:yearMonthDuration-equal | Equality comparison on yearMonthDuration values | 
| op:yearMonthDuration-less-than | Less-than comparison on yearMonthDuration values | 
| op:yearMonthDuration-greater-than | Greater-than comparison on yearMonthDuration values | 
| op:dayTimeDuration-equal | Equality comparison on dayTimeDuration values | 
| op:dayTimeDuration-less-than | Less-than comparison on dayTimeDuration values | 
| op:dayTimeDuration-greater-than | Greater-than comparison on dayTimeDuration values | 
| op:dateTime-equal | Equality comparison on dateTime values | 
| op:dateTime-less-than | Less-than comparison on dateTime values | 
| op:dateTime-greater-than | Greater-than comparison on dateTime values | 
| op:date-equal | Equality comparison on date values | 
| op:date-less-than | Less-than comparison on date values | 
| op:date-greater-than | Greater-than comparison on date values | 
| op:time-equal | Equality comparison on time values | 
| op:time-less-than | Less-than comparison on time values | 
| op:time-greater-than | Greater-than comparison on time values | 
| op:gYearMonth-equal | Equality comparison on gYearMonth values | 
| op:gYear-equal | Equality comparison on gYear values | 
| op:gMonthDay-equal | Equality comparison on gMonthDay values | 
| op:gMonth-equal | Equality comparison on gMonth values | 
| op:gDay-equal | Equality comparison on gDay values | 
The following comparison operators are defined on date, time and duration values. Each operator takes two operands of the same type and returns a boolean result. As discussed in [XML Schema Part 2: Datatypes], the order relation on the duration and the date and time datatypes is not a total order but, rather, a partial order. For this reason, only the equality function is defined on duration. A full complement of comparison and arithmetic functions are defined on the two subtypes of duration described in 8.2 Two Totally Ordered Subtypes of Duration.
If either operand to a comparison function on dateTime, date or time values does not have a explicit timezone then, for the purpose of the operation, an implicit timezone, provided by the static context, is assumed to be present as part of the value. This creates a total order for all dateTime, date and time values.
op:duration-equal($operand1 as duration, $operand2 as duration) as booleanReturns true if and only if each component of
$operand1 is exactly equal to the
corresponding component of $operand2. Returns false
otherwise.  If a component is missing it should be
interpreted as have a 0 value.
This function backs up the "eq" and "ne" operators on duration values.
| op:yearMonthDuration-equal( | $operand1 |  as yearMonthDuration, | 
| $operand2 |  as yearMonthDuration) as boolean | 
Returns true if and only if $operand1 is exactly equal to
$operand2. Returns false otherwise.
This function backs up the "eq" and "ne" operators on yearMonthDuration values.
| op:yearMonthDuration-less-than( | $operand1 |  as yearMonthDuration, | 
| $operand2 |  as yearMonthDuration) as boolean | 
Returns true if and only if $operand1 is less than
$operand2. Returns false otherwise.
This function backs up the "lt" and "ge" operators on yearMonthDuration values.
| op:yearMonthDuration-greater-than( | $operand1 |  as yearMonthDuration, | 
| $operand2 |  as yearMonthDuration) as boolean | 
Returns true if and only if $operand1 is greater than
$operand2. Returns false otherwise.
This function backs up the "gt" and "le" operators on yearMonthDuration values.
| op:dayTimeDuration-equal( | $operand1 |  as dayTimeDuration, | 
| $operand2 |  as dayTimeDuration) as boolean | 
Returns true if and only if $operand1 is exactly equal to
$operand2. Returns false otherwise.
This function backs up the "eq" and "ne" operators on dayTimeDuration values.
| op:dayTimeDuration-less-than( | $operand1 |  as dayTimeDuration, | 
| $operand2 |  as dayTimeDuration) as boolean | 
Returns true if and only if $operand1 is less than
$operand2. Returns false otherwise.
This function backs up the "lt" and "ge" operators on dayTimeDuration values.
| op:dayTimeDuration-greater-than( | $operand1 |  as dayTimeDuration, | 
| $operand2 |  as dayTimeDuration) as boolean | 
Returns true if and only if $operand1 is greater than
$operand2. Returns false otherwise.
This function backs up the "gt" and "le" operators on dayTimeDuration values.
op:dateTime-equal($operand1 as dateTime, $operand2 as dateTime) as booleanReturns true if and only if $operand1 is exactly equal to
$operand2. Returns false otherwise.
If either $operand1 or $operand2 is a value that does not contain a timezone, then for the purposes of this operation the implicit timezone is considered to be present in the value. The ordering of the dateTime data type is defined by section 3.2.7.3, "Order relation on dateTime", of [XML Schema Part 2: Datatypes].
This function backs up the "eq" and "ne" operators on dateTime values.
Assume that the static context provides an implicit timezone value of -5:00.
op:dateTime-equal(xs:dateTime("2002-04-02T12:00"),
    xs:dateTime("2002-04-02T17:00Z")) returns true.
op:dateTime-equal(xs:dateTime("2002-04-02T12:00"),
    xs:dateTime("2002-04-02T17:00")) returns false.
op:dateTime-equal(xs:dateTime("2002-04-02T12:00"),
    xs:dateTime("2002-04-02T12:00")) returns true.
op:dateTime-less-than($operand1 as dateTime, $operand2 as dateTime) as booleanReturns true if and only if $operand1 is less than
$operand2. Returns false otherwise.
If either $operand1 or $operand2 is a value that does not contain a timezone, then for the purposes of this operation the Implicit Timezone is considered to be present in the value. The ordering of the dateTime data type is defined by section 3.2.7.3, "Order relation on dateTime", of [XML Schema Part 2: Datatypes].
This function backs up the "lt" and "ge" operators on dateTime values.
| op:dateTime-greater-than( | $operand1 |  as dateTime, | 
| $operand2 |  as dateTime) as boolean | 
Returns true if and only if $operand1 is greater than
$operand2. Returns false otherwise.
If either $operand1 or $operand2 is a value that does not contain a timezone, then for the purposes of this operation the Implicit Timezone is considered to be present in the value. The ordering of the dateTime data type is defined by section 3.2.7.3, "Order relation on dateTime", of [XML Schema Part 2: Datatypes].
This function backs up the "gt" and "le" operators on dateTime values.
op:date-equal($operand1 as date, $operand2 as date) as booleanReturns true if and only if $operand1 is exactly equal to
$operand2. Returns false otherwise.
If either $operand1 or $operand2 is a value that does not contain a timezone, then for the purposes of this operation the Implicit Timezone is considered to be present in the value. The ordering of the date data type is defined by section 3.2.7.3, "Order relation on dateTime", and section 3.2.9, "date", of [XML Schema Part 2: Datatypes].
This function backs up the "eq" and "ne" operators on date values.
op:date-less-than($operand1 as date, $operand2 as date) as booleanReturns true if and only if $operand1 is less than
$operand2. Returns false otherwise.
If either $operand1 or $operand2 is a value that does not contain a timezone, then for the purposes of this operation the Implicit Timezone is considered to be present in the value. The ordering of the date data type is defined by section 3.2.7.3, "Order relation on dateTime", and section 3.2.9, "date", of [XML Schema Part 2: Datatypes].
This function backs up the "lt" and "ge" operators on date values.
op:date-greater-than($operand1 as date, $operand2 as date) as booleanReturns true if and only if $operand1 is greater than
$operand2. Returns false otherwise.
If either $operand1 or $operand2 is a value that does not contain a timezone, then for the purposes of this operation the Implicit Timezone is considered to be present in the value. The ordering of the date data type is defined by section 3.2.7.3, "Order relation on dateTime", and section 3.2.9, "date", of [XML Schema Part 2: Datatypes].
This function backs up the "gt" and "le" operators on date values.
op:time-equal($operand1 as time, $operand2 as time) as booleanReturns true if and only if $operand1 is exactly equal to
$operand2. Returns false otherwise.
If either $operand1 or $operand2 is a value that does not contain a timezone, then for the purposes of this operation the Implicit Timezone is considered to be present in the value. The ordering of the date data type is defined by section 3.2.7.3, "Order relation on dateTime", and section 3.2.8, "time", of [XML Schema Part 2: Datatypes].
This function backs up the "eq" and "ne" operators on time values.
op:time-less-than($operand1 as time, $operand2 as time) as booleanReturns true if and only if $operand1 is less than
$operand2. Returns false otherwise.
If either $operand1 or $operand2 is a value that does not contain a timezone, then for the purposes of this operation the Implicit Timezone is considered to be present in the value. The ordering of the date data type is defined by section 3.2.7.3, "Order relation on dateTime", and section 3.2.8, "time", of [XML Schema Part 2: Datatypes].
This function backs up the "lt" and "ge" operators on time values.
op:time-greater-than($operand1 as dateTime, $operand2 as dateTime) as booleanReturns true if and only if $operand1 is greater than
$operand2. Returns false otherwise.
If either $operand1 or $operand2 is a value that does not contain a timezone, then for the purposes of this operation the Implicit Timezone is considered to be present in the value. The ordering of the date data type is defined by section 3.2.7.3, "Order relation on dateTime", and section 3.2.8, "time", of [XML Schema Part 2: Datatypes].
This function backs up the "gt" and "le" operators on time values.
| op:gYearMonth-equal( | $operand1 |  as gYearMonth, | 
| $operand2 |  as gYearMonth) as boolean | 
Returns true if and only if $operand1 is exactly equal to
$operand2. Returns false otherwise.
This function backs up the "eq" and "ne" operators on gYearMonth values.
op:gYear-equal($operand1 as gYear, $operand2 as gYear) as booleanReturns true if and only if $operand1 is exactly equal to
$operand2. Returns false otherwise.
This function backs up the "eq" and "ne" operators on gYear values.
op:gMonthDay-equal($operand1 as gMonthDay, $operand2 as gMonthDay) as booleanReturns true if and only if $operand1 is exactly equal to
$operand2. Returns false otherwise.
This function backs up the "eq" and "ne" operators on gMonthDay values.
The date and time datatypes may be considered to be composite datatypes in that they contain distinct components. The extraction functions specified below extract one component from a date or time value.
| Function | Meaning | 
|---|---|
| fn:get-years-from-yearMonthDuration | Returns the year component of a yearMonthDuration value. | 
| fn:get-months-from-yearMonthDuration | Returns the months component of a yearMonthDuration value. | 
| fn:get-days-from-dayTimeDuration | Returns the days component of a dayTimeDuration value. | 
| fn:get-hours-from-dayTimeDuration | Returns the hours component of a dayTimeDuration value. | 
| fn:get-minutes-from-dayTimeDuration | Returns the minutes component of a dayTimeDuration value. | 
| fn:get-seconds-from-dayTimeDuration | Returns the seconds component of a dayTimeDuration value. | 
| fn:get-year-from-dateTime | Returns the year from a dateTime value. | 
| fn:get-month-from-dateTime | Returns the month from a dateTime value. | 
| fn:get-day-from-dateTime | Returns the day from a dateTime value. | 
| fn:get-hours-from-dateTime | Returns the hours from a dateTime value. | 
| fn:get-minutes-from-dateTime | Returns the minutes from a dateTime value. | 
| fn:get-seconds-from-dateTime | Returns the seconds from a dateTime value. | 
| fn:get-timezone-from-dateTime | Returns the timezone from a dateTime value. | 
| fn:get-year-from-date | Returns the year from a date value. | 
| fn:get-month-from-date | Returns the month from a date value. | 
| fn:get-day-from-date | Returns the day from a date value. | 
| fn:get-timezone-from-date | Returns the timezone from a date value. | 
| fn:get-hours-from-time | Returns the hours from a time value. | 
| fn:get-minutes-from-time | Returns the minutes from a time value. | 
| fn:get-seconds-from-time | Returns the seconds from a time value. | 
| fn:get-timezone-from-time | Returns the timezone from a time value. | 
fn:get-years-from-yearMonthDuration($srcval as yearMonthDuration?) as integer?Returns an integer representing the years component in the value of
$srcval. The result may be negative.
If $srcval is the empty sequence, returns the empty
sequence.
| fn:get-months-from-yearMonthDuration( | $srcval |  as yearMonthDuration?) as integer? | 
Returns an integer representing the months component in the value of
$srcval. The result may be negative.
If $srcval is the empty sequence, returns the empty
sequence.
fn:get-days-from-dayTimeDuration($srcval as dayTimeDuration?) as integer?Returns an integer representing the days component in the value of
$srcval. The result may be negative.
If $srcval is the empty sequence, returns the empty
sequence.
fn:get-hours-from-dayTimeDuration($srcval as dayTimeDuration?) as integer?Returns an integer representing the hours component in the value of
$srcval. The result may be negative.
If $srcval is the empty sequence, returns the empty
sequence.
fn:get-minutes-from-dayTimeDuration($srcval as dayTimeDuration?) as integer?Returns an integer representing the minutes component in the value of
$srcval. The result may be negative.
If $srcval is the empty sequence, returns the empty
sequence.
fn:get-seconds-from-dayTimeDuration($srcval as dayTimeDuration?) as decimal?Returns a decimal number representing the seconds component in the value
of $srcval. The result may be negative.
If $srcval is the empty sequence, returns the empty
sequence.
fn:get-year-from-dateTime($srcval as dateTime?) as integer?Returns an integer representing the year component in the value of
$srcval. The result may be negative.
If $srcval is the empty sequence, returns the empty
sequence.
fn:get-month-from-dateTime($srcval as dateTime?) as integer?Returns an integer between 1 and 12, both
inclusive, representing the month component in the value of
$srcval. If $srcval is the empty sequence, returns
the empty sequence.
fn:get-day-from-dateTime($srcval as dateTime?) as integer?Returns an integer between 1 and 31, both
inclusive, representing the day component in the value of
$srcval. If $srcval is the empty sequence, returns
the empty sequence.
fn:get-hours-from-dateTime($srcval as dateTime?) as integer?Returns an integer representing the hours value identified in the value of
$srcval.  The hours value ranges from 0 to 23, both inclusive. If $srcval is the empty
sequence, returns the empty sequence.
fn:get-minutes-from-dateTime($srcval as dateTime?) as integer?Returns an integer value representing the minute identified in the value
of $srcval.  The minute value ranges from 0 to 59, both inclusive. If $srcval is the empty
sequence, returns the empty sequence.
fn:get-seconds-from-dateTime($srcval as dateTime?) as decimal?Returns a decimal value representing the seconds and fractional seconds
identified in the value of $srcval.  The value ranges from 0 to
60.999..., inclusive.  The number of digits of fractional seconds precision
is determined by the relevant facet of the argument.  Note that the value can
be greater than 60 seconds to accomodate occasional
leap seconds used to keep human time synchronized with the rotation of
the planet.  If $srcval is the empty sequence, returns the empty
sequence.
fn:get-timezone-from-dateTime($srcval as dateTime?) as string?Returns a string representing the timezone component of
$srcval.  The result is a dayTimeDuration
that indicates deviation from UTC whose value may range from +14:00 to
-12:00 hours, both inclusive.  If $srcval does not
contain a timezone, the result is the empty sequence.  If
$srcval is the empty sequence, returns the empty sequence.
fn:get-year-from-date($srcval as date?) as integer?Returns an integer representing the year in the value of
$srcval.  The value may be negative.
If $srcval is the empty sequence, returns the empty
sequence.
fn:get-month-from-date($srcval as date?) as integer?Returns an integer between 1 and 12, both
inclusive, representing the month component in the value of
$srcval. If $srcval is the empty sequence, returns
the empty sequence.
fn:get-day-from-date($srcval as date?) as integer?Returns an integer between 1 and 31, both
inclusive, representing the day component in the value of
$srcval. If $srcval is the empty sequence, returns
the empty sequence.
fn:get-timezone-from-date($srcval as date?) as string?Returns a string representing the timezone component of
$srcval.  The result is a dayTimeDuration
that indicates deviation from UTC whose value may range from +14:00 to
-12:00 hours, both inclusive.  If $srcval does not
contain a timezone, the result is the empty sequence.  If
$srcval is the empty sequence, returns the empty sequence.
fn:get-hours-from-time($srcval as time?) as integer?Returns an integer representing the hours value identified in the value of
$srcval.  The hours value ranges from 0 to 23,  both inclusive. If $srcval is the empty
sequence, returns the empty sequence.
fn:get-minutes-from-time($srcval as time?) as integer?Returns an integer value representing the minute identified in the value
of $srcval.  The minute value ranges from 0 to 59, both inclusive.  If $srcval is the empty
sequence, returns the empty sequence.
fn:get-seconds-from-time($srcval as time?) as decimal?Returns a decimal value representing the seconds and fractional seconds
identified in the value of $srcval.  The value ranges from 0 to
60.999..., inclusive.  The number of digits of fractional seconds precision
is determined by the relevant facet of the argument.  Note that the value can
be greater than 60 seconds to accomodate occassional leap seconds used to
keep human time synchronized with the rotation of the planet.  If
$srcval is the empty sequence, returns the empty sequence.
fn:get-timezone-from-time($srcval as time?) as string?Returns a dayTimeDuration representing the
timezone component of $srcval.  The result is a dayTimeDuration that indicates
deviation from UTC whose value may range from
+14:00 to -12:00 hours, both inclusive. If $srcval does
not contain a timezone, the result is the empty sequence.  If
$srcval is the empty sequence, returns the empty sequence.
| Function | Meaning | 
|---|---|
| op:add-yearMonthDurations | Adds two yearMonthDurations. Returns a yearMonthDuration. | 
| op:subtract-yearMonthDurations | Subtracts one yearMonthDuration from another. Returns a yearMonthDuration. | 
| op:multiply-yearMonthDuration | Multiply a yearMonthDuration by a decimal. Returns a yearMonthDuration. | 
| op:divide-yearMonthDuration | Divide a yearMonthDuration by a decimal. Returns a yearMonthDuration. | 
| op:add-dayTimeDurations | Adds two dayTimeDurations. Returns a dayTimeDuration. | 
| op:subtract-dayTimeDurations | Subtracts one dayTimeDuration from another. Returns a dayTimeDuration. | 
| op:multiply-dayTimeDuration | Multiply a dayTimeDuration by a decimal. Returns a dayTimeDuration. | 
| op:divide-dayTimeDuration | Divide a dayTimeDuration by a decimal. Returns a dayTimeDuration. | 
| op:add-yearMonthDurations( | $srcval1 |  as yearMonthDuration, | 
| $srcval2 |  as yearMonthDuration) as yearMonthDuration | 
Returns the result of adding the value of $srcval1 to the
value of $srcval2.  Backs up the "+" operator on
yearMonthDuration values.
| op:subtract-yearMonthDurations( | $srcval1 |  as yearMonthDuration, | 
| $srcval2 |  as yearMonthDuration) as yearMonthDuration | 
Returns the result of subtracting the value of $srcval2 from
the value of $srcval2.  Backs up the "-" operator on
yearMonthDuration values.
| op:multiply-yearMonthDuration( | $srcval1 |  as yearMonthDuration, | 
| $srcval2 |  as decimal) as yearMonthDuration | 
Returns the result of multiplying the value of $srcval1 by
$srcval2.  The result is rounded to the nearest month.  For a
value v, 0 <= v < 0.5  rounds to 0; 0.5 <=
v < 1.0 rounds to 1.
Backs up the "*" operator on yearMonthDuration values.
| op:divide-yearMonthDuration( | $srcval1 |  as yearMonthDuration, | 
| $srcval2 |  as decimal) as yearMonthDuration | 
Returns the result of dividing the value of $srcval1 by
$srcval2.  The result is rounded to the nearest month.  For a
value v, 0 <= v < 0.5  rounds to 0; 0.5 <=
v < 1.0 rounds to 1.
Backs up the "div" operator on yearMonthDuration values.
| op:add-dayTimeDurations( | $srcval1 |  as dayTimeDuration, | 
| $srcval2 |  as dayTimeDuration) as dayTimeDuration | 
Returns the result of adding the value of $srcval1 to the
value of $srcval2.  Backs up the "+" operator on dayTimeDuration
values.
| op:subtract-dayTimeDurations( | $srcval1 |  as dayTimeDuration, | 
| $srcval2 |  as dayTimeDuration) as dayTimeDuration | 
Returns the result of subtracting the value of $srcval2 from
the value of $srcval2.  Backs up the "-" operator on
dayTimeDuration values.
| op:multiply-dayTimeDuration( | $srcval1 |  as dayTimeDuration, | 
| $srcval2 |  as decimal) as dayTimeDuration | 
Returns the result of multiplying the value of $srcval1 by
$srcval2.  Backs up the "*" operator on dayTimeDuration
values.
| Function | Meaning | 
|---|---|
| class="diff-add"fn:add-timezone-to-dateTime | Returns a dateTime with a timezone. | 
fn:remove-timezone-from-dateTimefn:add-timezone-to-datefn:add-timezone-to-timefn:remove-timezone-from-timefn:add-timezone-to-dateTime($srcval as dateTime) as dateTime| fn:add-timezone-to-dateTime( | $srcval |  as dateTime, | 
| $timezone |  as dayTimeDuration) as dateTime | 
Returns a dateTime with a timezone.
If $srcval is a dateTime value without a timezone, then let $srcn be
$srcval. Otherwise, let $srcn be the value of fn:remove-timezone-from-dateTime
($srcval). If $timezone is not specified, then $timezone
will be the value of the implicit timezone for the query. The value of
$srcn - $timezone is returned with a timezone of Z.
Assume the static context provides an implicit timezone of -5:00.
let $tz := fn:dayTimeDuration("-PT10H")
fn:add-timezone-to-dateTime(xs:dateTime("2002-03-07T10:00:00"))
    returns 2002-03-07T15:00:00Z
fn:add-timezone-to-dateTime(xs:dateTime("2002-03-07T10:00:00-07:00"))
    returns 2002-03-07T17:00:00Z
fn:add-timezone-to-dateTime(xs:dateTime("2002-03-07T10:00:00"),
    $tz) returns 2002-03-07T20:00:00Z
fn:add-timezone-to-dateTime(xs:dateTime("2002-03-07T10:00:00-07:00"),
    $tz) returns 2002-03-07T22:00:00Z
fn:remove-timezone-from-dateTime($srcval as dateTime) as dateTime| fn:remove-timezone-from-dateTime( | $srcval |  as dateTime, | 
| $timezone |  as dayTimeDuration) as dateTime | 
Returns a dateTime without a timezone.
If $srcval has a timezone, then let $srcn be $srcval. Otherwise, let $srcn
be the value of fn:add-timezone-to-dateTime ($srcval). If
$timezone is not specified, then $timezone will be the value of the implicit
timezone for the query. The value returned is $srcn + $timezone,
expressed in timezone Z, with the timezone of Z removed.
Assume that the static context provides an implicit timezone of -5:00.
let $tz := fn:dayTimeDuration("-PT10H")
fn:remove-timezone-from-dateTime(xs:dateTime("2002-03-07T10:00:00"))
    returns 2002-03-07T10:00:00
fn:remove-timezone-from-dateTime(xs:dateTime("2002-03-07T10:00:00-07:00"))
    returns 2002-03-07T12:00:00
fn:remove-timezone-from-dateTime(xs:dateTime("2002-03-07T10:00:00"),
    $tz) returns 2002-03-07T05:00:00
fn:remove-timezone-from-dateTime(xs:dateTime("2002-03-07T10:00:00-07:00"),
    $tz) returns 2002-03-07T07:00:00
fn:add-timezone-to-date($srcval as date) as datefn:add-timezone-to-date($srcval as date, $timezone as dayTimeDuration) as dateReturns a date with a timezone.
If $srcval is a date value without a timezone, then let $srcn be $srcval.
Otherwise, let $srcn be the value of fn:remove-timezone-from-date($srcval). If
$timezone is not specified, then $timezone will be the value of the implicit
timezone for the query. The value of $srcn - $timezone is
returned with a timezone of Z.
Note:
EDITOR'S NOTE: The preceding paragraph makes
use of a function fn:remove-timezone-from-date that has been
removed by a different proposal. As a result, the preceding paragraph is
"broken", as is the fourth example below.
Assume an implicit timezone of -5:00.
let $tz := fn:dayTimeDuration("-PT10H")
fn:add-timezone-to-date(xs:date("2002-03-07))
    returns 2002-03-07-05:00
fn:add-timezone-to-date(xs:date("2002-03-07-07:00"))
    returns 2002-03-07-07:00
fn:add-timezone-to-date(xs:date("2002-03-07"),
    $tz) returns 2002-03-07-10:00
fn:add-timezone-to-date(xs:date("2002-03-07T-07:00"),
    $tz) returns 2002-03-07Z
Note:
EDITOR NOTE: The fourth example above is broken because it implies removing the timezone from the date value before adding a new timezone to it.
fn:add-timezone-to-time($srcval as time) as timefn:add-timezone-to-time($srcval as time, $timezone as dayTimeDuration) as timeReturns a time with a timezone.
If $srcval is a time value without a timezone, then let $srcn be $srcval.
Otherwise, let $srcn be the value of fn:remove-timezone-from-time($srcval). If
$timezone is not specified, then $timezone will be the value of the implicit
timezone for the query. The value of $srcn - $timezone is
returned with a timezone of Z.
Assume an implicit timezone of -5:00.
let $tz := fn:dayTimeDuration("-PT10H")
fn:add-timezone-to-time(xs:time("10:00:30"))
    returns 15:00:30Z
fn:add-timezone-to-time(xs:time("10:00:00-07:00"))
    returns 17:00:00Z
fn:add-timezone-to-time(xs:time("10:30:00"),
    $tz) returns 20:30:00Z
fn:add-timezone-to-time(xs:time("10:00:00-07:00"),
    $tz) returns 22:00:00Z
fn:remove-timezone-from-time($srcval as time) as time| fn:remove-timezone-from-time( | $srcval |  as time, | 
| $timezone |  as dayTimeDuration) as time | 
Returns a time without a timezone.
If $srcval has a timezone, then let $srcn be $srcval. Otherwise, let $srcn
be the value of fn:add-timezone-to-time ($srcval). If
$timezone is not specified, then $timezone will be the value of the implicit
timezone for the query. The value returned is $srcn + $timezone,
expressed in timezone Z, with the timezone of Z removed.
Assume an implicit timezone of -5:00.
let $tz := fn:dayTimeDuration("-PT10H")
fn:remove-timezone-from-time(xs:time("10:30:00"))
    returns 10:30:00
fn:remove-timezone-from-time(xs:time("10:30:00-07:00"))
    returns 12:30:00
fn:remove-timezone-from-time(xs:time("10:00:00"),
    $tz) returns 05:00:00
fn:remove-timezone-from-time(xs:time("10:15:00-07:00"),
    $tz) returns 07:15:00
These functions support adding or subtracting a duration value to or from a dateTime, a date or a time value. Appendix E of [XML Schema Part 2: Datatypes] describes an algorithm for performing such operations.
If any of the arguments to the functions below is a dateTime, date or time value that does not contain a timezone, then, for the purposes of the function, the argument is considered to a have an implicit timezone provided by the implementation.
| Function | Meaning | 
|---|---|
| fn:subtract-dateTimes-yielding-yearMonthDuration | Returns the difference between two dateTimes as a yearMonthDuration. | 
| fn:subtract-dateTimes-yielding-dayTimeDuration | Returns the difference between two dateTimes as a dayTimeDuration. | 
| op:subtract-dates | Returns the difference between two dates as a dayTimeDuration. | 
| op:subtract-times | Returns the difference between two times as a dayTimeDuration. | 
| op:add-yearMonthDuration-to-dateTime | Returns the end of a time period by adding a yearMonthDuration to the dateTime that starts the period. | 
| op:add-dayTimeDuration-to-dateTime | Returns the end of a time period by adding a dayTimeDuration to the dateTime that starts the period. | 
| op:subtract-yearMonthDuration-from-dateTime | Returns the beginning of a time period by subtracting a yearMonthDuration from the dateTime that ends the period. | 
| op:subtract-dayTimeDuration-from-dateTime | Returns the beginning of a time period by subtracting a dayTimeDuration from the dateTime that ends the period. | 
| op:add-yearMonthDuration-to-date | Returns the end of a time period by adding a yearMonthDuration to the date that starts the period. | 
| op:add-dayTimeDuration-to-date | Returns the end of a time period by adding a dayTimeDuration to the date that starts the period. | 
| op:subtract-yearMonthDuration-from-date | Returns the beginning of a time period by subtracting a yearMonthDuration from the date that ends the period. | 
| op:subtract-dayTimeDuration-from-date | Returns the beginning of a time period by subtracting a dayTimeDuration from the date that ends the period. | 
| op:add-dayTimeDuration-to-time | Adds the value of the hours, minutes and seconds components of a dayTimeDuration to a time value. | 
| op:subtract-dayTimeDuration-from-time | Subtracts the value of the hours, minutes and seconds components of a dayTimeDuration to a time value. | 
| fn:subtract-dateTimes-yielding-yearMonthDuration( | $srcval1 |  as dateTime, | 
| $srcval2 |  as dateTime) as yearMonthDuration | 
Returns the yearMonthDuration that corresponds to the difference between
the value of $srcval1 and the value of $srcval2. 
If the value of $srcval1 follows in time the value of
$srcval2, then the returned value is a negative duration.  If
one or both arguments do not have a timezone they are assigned an implicit ·implementation-defined·
timezone. If either argument is the empty sequence, returns the empty
sequence.
In general, the difference between two dateTime values will be a duration
that contains years and months as well as days, hours, etc.  In fact, it can
be looked at as a yearMonthDuration plus a dayTimeDuration.  This function
returns the result rounded to contain only years and months. The calculation
is as follows:  first the duration is calculated as the value of a
dayTimeDuration in seconds.  Then, starting from $srcval2, the
maximum number of months in the duration are calculated. The remainder
r is is rounded and added to the number of months. If 0 <=
r < 15.5 days, r rounds to 0 months; if 15.5 days <=
r, r rounds to 1 month.
| fn:subtract-dateTimes-yielding-dayTimeDuration( | $srcval1 |  as dateTime, | 
| $srcval2 |  as dateTime) as dayTimeDuration | 
Returns the dayTimeDuration that corresponds to the difference between the
value of $srcval1 and the value of $srcval2.  If
the value of $srcval1 follows in time the value of
$srcval2, then the returned value is a negative duration.  If
one or both arguments do not have a timezone they are assigned an implicit ·implementation-defined·
timezone. If either argument is the empty sequence, returns the empty
sequence.
This function returns the value of a dayTimeDuration in seconds. Note that the number of days in this value can be greater than 31.
Backs up the subtract, "-", operator on dateTime values.
op:subtract-dates($srcval1 as date, $srcval2 as date) as dayTimeDurationReturns the dayTimeDuration that corresponds to the difference between the
value of $srcval1 and the value of $srcval2.  If
the value of $srcval1 precedes in
time the value of $srcval2, then the returned value is a
negative duration.  If one or both arguments do not have a timezone, they are
assigned an implicit ·implementation-defined·
timezone. If either argument is the empty sequence, returns the empty
sequence.
This function returns the value of a dayTimeDuration in seconds. Note that the number of days in this value can be greater than 31.
Backs up the subtract, "-", operator on date values.
op:subtract-times($srcval1 as time, $srcval2 as time) as dayTimeDurationReturns the dayTimeDuration that corresponds to the difference between the
value of $srcval1 and the value of $srcval2.  If
the value of $srcval1 precedes in
time the value of $srcval2, then the returned value is a
negative duration.  If one or both arguments do not have a timezone, they are
assigned an implicit ·implementation-defined·
timezone. If either argument is the empty sequence, returns the empty
sequence.
This function returns the value of a dayTimeDuration in seconds.
Backs up the subtract, "-", operator on time values.
| op:add-yearMonthDuration-to-dateTime( | $srcval1 |  as dateTime, | 
| $srcval2 |  as yearMonthDuration) as dateTime | 
Returns the dateTime    computed by adding the
yearMonthDuration $srcval2 to the dateTime $srcval1
using the algorithm  
described in Appendix E of [XML Schema Part 2:
Datatypes]. If $srcval2 is
negative, then the result dateTime precedes
$srcval1.
The result has the same timezone as srcval1.  If
srcval1 has no timezone the result has no timezone.
This functions backs up the "+" operator on dateTime and yearMonthDuration.
| op:add-dayTimeDuration-to-dateTime( | $srcval1 |  as dateTime, | 
| $srcval2 |  as dayTimeDuration) as dateTime | 
Returns the dateTime    computed by adding the
dayTimeDuration $srcval2 to the dateTime $srcval1
using the algorithm  
described in Appendix E of [XML Schema Part 2:
Datatypes]. If $srcval2 is
negative, then the result dateTime precedes
$srcval1.
The result has the same timezone as srcval1.  If
srcval1 has no timezone the result has no timezone.
This functions backs up the "+" operator on dateTime and dayTimeDuration.
| op:subtract-yearMonthDuration-from-dateTime( | $srcval1 |  as dateTime, | 
| $srcval2 |  as yearMonthDuration) as dateTime | 
Returns the dateTime    computed by negating the
yearMonthDuration $srcval2 and
adding the result to the dateTime $srcval1
using the algorithm 
described in Appendix E of [XML Schema Part 2:
Datatypes]. If $srcval2 is
negative, then the result dateTime follows $srcval1.
The result has the same timezone as srcval1.  If
srcval1 has no timezone the result has no timezone.
This functions backs up the "-" operator on dateTime and yearMonthDuration.
| op:subtract-dayTimeDuration-from-dateTime( | $srcval1 |  as dateTime, | 
| $srcval2 |  as dayTimeDuration) as dateTime | 
Returns the dateTime    computed by negating the
dayTimeDuration $srcval2 and
adding the result to the dateTime $srcval1
using the algorithm 
described in Appendix E of [XML Schema Part 2:
Datatypes]. If $srcval2 is
negative, then the result dateTime follows
$srcval1.
The result has the same timezone as srcval1.  If
srcval1 has no timezone the result has no timezone.
This functions backs up the "-" operator on dateTime and dayTimeDuration.
| op:add-yearMonthDuration-to-date( | $srcval1 |  as date, | 
| $srcval2 |  as yearMonthDuration) as date | 
Returns the date computed by adding the yearMonthDuration
$srcval2 to the date  $srcval1 using the algorithm described
in Appendix E of [XML Schema
Part 2: Datatypes]. If $srcval2
is negative, then the result date precedes $srcval1.
The result has the same timezone as srcval1.  If
srcval1 has no timezone the result has no timezone.
This functions backs up the "+" operator on date and yearMonthDuration.
| op:add-dayTimeDuration-to-date( | $srcval1 |  as date, | 
| $srcval2 |  as dayTimeDuration) as date | 
Returns the date computed by adding the dayTimeDuration $srcval2 to
the date $srcval1
using the algorithm
described in Appendix E of [XML Schema Part 2: Datatypes]. If $srcval2 is
negative, then the result date precedes $srcval1.
The result has the same timezone as srcval1.  If
srcval1 has no timezone the result has no timezone.
This functions backs up the "+" operator on date and dayTimeDuration.
| op:subtract-yearMonthDuration-from-date( | $srcval1 |  as date, | 
| $srcval2 |  as yearMonthDuration) as date | 
Returns the date computed by negating the
yearMonthDuration $srcval2 and adding
the result to the
date $srcval1 using the algorithm described
in Appendix E of [XML Schema
Part 2: Datatypes]. If $srcval2
is negative, then the result date precedes
$srcval1.
The result has the same timezone as srcval1.  If
srcval1 has no timezone the result has no timezone.
This functions backs up the "-" operator on date and yearMonthDuration.
| op:subtract-dayTimeDuration-from-date( | $srcval1 |  as date, | 
| $srcval2 |  as dayTimeDuration) as date | 
Returns the date computed by negating the
dayTimeDuration $srcval2
and adding the result to the date  $srcval1 using
the algorithm described in Appendix E of [XML Schema Part 2: Datatypes]. If $srcval2 
is negative, then the result date precedes
$srcval1.
The result has the same timezone as srcval1.  If
srcval1 has no timezone the result has no timezone.
This functions backs up the "-" operator on date and dayTimeDuration.
| op:add-dayTimeDuration-to-time( | $srcval1 |  as time, | 
| $srcval2 |  as dayTimeDuration) as time | 
First, the days component of $srcval2 is set to zero (0) and
the value of the resulting duration is calculated.   This value is added to
$parameter1 and the result returned.
The result has the same timezone as srcval1.  If
srcval1 has no timezone the result has no timezone.
This functions backs up the "+" operator on time and dayTimeDuration.
| op:subtract-dayTimeDuration-from-time( | $srcval1 |  as time, | 
| $srcval2 |  as dayTimeDuration) as time | 
First, the days component of $srcval2 is set to zero (0) and
the value of the resulting duration is calculated.   This value is subtracted
from $srcval1 and the result returned.
The result has the same timezone as srcval1.  If
srcval1 has no timezone the result has no timezone.
This functions backs up the "-" operator on time and dayTimeDuration.
Since the validity of a QName is situation dependent, there is no constructor function for QName defined in 4 Constructor Functions. Neither is casting defined for QName from any other type in 16 Casting Functions. This section defines constructor functions for QName as defined in [XML Schema Part 2: Datatypes]. Leading and trailing whitespace, if present, is stripped from string arguments before the result is constructed.
| Function | Meaning | Source | 
|---|---|---|
| class="diff-add"fn:QName-in-context | Returns a QName with the lexical form given in the first argument. The prefix is resolved using the in-scope namespaces defined in the static context or in the given context. | 
fn:QName-in-context($qname as string, $use-default as boolean) as QNameTakes a QName in its lexical form (that is, [prefix:]local-part), and turns it into a value of type QName, resolving any namespace prefix using the in-scope namespaces defined in the static context.
A dynamic error is raised (Invalid lexical form for
QName) if $qname is not in the lexical space for the QName data type as
defined [XML Schema Part 2: Datatypes].
The local part of the resulting QName is taken from
the local part of the supplied $qname. The namespace
URI of the resulting QName is determined as
follows:
If $qname has a
    prefix, then the prefix is mapped to a namespace URI using the in-scope
    namespaces from the static context. A dynamic error is raised (No
    namespace for prefix) if there is no in-scope namespace with this prefix.
If $qname has no
    prefix, and $use-default is
    false, then the resulting QName has no namespace
    URI.
If $qname has no
    prefix, and $use-default is
    true, then the resulting QName has the namespace URI
    given by the default namespace for elements, as
    defined in the static context.
Note: since the supplied argument can be constructed dynamically, this function requires that the namespace mappings defined in the static context are available at evaluation time.
| fn:QName-in-context( | $qname |  as string, | 
| $use-default |  as boolean, | |
| $node |  as node) as QName | 
In this version of the function, the namespace prefix is resolved using the in-scope namespaces property of a supplied element node. The namespace URI of the resulting QName is determined as follows:
If $qname has a
    prefix, then this prefix is mapped to a namespace URI using the in-scope
    namespaces of $node. A dynamic
    error is raised if there is no in-scope namespace with this prefix (No
    namespace for prefix).
If $qname has no
    prefix, and $use-default is
    false, then the resulting QName
    has no namespace URI.
If $qname has no
    prefix, and $use-default is
    true, then the resulting QName has the namespace URI given
    by the default in-scope namespace for $node.
Note: this function is typically used to resolve a QName occurring within the content of an element or attribute, in cases where the QName cannot be resolved directly by the schema processor. Some processors may allow unreferenced in-scope namespaces for an element to be discarded from the data model; when this is the case, the function may raise an error indicating that the prefix is not in scope.
fn:QName-in-context("hello",
    xs:boolean("false")) returns a QName with local name = "hello"
    that is in no namespace".
fn:QName-in-context("eg:myFunc",
      xs:boolean("false") returns a
      QName with local name = "myFunc", prefix
      = "eg" where the prefix is bound to some namespace URI in the static
      context.  The value of the QName is the tuple: namespace URI, local
      name.
This section discusses functions on QNames as defined in [XML Schema Part 2: Datatypes].
| Function | Meaning | Source | 
|---|---|---|
| op:QName-equal | Returns trueif the local
        names and namespace URIs of the two arguments are equal. | |
| fn:get-local-name-from-QName | Returns a string representing the local part of the QName argument. | |
| fn:get-namespace-from-QName | Returns the namespace URI for the QName argument. This may be the empty sequence if the QName is in no namespace. | |
| class="diff-add"fn:get-namespace-uri-for-prefix | Returns the namespace URI of one of the in-scope namespaces for the given element, identified by its namespace prefix. | 
fn:get-in-scope-namespacesop:QName-equal($srcval1 as QName, $srcval2 as QName) as booleanReturns true if the namespace names of $srcval1
and $srcval2 are equal and the local-name parts of
$srcval1 and $srcval2 are identical on a
codepoint-by-codepoint basis. Otherwise, returns false. Two
namespace names are considered equal if they are either both absent or both
present and identical on a codepoint-by-codepoint basis.
Backs up the "eq" and "ne" operators on values of type QName.
If either namespace name is a relative URI, it is undefined whether it will compare equal to any other namespace name.
fn:get-local-name-from-QName($srcval as QName?) as string?Returns a string representing the local part of $srcval. If
$srcval is the empty sequence, returns the empty sequence.
fn:get-namespace-from-QName($srcval as QName?) as anyURI?Returns the namespace URI for $srcval. If
$srcval is in no namespace, the function returns the empty
sequence.
If $srcval is the empty sequence, the empty sequence is
returned.
| fn:get-namespace-uri-for-prefix( | $element |  as element, | 
| $prefix |  as string) as string? | 
Returns the namespace URI of one of the in-scope namespaces for $element, identified by its namespace prefix.
If $element has an
in-scope namespace whose namespace prefix is equal to $prefix, it returns the
namespace URI of that namespace. If $prefix is the
zero-length string, it returns the namespace URI of the default (unnamed)
namespace. Otherwise, it returns the empty sequence.
Names are equal only if their Unicode code-points match exactly.
fn:get-in-scope-namespaces($element as element) as string*Returns the names of the in-scope namespaces for
$element. For namespaces that have a name, it returns the name of
the namespace node (that is, the namespace prefix) as an NCName. For the
default namespace, which is unnamed, it returns the zero-length
string.
This section defines a constructor function for anyURI as defined in [XML Schema Part 2: Datatypes].
| Function | Meaning | Source | 
|---|---|---|
| fn:resolve-uri | Returns an absolute anyURIgiven a base URI and a relative URI. | 
fn:resolve-uri(
$relative as anyURI as anyURIfn:resolve-uri($relative as anyURI, $base as anyURI) as anyURIThe second form of
this function expects $base to be an absolute URI and
$relative to be a relative URI.  It resolves the relative URI
$relative against the base-uri 
$base and returns the resulting
absolute URI.  If $relative
  is an absolute URI, it is returned unchanged. 
If $base is not an absolute URI, a
error is raised ("Relative URI base argument to resolve-uri").
The first form of this function resolves the
relative URI $relative
against the base-uri from the static context. If
$relative is an absolute URI, it is returned unchanged.  If base-uri
is not defined in the static context an error is raised ("No base-uri in
static context").
If the $relativeURI is the
empty string, returns the base-uri from the static context in the first form
and $base in the second form.
Resolving a URI does not dereference it. This is merely a syntactic operation on two character strings.
This section specifies functions that take anyURI as arguments.
| Function | Meaning | Source | 
|---|---|---|
| op:anyURI-equal | Returns trueif the two
        arguments are equal. | 
We define the following comparison operators on base64Binary and hexBinary values. Comparisons take two operands of the same type; that is, both operands must be base64Binary or hexBinary. Each returns a boolean value.
| Function | Meaning | Source | 
|---|---|---|
| op:hexBinary-equal | Returns trueif the two
        arguments are equal. | |
| op:base64Binary-equal | Returns trueif the two
        arguments are equal. | 
| op:base64Binary-equal( | $value1 |  as base64Binary, | 
| $value2 |  as base64Binary) as boolean | 
Returns true if $value1 and value2
are of the same length and contain the same code-points. Otherwise, returns
false.
This function backs up the "eq" and "ne" operators on base64Binary values.
This section discusses functions that take NOTATION as arguments.
| Function | Meaning | Source | 
|---|---|---|
| op:NOTATION-equal | Returns trueif the two
        arguments are equal. | 
This section discusses functions and operators on nodes. 
Nodes are formally defined in [XQuery 1.0
and XPath 2.0 Data Model].
| Function | Meaning | Source | 
|---|---|---|
| fn:name | Returns the name of the context node or the specified node as a string. | XPath 1.0 modified | 
| class="diff-chg"fn:local-name | Returns the local name of the context node or the specified node as a NCName. | 
fn:namespace-urifn:numberfn:langop:node-equalfn:deep-equalop:node-beforeop:node-afterfn:rootFor the illustrative examples below, assume an XQuery operating on a
Purchase Order document containing a number of item elements.  Each item has
child elements called description, quantity, etc.  Quantity has simple
content of type decimal.  Further assume that variables $item1,
$item2, etc. are bound to the nodes for the item elements in the
document in sequence.
fn:name() as stringfn:name($srcval as node?) as stringReturns the name of a node, as a string that is either the zero-length string, or has the lexical form of a QName.
If the argument is omitted, it defaults to the context node. If there is no context node (that is, if the context item is not a node), the function returns the zero-length string.
If the argument is supplied and is the empty sequence, the function returns the zero-length string.
If the target node has no name (that is, if it is a document node, a comment, a text node, or a namespace node having no name), the function returns the zero-length string.
Otherwise, the value returned is a string whose lexical form is a QName.
If $srcval is a processing instruction or a namespace node,
or if it is an element or attribute node whose expanded-QName  (as determined by the name accessor
in the data model) is in no namespace, then the function returns the local
part of the expanded-QName.
If $srcval is an element or attribute whose expanded QName is
in a namespace, then a prefix is determined using 
the same       rules as those for determining the prefix property when the element or               attribute
node               is mapped                   
    to an  element or attribute information item in the InfoSet.     These rules
are given   in
[XQuery 1.0 and XPath 2.0
Data Model]. This prefix is then
combined with the local part of the node's expanded QName to form a string
which will take one of the forms "prefix:local-part" (if the prefix is a
non-zero length string) or "local-part" (if the prefix is a zero-length
string).
fn:local-name() as stringfn:local-name($srcval as node?) as stringReturns the local part of the name of $srcval as a string
that will either be the zero-length string, or will have the lexical form of
an NCName.
If the argument is omitted, it defaults to the context node. If there is no context node (that is, if the context item is not a node), the function returns the zero-length string.
If the argument is supplied and is the empty sequence, the function returns the zero-length string.
If the target node has no name (that is, if it is a document node, a comment, or a text node), the function returns the zero-length string.
Otherwise, the value returned will be the local part of the expanded-QName of the target node (as determined by the name accessor in the data model). This will be a string whose lexical form is an NCName.
fn:namespace-uri() as stringfn:namespace-uri($srcval as node?) as stringReturns the namespace URI of the QName of $srcval as a
string. If the argument is omitted, it defaults to the context node. If there
is no context node (that is, if the context item is not a node), the function
returns the zero-length string. If $srcval is the empty
sequence, the zero-length string is returned.
If the $srcval is neither an element nor an attribute node,
or if it is an element or attribute node which has no QName or whose expanded-QName  (as determined by the name accessor
in the data model) is in no namespace, then the function returns the
zero-length string.
fn:number() as doublefn:number($srcval as item?) as doubleReturns the value    indicated by $srcval or, if
$srcval is not specified, the context node, converted to a
double.
If $srcval is atomic then return the value obtained by converting it to double following the
    rules of 16.8 Casting to numeric
    types.
If $srcval is a node
    with a simply typed value then return that value converted to double following the rules of 16.8 Casting to numeric types.
Otherwise convert $srcval to a string
    as if by a call to the fn:string() function
    and then convert the string to a double following the rules of 16.8 Casting to numeric types.
If the conversion to double fails because the lexical representation is not a valid lexical representation of a numeric simple type as defined in [XML Schema Part 2: Datatypes], then an error is raised ("Invalid lexical representation")
fn:lang($testlang as string) as booleanReturns true or false depending on whether the
language of the context node, as defined using the xml:lang
attribute, is the same as, or a sublanguage of, the language specified by
$testlang.
The relevant xml:lang attribute is determined by the value of
the XPath expression:
(ancestor-or-self::*/@xml:lang)[last()]
If this expression returns an empty sequence, the function returns
false.
Otherwise, the function returns true if and only if the
string-value of the relevant xml:lang attribute is equal to
$testlang ignoring case, or if the string-value of the relevant
testlang attribute contains some hyphen (-) such that the part
of the string-value preceding that hyphen is equal to $testlang,
ignoring case.
op:node-equal($parameter1 as node, $parameter2 as node) as booleanIf the node identified by the value of $parameter1 is the
same node as the node identified by the value of $parameter2
(that is, the two nodes have the same identity), then the function returns
true; otherwise, the function returns false. This
function backs up the "is" and "isnot" operators on nodes.
fn:deep-equal($parameter1 as node, $parameter2 as node) as boolean| fn:deep-equal( | $parameter1 |  as node, | 
| $parameter2 |  as node, | |
| $collation |  as anyURI) as boolean | 
This function tests whether the name and content of the node
$parameter1 are the same as the name and content of the node
$parameter2.
The following (recursive) tests are applied in order to determine whether two nodes are deep-equal.
If the two nodes are of different node-kinds, the result is false.
if (fn:node-kind($parameter1) ne fn:node-kind($parameter2)) 
then false
else
If the two nodes have names, and the names are different when compared as expanded-QNames, the result is false.
if (fn:node-name($parameter1) != fn:node-name($parameter2)) 
then false
else
If the two nodes are text nodes, comment nodes, processing instruction nodes, or namespace nodes, then the result is true if and only if the two nodes have equal string-values, when compared using the selected collation.
if (some $n in ("text", "comment", "processing-instruction", "namespace")
         satisfies $n eq fn:node-kind($parameter1)
    and fn:compare(fn:string($parameter1), fn:string($parameter2), $collation) ne 0)
then false
else
If either node has attributes, then the result is false if either node has an attribute that is not deep-equal to an attribute of the other node, using the selected collation.
if (some $a1 in $parameter1/@* satisfies
      not (some $a2 in $parameter2/@* 
           satisfies fn:deep-equal($a1, $a2, $collation))
    or some $a2 in $parameter2/@* satisfies
      not (some $a1 in $parameter1/@* 
           satisfies fn:deep-equal($a1, $a2, $collation)))
then false
else
If neither node has element children, then the result is true only if the
other node also has simple content, and if the simple content of the two
nodes (that is, the result of the fn:data function) is equal under the rules
for the fn:sequence-deep-equal function, using the
selected collation. (Note: attributes always have simple content.)
if (empty($parameter1/*) and empty($parameter2/*))
then fn:sequence-deep-equal( fn:data($parameter1),
                             fn:data($parameter2),
                             $collation )
else
Otherwise, the result is true if and only if the children of node
$parameter1 are pairwise deep-equal to the children of node
$parameter2, ignoring comment and processing instruction nodes
in both cases.
fn:sequence-deep-equal( $parameter1/(* | text()),
                        $parameter2/(* | text()),
                        $collation )
Note:
The two nodes are not required to have the same type annotation, and they are not required to have the same in-scope namespaces. They may also differ in their parent, their base URI, and their unique-ID. The order of children is significant, but the order of attributes is insignificant. The contents of comments and processing instructions are significant only if these nodes are used directly as arguments to the function, not if they appear as children of the nodes supplied as arguments.
Note:
The result of sequence-deep-equal(1, current-dateTime()) is
false; it does not cause an error to be returned.
The collation used by the invocation of this function is determined according to the rules in 6.3 Equality and Comparison of Strings.
op:node-before($parameter1 as node, $parameter2 as node) as booleanIf the node identified by the value of $parameter1 occurs in
document order before the node identified by the value of
$parameter2, this function returns true; otherwise,
it returns false.  The rules determining the order of nodes
within a single document and in different documents can be found in [XQuery 1.0 and XPath 2.0 Data Model]. This function
backs up the "<<" operator.
op:node-after($parameter1 as node, $parameter2 as node) as booleanIf the node identified by the value of $parameter1 occurs in
document after the node identified by the value of $parameter2,
this function returns true; otherwise, it returns
false. The rules determining the order of nodes within a single
document and in different documents can be found in [XQuery 1.0 and XPath 2.0 Data Model]. This function
backs up the ">>" operator.
fn:root() as nodefn:root($srcval as node) as nodeReturns the root of the tree to which $srcval belongs. This
will usually, but not necessarily, be a document node. If 
$srcval is a document node it is returned.
If the function is called without an argument, the context item is used as the default argument. If the context item is not a node an error is raised ("Context item is not a node").
A sequence is an ordered collection of zero or more
items. An item is either a node or an atomic value.
The terms sequence and item are defined formally in
[XQuery 1.0: An XML Query Language] and [XPath 2.0].
[Issue 89: Functions that have anyType in their return are problematic.]
The following constructor functions are defined for sequences.
| Function | Meaning | 
|---|---|
| op:to | Returns the sequence containing every integer between the values of the operands. | 
op:to($firstval as integer, $lastval as integer) as integer+Returns        the sequence containing every
integer whose value is between the  value of $firstval
(inclusive) and the  value of $lastval (inclusive), in monotonic
order. If the  value of the first operand is less than the  value of the
second, the sequence is in increasing order; otherwise, it is in decreasing
order.  If the values  of the two operands
are equal, a sequence containing a single
integer equal to the  value is returned.
This function backs up the "to" operator.
The following functions are defined on sequences.
| Function | Meaning | Source | 
|---|---|---|
| fn:boolean | Casts a sequence to a boolean. | XPath 1.0 | 
| op:concatenate | Concatenates two sequences. | XPath 1.0 | 
| fn:item-at | Returns the item at given index. | XPath 2.0 Req 4.4 (Should) | 
| fn:index-of | Returns a sequence of unsignedInts, each of which is the index of a member of the specified sequence that is equal to the simple value or node that is the value of the second argument. If no members of the specified sequence are equal to the value of the second argument, the function returns an empty sequence. | XPath 2.0 Req 4.4 (Should) | 
| fn:empty | Indicates whether or not the provided sequence is empty. | XPath 2.0 Req 4.4 (Should) | 
| fn:exists | Indicates whether or not the provided sequence is not empty. | |
| class="diff-chg"fn:distinct-nodes | Returns a sequence in which all but one of a set of duplicate nodes, based on node identity, have been deleted. The order in which the distinct nodes are returned is implementation-dependent. | 
fn:distinct-valuesfn:insertfn:removefn:subsequencefn:unordered[Issue 63: Do we need variations of index-of for values and identity?]
As in the previous section, for the illustrative examples below, assume an
XQuery operating on a Purchase Order document containing a number of item
elements. The variable $seq is bound to the sequence of item
nodes in document order.  The variables $item1,
$item2, etc. are bound to individual item nodes in the
sequence.
fn:boolean($srcval as item*) as booleanComputes the  boolean value of the sequence            $srcval.  Returns
false if      $srcval is one of
the following:
The empty sequence
The singleton
    boolean value   false.
The singleton string value "" (the empty string).
A singleton numeric value that is numerically equal to zero.
The singleton
    double or float   value   
    NaN.
Otherwise   returns
true.
op:concatenate($seq1 as item*, $seq2 as item*) as item*Returns a sequence consisting of the items in $seq1 followed
by the items in $seq2. This function backs up the infix operator
",".  If either sequence is the empty sequence, the other operand is
returned.
fn:item-at($seqParam as item*, $posParam as integer) as item?Returns the item in $seqParam that is located at the index
that is the value of $posParam.
If  $seqParam is the empty sequence, returns the empty
sequence.
If the value of $posParam is greater than the number of items
in the sequence, or is less than or equal to zero (0), then an error is
raised ("Invalid position").
This function is used in the definition of the formal semantics of filter
expressions, that is, expressions of the form
expression-1[expression-2]
fn:node-equal(fn:item-at($seq, 1),
    $item1) returns true.
fn:index-of($seqParam as item*, $srchParam as item) as unsignedInt*| fn:index-of( | $seqParam |  as item*, | 
| $srchParam |  as item, | |
| $collationLiteral |  as anyURI) as unsignedInt* | 
If the value of $seqParam contains only simple values, then
the function returns a sequence of unsigned integers indicating the indexes
(positions) of items in the value of $seqParam that are equal to
the simple value of $srchParam.  If the data types of the simple
values are strings, then equality is determined according to the collation
that is used.
If the value of $seqParam contains nodes, then the function
returns a sequence of unsigned integers indicating the indexes (positions) of
nodes whose string values are equal to the string value of the node in the
second argument.  Equality of string values is determined according to the
collation that is used.
The collation used by the invocation of this function is determined according to the rules in 6.3 Equality and Comparison of Strings.
The sequence must contain either simple values or nodes,
not both.  In addition, if the sequence contains simple values
$srchParam must be a simple value and if the sequence contains
nodes $srchParam must be a node. If the above conditions are
violated, then an error is raised ("Mixed simple values and nodes").
If the value of $seqParam is the empty sequence, the empty
sequence is returned.
The index is 1-based, not 0-based.
fn:empty($srcval as item*) as booleanIf the value of $srcval is the empty sequence, the function
returns true; otherwise, the function returns
false.
fn:exists($srcval as item*) as booleanIf the value of $srcval is not the empty sequence, the
function returns true; otherwise, the function returns
false.
fn:distinct-nodes($srcval as node*) as node*Returns the sequence that results from removing from $srcval
all but one of a set of nodes that have the same identity as one another,
based on node identity (that is, using node-equal()).  The order  in which  the distinct nodes are 
returned is implementation-dependent. If
$srcval is the empty sequence, returns the empty sequence.
fn:distinct-values($srcval as atomic value*) as atomic value*| fn:distinct-values( | $srcval |  as atomic value*, | 
| $collationLiteral |  as anyURI) as atomic
        value* | 
Returns      the sequence that results from
removing from $srcval all but one of a set of values that are
eq to one other.   Values of the same type must have a total
order. If this condition is not satisfied, an error is
raised ("Values do not have total order"). If date/time values do not have a
timezone a implicit timezone, provided by the static context is added.
For float and double   values
NaN is equal to itself and 0.0 is equal 
to -0.0.
Equality of string values are determined according to the collation that is used. The order of the values returned is implementation-dependent. The collation used by the invocation of this function is determined according to the rules in 6.3 Equality and Comparison of Strings.
If $srcval is the empty
sequence, the empty sequence is returned.
fn:insert($target as item*, $position as integer, $inserts as item*) as item*Returns a new sequence constructed from the value of $target
with the value of $inserts inserted at the position specified by
the value of $position.  (The value of $target is
not affected by the sequence construction.)
Let the effective value of $position be N computed
as cast as unsignedInt(floor($position)).
If N is less than zero (0), the effective value of N is
zero (0).  If N is greater than the number of items in
$target, then the effective value of N is equal to the
number of items in $target plus 1.
The value returned by the function consists of all items of
$target whose index is less than or equal to N,
followed by all items of $inserts, followed by the remaining
elements of $target, in that sequence.
If $target is the empty sequence, a copy of
$inserts is returned. If $inserts is the empty
sequence, a copy of $target is returned.
fn:remove($target as item*, $position as integer) as item*Returns a new sequence constructed from the value of $target
with the item at the position specified by the value of
$position removed.
Let the effective value of $position be N computed
as cast as unsignedInt(floor($position)).
If N is less than 1 or greater than the number of items in
$target, no action is taken. Otherwise, the value returned by
the function consists of all items of $target whose index is
less than N, followed by all items of $target whose
index is greater than N.  If $target is the empty
sequence, the empty sequence is returned.
fn:subsequence($sourceSeq as item*, $startingLoc as integer) as item*| fn:subsequence( | $sourceSeq |  as item*, | 
| $startingLoc |  as integer, | |
| $length |  as integer) as item* | 
Returns the contiguous sequence of items in the value of
$sourceSeq beginning at the position indicated by the value of
$startingLoc and continuing for the number of items indicated by
the value of $length.
If $length is not specified, then the subsequence includes
items to the end of $sourceSeq.
The value of $length can be greater than the number of items
in the value of $sourceSeq following the beginning position, in
which case the subsequence includes items to the end of
$length.
The first item of a sequence is located at position 1, not position 0.
If $sourceSeq is the empty sequence, returns the empty
sequence.
| Function | Meaning | Source | 
|---|---|---|
| fn:sequence-deep-equal | Returns true if the two arguments have the same value. | Data Model | 
| fn:sequence-node-equal | Returns true if the two arguments have the same nodes. | Data Model | 
| op:union | Returns the union of the two sequence arguments, eliminating duplicates. | XPath 2.0 Req 1.5 (Should) | 
| op:intersect | Returns the intersection of the two sequence arguments, eliminating duplicates. | XPath 2.0 Req 1.5 (Should) | 
| op:except | Returns the difference of the two sequence arguments, eliminating duplicates. | XPath 2.0 Req 1.5 (Should) | 
As in the previous sections, for the illustrative examples below, assume a
XQuery operating on a Purchase Order document containing a number of item
elements. The variables $item1, $item2, etc. are
bound to individual item nodes in the sequence.  We shall use sequences of
these nodes in the examples below.
fn:sequence-deep-equal($parameter1 as item*, $parameter2 as item*) as boolean?| fn:sequence-deep-equal( | $parameter1 |  as item*, | 
| $parameter2 |  as item*, | |
| $collationLiteral |  as anyURI) as boolean? | 
If the sequences that are the values of $parameter1 and
$parameter2 have the same values (that is, they have the same
number of items and items in corresponding positions in the two sequences
compare equal if they are values and deep-equal() if they are
nodes.), then the function returns true; otherwise, the function
returns false. Returns the empty sequence if one or both of its
arguments is the empty sequence.
String values are compared according to the collation that is used.
The collation used by the invocation of this function is determined according to the rules in 6.3 Equality and Comparison of Strings.
fn:sequence-node-equal($parameter1 as node*, $parameter2 as node*) as boolean?Returns the empty sequence if one or both of its arguments is the empty sequence.
If the sequences that are the values of $parameter1 and
$parameter2 have the same nodes as content (that is, they have
the same number of items and items in corresponding positions in the two
sequences are the identical nodes), then the function returns
true; otherwise, the function returns false.
op:union($parameter1 as node*, $parameter2 as node*) as node*Constructs a sequence containing every node that occurs in the values of
$parameter1 or $parameter2, eliminating duplicate
nodes.  Nodes are returned in document order. Two nodes are equal if they are
fn:node-equal().
This function backs up the "union" or "|" operator.
op:intersect($parameter1 as node*, $parameter2 as node*) as node*Constructs a sequence containing every node that occurs in the values of
both $parameter1 and $parameter2, eliminating
duplicate nodes.  Nodes are returned in document order.
If either operand is the empty sequence, the empty sequence is returned.
Two nodes are equal if they are fn:node-equal().
This function backs up the "intersect" operator.
op:except($parameter1 as node*, $parameter2 as node*) as node*Constructs a sequence containing every node that occurs in the values of
$parameter1, but not in the value of $parameter2,
eliminating duplicate nodes.  Nodes are returned in document order.
If $parameter1 is the empty sequence, the empty sequence is
returned.  If $parameter2 is the empty sequence, a copy of
$parameter1 is returned.
Two nodes are equal if they are fn:node-equal().
This function backs up the "except" operator.
Aggregate functions take a sequence as argument and return a single value
computed from values in the sequence. Except for fn:count, 
the sequence must consist of values of a single type,
or they must be numeric, and support certain
operations.
| Function | Meaning | Source | 
|---|---|---|
| fn:count | Returns the number of items in the sequence. | XPath 1.0 | 
| class="diff-chg"fn:avg | Returns the average of a sequence of values. | 
fn:maxfn:minfn:sumfn:count($srcval as item*) as unsignedIntReturns the number of items in the value of $srcval.  Returns
0 if $srcval is the empty sequence.
fn:avg($srcval as atomic value*) as atomic
value?$srcval must  contain items of a single type
(For numeric values, the numeric promotion   rules
defined in 5.2 Operators on Numeric Values are used to promote all values
to a single common type).  In addition, the type must support addition and
division by an integer. If date/time values
do not have
a timezone, the implicit timezone provided by
the static context is added. The function returns a value of the same type as
the items in $srcval which is the average of the values (computed as sum($srcval) div
count($srcval)).   If $srcval is the empty sequence, the
empty sequence is returned.
If,       $srcval does not contain only numbers, or items of a single type that support addition and division
by an integer, then an error is raised ("Invalid  argument").
fn:max($srcval as atomic value*) as atomic
value?fn:max($srcval as atomic value*,
$collationLiteral as anyURI) as atomic
value?$srcval must contain only items
of a single type. (For numeric values, the numeric promotion rules defined in 5.2 Operators on Numeric Values are used to
promote all values to a single common type.) In addition, the values in the
sequence must have a total order.   If date/time
values do not have a timezone, the implicit timezone provided by the static context is added.   Duration values must either all be
yearMonthDuration values or must all be dayTimeDuration values. If any of
these conditions is not true, then an error is raised ("Invalid
argument").
fn:max returns a value of the same type as the items in $srcval
which is the item in the value in $srcval whose value is greater than
or equal to the value of every other item in the value of
$srcval.  If there are two or more such items, then the specific
item whose value is returned is implementation-dependent.
For float and
double values NaN
is greater than all numeric values including +INF and
0.0 is greater than -0.0.
If the items in the value of $srcval are strings, then the
determination of the greatest item is made according to the collation that is
used. The collation used by the invocation of this function is determined
according to the rules in 6.3 Equality and
Comparison of Strings.
fn:min($srcval as atomic value*) as atomic
value?fn:min($srcval as atomic value*,
$collationLiteral as anyURI) as atomic
value?$srcval must contain only items
of a single type. (For numeric values, the numeric promotion rules defined in 5.2 Operators on Numeric Values are used to
promote all values to a single common type.) In addition, the values in the
sequence must have a total order. If date/time
values do  not
have a timezone, the implicit timezone
provided by the static context is added.  Duration values must either all be
yearMonthDuration values or must all be dayTimeDuration values. If any of
these conditions is not true, then an error is raised ("Invalid
argument").
fn:min returns a value of the same type as the items in $srcval
which is the item in the value in $srcval whose value is less than or
equal to the value of every other item in the value of $srcval. 
If there are two or more such items, then the specific item whose value is
returned is implementation-dependent.
For float and
double values NaN
is greater than all numeric values including +INF and
0.0 is greater than -0.0.
If the items in the value of $srcval are strings, then the
determination of the least item is made according to the collation that is
used. The collation used by the invocation of this function is determined
according to the rules in 6.3 Equality and
Comparison of Strings.
fn:sum($srcval as atomic value*) as atomic
value$srcval must  contain items of a single type
(For numeric values, the numeric promotion   rules
defined in 5.2 Operators on Numeric Values are used to promote all values to a single common type).  In
addition, the type must support addition. 
Duration values must either all be yearMonthDuration
values or must all be dayTimeDuration values. The function returns a value of
the same type as the items in $srcval which is
the sum of the values.   If
$srcval is the empty sequence, then 0.0 is returned.
If,       $srcval does not contain only numbers, or items of a single type that support addition, then
an error is raised ("Invalid argument").
| Function | Meaning | Source | 
|---|---|---|
| fn:id | Returns the sequence of nodes having unique IDs that match the IDREFs represented by the argument sequence. | XPath 1.0 | 
| fn:idref | Returns the sequence of nodes with IDREFs matching the items in the argument sequence. | XSLT 2.0 Req. 2.11 (Could) | 
| fn:document | Returns a sequence of document nodes retrieved using the URIs specified in its arguments. | XSLT 1.0 | 
| fn:collection | Returns a sequence of document nodes retrieved using the URI specified as its argument. | |
| fn:input | Returns the input sequence. | 
fn:id($srcval as string*) as element*Returns the sequence of element nodes with ID values matching the value of
one of the IDREF values supplied in $srcval. Each
string in  
$srcval is
parsed as if it were of type xs:IDREF, that is,
$srcval is treated as a space-separated
sequence of tokens, each acting as an IDREF. These tokens are then included in the list of
candidate IDREFs. After this substitution, the sequence must consist entirely of IDREF
values. If any of the tokens is not a
lexically-valid IDREF (that is, if it is not lexically an NCName) it is
ignored.
The result of the function is a sequence, in document order, of those elements that are in the same document as the context node, and that have an ID value equal to one or more of the IDREFs in the list of candidate IDREFs. An element has an ID value of V if it has an attribute whose type is xs:ID and whose value is V.
An ID value matches a candidate IDREF if they consist of the same sequence of Unicode code-points. The default collation is not used in the comparison.
A dynamic error is raised if the context item is not a node ("No context node").
No error is raised in respect of an IDREF value that does not match the ID of any element in the document. If no IDREF value matches any element, the function will return an empty sequence.
If the source document is well-formed but not valid, it is possible for two or more elements to have the same ID value. In this situation, the function will select the last such element.
It is also possible in an invalid document to have an attribute that has a declared type of ID, whose value does not conform to the lexical rules for an ID. Such an element will never be selected by this function.
fn:idref($srcval as string*) as element*Returns the sequence of elements nodes having either an IDREF attribute
whose value matches the value of one of the items in the value of
$srcval or an IDREFS attribute whose value contains an IDREF
value that matches the value of one of the items in the value of
$srcval. This function allows reverse navigation from IDs to
IDREFs.
The nodes that are returned all belong to the document containing the context item, if it is a node. If the context document is not specified, then an error is raised ("No context document"). If the context document is the empty sequence, returns the empty sequence.
fn:document($srcval1 as item*) as node*fn:document($srcval1 as item*, $srcval2 as node*) as node*If $srcval2 is the empty sequence, or a sequence whose first
item is not a node, unless all the URIs in $srcval1 are absolute
URIs, then an error is raised ("Invalid arguments to document function"). If
$srcval2 is a sequence of more than one node, the effect is as
if only the first node in the sequence were supplied.
Two documents are treated as the same document if they are identified by the same URI. The URI used for the comparison is the absolute URI into which any relative URI was resolved and does not include any fragment identifier. Thus, the following expression (if it does not cause an error) will always be true:
document("foo.xml") is document("foo.xml")
Note:
The scope over which this applies depends on the processing context. In XSLT, it applies to any two calls on the document function executed during the same transformation. In XQuery, it applies to any two calls executed during the same query evaluation.
The result of the document function can be explained in terms of an
internal primitive function one-doc, which takes a requested URI
and a base URI as arguments and returns a node sequence as its result. The
result of the document function is the union of the node sequences obtained
by calling one-doc once for each member of
$srcval1.
The one-doc function retrieves a document using a request URI
R and a base URI B.
For a member of $srcval1 that is a node N, the
one-doc function is called with the string-value of N as the
request URI and the effective base URI of $srcval2 if
$srcval2 is supplied. If srcval2 is not supplied,
the base URI is the effective base URI of N.
For a member of $srcval1 that is a simple value, the
one-doc function is called using a request URI obtained by
converting the simple value to a string as if by using the string function,
and the effective base URI of $srcval2 if $srcval2
is supplied. If srvcal2 is not supplied, the base URI is
obtained from the static context.
The effective base URI of a node is defined to be the base URI of the node (as defined in [XQuery 1.0 and XPath 2.0 Data Model] in the case of document nodes and element nodes, and the base URI of the parent of the node for any other kind of node. If the node is not a document or element node and has no parent, then an error is raised ("Invalid arguments to document function").
The internal one-doc function operates as follows.
The resource identified by the URI is retrieved. The data resulting from the retrieval action is parsed as an XML document and a tree is constructed in accordance with the [XQuery 1.0 and XPath 2.0 Data Model]. An error retrieving the resource is classed as a dynamic error. In such cases, either an error is raised ("Error retrieving resource"), or the processor must recover by returning an empty sequence. One possible kind of retrieval error is that the implementation does not support the URI scheme used by the URI. An implementation is not required to support any particular URI schemes. The documentation for an implementation should specify which URI schemes the implementation supports.
If the URI reference does not contain a fragment identifier, then the document node of the document is returned. If the URI reference does contain a fragment identifier, the function returns a node sequence containing the nodes in the tree identified by the fragment identifier of the URI reference. The semantics of the fragment identifier are dependent on the media type of the result of retrieving the URI. An error in processing the fragment identifier is classed as a dynamic error. In such cases, then an error is raised ("Error processing fragment identifier"), or the processor must recover by returning an empty sequence. Possible errors include:
The fragment identifier identifies something that cannot be represented by a node sequence (such as a range of characters within a text node).
The implementation does not support fragment identifiers for the media-type of the retrieval result. An implementation is not required to support any particular media types. The documentation for an implementation should specify for which media types the implementation supports fragment identifiers.
The data resulting from the retrieval action is parsed as an XML document regardless of the media type of the retrieval result; if the top-level media type is text, then it is parsed in the same way as if the media type were text/xml; otherwise, it is parsed in the same way as if the media type were application/xml.
fn:collection($srcval as string) as node*Takes a string as argument and returns a sequence of nodes obtained by
casting $srcval to anyURI and resolving it.  If
$srcval is not in the lexical space of anyURI or if the value,
after casting, does not resolve to a collection, then an error is raised
("Invalid argument to collection function"). All
invocations of this function that are executed during the course of a single
outermost XQuery or XPath expression return the same value.
fn:input() as node*Returns the input sequence. If no input sequence has been assigned, then an error is raised ("No input sequence"). The means by which an input sequence is assigned depends on the environment. All invocations of this function that are executed during the course of a single outermost XQuery or XPath expression return the same value.
The following functions are defined to obtain information from the evaluation context. The context is always defined but may be the empty sequence.
| Function | Meaning | Source | 
|---|---|---|
| fn:context-item | Returns the context item. | XPath 1.0 | 
| fn:position | Returns the position of the context item within the sequence of items currently being processed. | XPath 1.0 | 
| fn:last | Returns the number of items in the sequence of items currently being processed. | XPath 1.0 | 
| class="diff-chg"fn:current-dateTime | Returns the current dateTime. | 
fn:current-datefn:current-timefn:default-collationfn:implicit-timezonefn:context-item() as item?Returns the context item i.e. the item currently being processed. Returns the empty sequence if the context is the empty sequence.
fn:position() as unsignedInt?Returns an unsignedInt indicating the position of the context item within the sequence of items currently being processed. Returns the empty sequence if the context is the empty sequence.
fn:last() as unsignedInt?Returns an unsignedInt indicating the number of items in the sequence of items currently being processed. Returns the empty sequence if the context is the empty sequence.
fn:current-dateTime() as dateTimeReturns the dateTime (with timezone) that is current at some time during
the evaluation of the XQuery or XPath expression in which
current-dateTime() is executed.  All invocations of
current-dateTime() that are executed during the course of a
single outermost XQuery or XPath expression return the same value.  The
precise instant during that XQuery or XPath
expression's evaluation represented by the value of
current-dateTime() is ·implementation-defined·.
fn:current-date() as dateReturns the date (with timezone) that is current at some time during the
evaluation of the XQuery or XPath expression in which
current-date() is executed.  All invocations of
current-date() that are executed during the course of a single
outermost XQuery or XPath expression return the same value. The precise
instant during that XQuery or XPath
expression's evaluation represented by the value of
current-date() is ·implementation-defined·.
fn:current-time() as timeReturns the date (with timezone) that is current at some time during the
evaluation of the XQuery or XPath expression in which
current-date() is executed.  All invocations of
current-date() that are executed during the course of a single
outermost XQuery or XPath expression return the same value. The precise
instant during that XQuery or Xpath expression's evaluation represented by
the value of current-date() is ·implementation-defined·.
Cast functions and cast operators take an expression as their argument and
return a value of a given type. There are two ways of converting values to a
given type: constructor functions and cast
expressions. They                         provide identical semantics with different syntax.  The name of a constructor function is the
same as the name of the [XML Schema Part 2: Datatypes]
built-in type (see 4.1 Constructor Functions for
XML Schema Built-in Types) or
user-derived type (see 4.2 Constructor
Functions for User-Defined Types)
that is the target for the conversion, and the semantics are exactly
the same as for a cast expression: for example,
xs:date("2002-01-01") means exactly the same as "cast as xs:date
("2002-01-02")" .
Where the argument to a cast is a literal, the result of the function may be evaluated statically; if an error is encountered during such evaluation, it may be reported as a static error.
This section defines casting between the 19
primitive types defined in [XML Schema Part 2:
Datatypes] as well as xs:anySimpleType and the two
derived types fn:yearMonthDuration and fn:dayTimeDuration. The type conversions
that are supported are indicated in the table below.  In this table, there is
a row for each primitive type with that type as the source of the conversion
and there is a column for each primitive type as the target of the
conversion. The intersections of rows and columns contain one of three
characters: "Y" indicates that a conversion from values of the type to which
the row applies to the type to which the column applies is supported; "N"
indicates that there are no supported conversions from values of the type to
which the row applies to the type to which the column applies; and "M"
indicates that a conversion from values of the type to which the row applies
to the type to which the column applies may be supported, subject to
restrictions discussed in this section.
In the following table, the columns and rows are identified by short codes that identify simple types as follows:
aST = anySimpleType
aURI = anyURI
b64 = base64Binary
bool = boolean
dat = date
Day = gDay
dbl = double
dec = decimal
dT = dateTime
dTD = dayTimeDuration
dur = duration
flt = float
hxB = hexBinary
MD = gMonthDay
Mon = gMonth
NOT = NOTATION
QN = Qname
str = string
tim = time
YM = gYearMonth
yMD = yearMonthDuration
Yr = gYear
In the following table, the notation "S\T" indicates that the source ("S") of the conversion is indicated in the column below the notation and that the target ("T") is indicated in the row to the right of the notation.
| S\T | aST | str | flt | dbl | dec | dur | yMD | dTD | dT | tim | dat | YM | Yr | MD | Day | Mon | bool | b64 | hxB | aURI | QN | NOT | 
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| aST | Yclass="diff-add" | Y | 
Casting a value to an derived type can be separated into three cases:
When the supplied value is an instance of a type that is derived by restriction from the target type. This is described in section 16.3 Casting from derived types to parent types.
When the supplied value is of a type derived by restriction from the same primitive type as the target type. This is described in 16.4 Casting within a branch of the type hierarchy.
.When the derived type is derived, directly or indirectly from a from a different primitive type than the source type. This is described in 16.5 Casting across the type hierarchy.
It is possible to
cast a value     of any     type to   a  type from   
which it is derived, directly         or indirectly,           by restriction.                         For example, it is possible   
       to cast an unsignedShort   to an
unsignedInt,      an unsignedLong,
an unsignedInteger      ,
an integer,   
or a decimal. Since
the value       space of the original type is
a subset of the value space of the
target type, such a cast is always successful.
The result will
have same value as the original, but will have a new type annotation.
It is possible to cast a value to a target type if the type of the source
value and the target type are both derived by restriction (directly or
indirectly) from the same primitive type, provided that the supplied value
conforms to the constraints implied by the facets of the target type. For
example an instance of xs:byte can be cast to
xs:unsignedShort, provided the value is not negative. This
includes the case where the target type is derived from the type of the
supplied value as well as the case where both derive from a common
supertype.
If the value does not conform to the facets defined by the target type, then an error is raised ("Value does not conform to facets"). In the case of the pattern facet (which applies to the lexical space rather than the value space), the pattern is tested against the canonical lexical representation of the value, as defined by the source data type (or the result of casting the value to a string, in the case of types that have no canonical lexical representation).
Note that this will cause casts to fail if
the pattern excludes the canonical lexical representation. For example, if
the type my:currency is defined as a restriction of
xs:decimal with a pattern that requires two digits after the
decimal point, casting of an integer to my:currency will always
fail, because the canonical representation of an integer does not conform to
this pattern.
In some cases, casting from a parent type to a derived type requires special rules. See, for example: 16.9 Casting to duration and date and time types
When the source type and the target type are derived, directly or indirectly from different primitive types, this is called casting across the type hierarchy. Casting across the type hierarchy is logically equivelent to three separate steps performed in order. Errors can occur in either of the latter two steps.
Cast the source value up the hirerachy to the primitive type of the source as described in: 16.3 Casting from derived types to parent types.
Cast the value to the primitive type of the target type as described in: 16.1 Casting from primitive types to primitive types.
Cast the value down to the target type as described in: 16.4 Casting within a branch of the type hierarchy
When the supplied
value is a string, or   
an instance of anySimpleType, it is
treated as being
a string value and validated as a lexical value
of the target type. Casting is permitted from string and
anySimpleType to any primitive atomic type or an atomic type derived by
restriction except QName.
For  example,
cast as
xs:unsignedInteger("13") returns the
unsignedInteger with value 13. This could also be written xs:unsignedInteger("13").
Casting is permitted
from any primitive type to the primitive type
string.
When a value of
    any simple type is cast to
    string, the derivation of the string value
    TV depends on the source type ST and on the
    source value
    SV, as follows.
If ST is string or
        NOTATION, TV is     SV    .
If ST is anyURI, then TV is the
        lexical representation of SV, as defined in [XML Schema Part 2: Datatypes], with each space
        replaced by the sequence "%20".
In all other cases, TV is the canonical representation of SV, as defined by [XML Schema Part 2: Datatypes]. If [XML Schema Part 2: Datatypes] does not provide a canonical representation for the datatype, then it is the single lexical representation of SV as defined in [XML Schema Part 2: Datatypes].
Casting is permitted from any primitive type
to anySimpleType. To cast to
anySimpleType the value is converted to its canonical lexical representation and the type annotation
changed to anySimpleType.
Conversion to the  numeric types (that is,
float, double and decimal depends on
factors discussed below.
When a value of any simple type is cast to float, the
    float value TV is derived from the source type
    ST and the source value SV as follows:
If ST is float, then TV is
        SV and the conversion is complete.
If ST is double and SV cannot be
        represented in the value space of float as defined in [XML Schema Part 2: Datatypes], then the cast
        returns NaN..
If ST is double and SV can be
        represented in the value space of float as defined in [XML Schema Part 2: Datatypes], then TV
        is SV and the conversion is complete.
If ST is decimal or a type derived from
        decimal, then TV is SVconverted to a float value
        and the conversion is complete.
If ST is boolean, SV is converted to
        1.0 if SV is 1 or true and
        0.0 if SV is 0 or false and
        the conversion is complete.
SV is converted to an intermediate value IV of
        type token.
If the value of fn:upper-case( IV
        ) is INF, -INF, or
        NAN, then TV is positive infinity, negative
        infinity, or not-a-number, respectively, and the conversion is
        complete.
If IV does not match the lexical structure of
        NumericLiteral as defined in [XQuery
        1.0: An XML Query Language], then an error is raised ("Invalid
        lexical value").
Otherwise, let NL be a NumericLiteral
        comprising the same sequence of characters as IV. 
        TV is xs:float( NL ).
When a value of any simple type is cast to double, the
    double value TV is derived from the source type
    ST and the source value SV as follows:
If ST is double, then TV is
        SV and the conversion is complete.
If ST is float or decimal or
        types derived from them, then TV is xs:double(cast as
        string( SV )) and the conversion is
        complete.
If ST is
        decimal or a type derived from decimal, then
        TV is SVconverted to a
        double value and the conversion is complete.
If ST is boolean, SV is converted to
        1.0 if SV is 1 or true and
        0.0 if SV is 0 or false and
        the conversion is complete.
SV is converted to an intermediate value IV of
        type token.
If the value of fn:upper-case( IV
        ) is INF, -INF, or
        NAN, then TV is positive infinity, negative
        infinity, or not-a-number, respectively, and the conversion is
        complete.
If IV does not match the lexical structure of
        NumericLiteral as defined in [XQuery
        1.0: An XML Query Language], then an error is raised ("Invalid
        lexical value").
Otherwise, let NL be a NumericLiteral
        comprising the same sequence of characters as IV. 
        TV is xs:double( NL ).
When a value of any simple type is cast to decimal, the
    decimal value TV is derived from the source type
    ST and the source value SV as follows:
If ST is decimal, or a type derived from
        decimal, then TV is SV, converted to decimal value
        if need be, and the conversion is complete.
If ST is float or double,
        then TV is the decimal value,
        within the set of decimal values
        that the implementation is capable of representing, that is
        numerically closest to SV. If
        two values are equally close then the one that is closest to zero is
        chosen. If SV is positive or negative infinity or
        NaN, or if it is
        higher than the highest decimal value
        that the implementation can represent, or lower than the lowest, then
        the cast raises an error (Error in casting to decimal).
If ST is boolean, SV is converted to
        1.0 if SV is 1 or true and
        0.0 if SV is 0 or false and
        the conversion is complete.
SV is converted to an intermediate value IV of
        type token.
If IV does not match the lexical structure of
        NumericLiteral as defined in [XQuery
        1.0: An XML Query Language], then an error is raised ("Invalid
        lexical value").
Otherwise, let NL be a NumericLiteral
        comprising the same sequence of characters as IV. 
        TV is decimal(cast as string(fn:round( NL
        ))).
Conversion from primitive types to duration and date and time types depends on factors considered below.
When a value of any primitive type is cast to duration,
    yearMonthDuration or dayTimeDuration the
    target value TV is derived from the source type
    ST and the source value SV as follows:
If source type (ST) = target type (TT) then TV is SV.
If ST is
          string or a type derived from string, then
          TV is derived from SV using XML Schema
          validation.
If ST is
          duration or a type derived from
          duration and TT is
          yearMonthDuration, then TV
          is derived from SV by removing
          the date and time components from SV.
If ST is
          duration or a type derived from duration and
          TT is dayTimeDuration, then TV is derived
          from SV by removing the year and month components from
          SV.
If ST is yearMonthDuration or dayTimeDuration or a type
        derived from them and TT
        is duration, then TV is derived from SV by
        xs:duration(cast as string(
        SV)).
When a value of any primitive type is cast to dateTime,
    time, date, gYearMonth,
    gYear, gMonthDay, gDay, or
    gMonth, let CYR be cast as string( fn:get-Year( fn:currentDateTime() ) ), let
    CMO be cast as string( fn:get-month( fn:currentDateTime() ) ),
    and let CDA be cast as string( fn:get-day( fn:currentDateTime() ) ).
When a value of any primitive type is cast to dateTime,
    the dateTime value TV is derived from the source
    type ST and the source value SV as follows:
If ST is dateTime, then TV is
        SV.
If ST is time, then let SHR be
        cast as string( fn:get-hour( SV )
        ), let SMI be cast as string( fn:get-minute( SV )
        ), and let SSE be cast as string( fn:get-second( SV )
        ); TV is xs:dateTime( fn:concat( CYR , '-',
         CMO , '-',  CDA , 'T',
         SHR , ':',  SMI , ':',
         SSE ) ).
If ST is date, then let SYR be
        cast as string( fn:get-Year( SV )
        ), let SMO be cast as string( fn:get-month( SV )
        ), and let SDA be cast as string( fn:get-day(  SV )
        ); TV is xs:dateTime( fn:concat( SYR , '-',
         SMO , '-',  SDA ,
        'T00:00:00') ).
If ST is string or a type derived from
        string and SV is not a valid lexical
        representation for dateTime as specified in [XML Schema Part 2: Datatypes], then an error is
        raised ("Invalid lexical value").
If ST is string or a type derived from
        string and SV is a valid lexical representation
        for dateTime as specified in [XML
        Schema Part 2: Datatypes], then TV is
        xs:dateTime( SV ).
When a value of any primitive type is cast to time, the
    time value TV is derived from the source type
    ST and the source value SV as follows:
If ST is time, then TV is
        SV.
If ST is dateTime, then TV is
        xs:time( fn:concat( cast as
        string( fn:get-hour( SV
        ) ), ':', cast as string( fn:get-minute( SV ) ),
        ':', cast as string( fn:get-second( SV ) ) )
        ).
If ST is string or a type derived from
        string and SV is a valid lexical representation
        for time as specified in [XML Schema
        Part 2: Datatypes], then TV is xs:time(
        SV ).
When a value of any primitive type is cast to date, the
    date value TV is derived from the source type
    ST and the source value SV as follows:
If ST is dateTime, then let SYR
        be cast as string( fn:get-Year( SV )
        ), let SMO be cast as string( fn:get-month( SV )
        ), and let SDA be cast as string( fn:get-day( SV )
        ); TV is xs:dateTime( fn:concat( SYR , '-',
         SMO , '-',  SDA )
        ).
If ST is date, then TV is
        SV.
If ST is string or a type derived from
        string and SV is not a valid lexical
        representation for date as specified in [XML Schema Part 2: Datatypes], then an error is
        raised ("Invalid lexical value").
If ST is string or a type derived from
        string and SV is a valid lexical representation
        for date as specified in [XML Schema
        Part 2: Datatypes], then TV is xs:date(
        SV ).
When a value of any primitive type is cast to
    gYearMonth, the gYearMonth value TV is
    derived from the source type ST and the source value SV
    as follows:
If ST is gYearMonth, then TV is
        SV.
If ST is string or a type derived from
        string and SV is not a valid lexical
        representation for gYearMonth as specified in [XML Schema Part 2: Datatypes], then an error is
        raised ("Invalid lexical value").
If ST is string or a type derived from
        string and SV is a valid lexical representation
        for gYearMonth as specified in [XML
        Schema Part 2: Datatypes], then TV is
        xs:date( SV ).
When a value of any primitive type is cast to gYear,
    the gYear value TV is derived from the source type
    ST and the source value SV as follows:
If ST is gYear, then TV is
        SV.
If ST is string or a type derived from
        string and SV is not a valid lexical
        representation for gYear as specified in [XML Schema Part 2: Datatypes], then an error is
        raised ("Invalid lexical value").
If ST is string or a type derived from
        string and SV is a valid lexical representation
        for gYear as specified in [XML Schema
        Part 2: Datatypes], then TV is xs:date(
        SV ).
When a value of any primitive type is cast to
    gMonthDay, the gMonthDay value TV is
    derived from the source type ST and the source value SV
    as follows:
If ST is gMonthDay, then TV is
        SV.
If ST is string or a type derived from
        string and SV is not a valid lexical
        representation for gMonthDay as specified in [XML Schema Part 2: Datatypes], then an error is
        raised ("Invalid lexical value").
If ST is string or a type derived from
        string and SV is a valid lexical representation
        for gMonthDay as specified in [XML
        Schema Part 2: Datatypes], then TV is
        xs:date( SV ).
When a value of any primitive type is cast to gDay, the
    gDay value TV is derived from the source type
    ST and the source value SV as follows:
If ST is gDay, then TV is
        SV.
If ST is string or a type derived from
        string and SV is not a valid lexical
        representation for gDay as specified in [XML Schema Part 2: Datatypes], then an error is
        raised ("Invalid lexical value").
If ST is string or a type derived from
        string and SV is a valid lexical representation
        for gDay as specified in [XML Schema
        Part 2: Datatypes], then TV is xs:date(
        SV ).
When a value of any primitive type is cast to gMonth,
    the gMonth value TV is derived from the source type
    ST and the source value SV as follows:
If ST is gMonth, then TV is
        SV.
If ST is string or a type derived from
        string and SV is not a valid lexical
        representation for gMonth as specified in [XML Schema Part 2: Datatypes], then an error is
        raised ("Invalid lexical value").
If ST is string or a type derived from
        string and SV is a valid lexical representation
        for gMonth as specified in [XML
        Schema Part 2: Datatypes], then TV is
        xs:date( SV ).
When a value of any primitive type is cast to boolean, the
boolean value TV is derived from the source type
ST and the source value SV as follows:
If ST is string and has
    value " true " or " 1 ", then
    TV is true; if ST is string
    and has value
    " false " or "
    0 ", then TV is false.
If ST is float, double, or
    decimal and SV is 0, +0, -0, or NaN, then
    TV is false.
If ST is float, double, or
    decimal and SV is not one of the above values, then
    TV is true.
If ST is boolean, then TV is
    SV.
If ST is base64Binary or
    hexBinary and SV is " 1 ", then
    TV is true; if ST is
    base64Binary or hexBinary and SV is "
    0 ", then TV is false.
Otherwise, an error is raised ("Invalid lexical value").
Casting       to base64Binary and hexBinary is
supported only from string
or anySimpleType.
Casting to anyURI   is possible only from the same type or
possibly from string or subtypes of
string.
When a value of any primitive type is cast to anyURI, the
anyURI value TV is derived from the source type
ST and the source value SV as follows:
If ST is string ora
    subtype of  string and SV conforms to the
    format of a Uniform Resource Identifier Reference as specified in [XML Schema Part 2: Datatypes], then TV is
    SV.
Otherwise, an error is raised ("Invalid lexical value").
This appendix summarizes the relationship between certain functions defined in [XPath 1.0] and the corresponding functions defined in this document. The first column of the table provides the signature of functions defined in this document, while the second column provides the signature of the corresponding function in [XPath 1.0]. The third column records issues concerning the relationship between the corresponding functions.
| XQuery 1.0 and XPath 2.0 | XPath 1.0 | Issues | 
|---|---|---|
| fn:node-name($srcval as node) as QName? | name(node-set?) =>
      string | XPath 1.0 function retained to provide compatibility. | 
| fn:string() as string | class="diff-chg"string(object) =>
      string | The string representation of double values is not backwards-compatible. When multiple items are supplied, an error ("type exception") is raised, with fall-back of first node, for XPath 1.0 compatibility. | 
fn:string($srcval as item*) as stringfn:floor($srcval as double?) as double?fn:ceiling($srcval as double?) as double?ceiling(number)=> numberfn:round($srcval as double?) as double?round(number)=> numberfn:concat() as stringconcat(string, string, string*) =>
    stringfn:concat($op1 as string?) as stringfn:concat($op1 as string?, $op2 as string?, ...) as stringfn:starts-with($operand1 as string?, $operand2 as string?) as boolean?starts-with(string, string) =>
    boolean| fn:starts-with( | $operand1 |  as string?, | 
| $operand2 |  as string?, | |
| $collationLiteral |  as anyURI) as boolean? | 
fn:contains($operand1 as string?, $operand2 as string?) as boolean?contains(string, string) =>
    boolean| fn:contains( | $operand1 |  as string?, | 
| $operand2 |  as string?, | |
| $collationLiteral |  as anyURI) as boolean? | 
fn:substring($sourceString as string?, $startingLoc as double?) as string?substring(string, number, number?) =>
    string| fn:substring( | $sourceString |  as string?, | 
| $startingLoc |  as double?, | |
| $length |  as double?) as string? | 
fn:string-length($srcval as string?) as integer?string-length(string?) =>
  numberfn:substring-before($operand1 as string?, $operand2 as string?) as string?substring-before(string, string) =>
    string| fn:substring-before( | $operand1 |  as string?, | 
| $operand2 |  as string?, | |
| $collationLiteral |  as anyURI) as string? | 
fn:substring-after($operand1 as string?, $operand2 as string?) as string?substring-after(string, string) =>
    string| fn:substring-after( | $operand1 |  as string?, | 
| $operand2 |  as string?, | |
| $collationLiteral |  as anyURI) as string? | 
fn:normalize-space($srcval as string?) as string?normalize-space(string?) =>
    string| fn:translate( | $srcval |  as string?, | 
| $mapString |  as string?, | |
| $transString |  as string?) as string? | 
translate(string, string, string)=>
    stringfn:true() as booleantrue() => booleanfn:false() as booleanfalse() => booleanfn:not($srcval as item*?) as booleannot(boolean) => booleanfn:namespace-uri() as stringnamespace-uri(node-set?) =>
    stringfn:namespace-uri($srcval as string*) as stringfn:name() as stringname(node-set?) => stringfn:name($srcval as string*) as stringfn:local-name() as stringlocal-name(node-set?) =>
  stringfn:local-name($srcval as node) as stringfn:number() as doublenumber(object?) => numberfn:number($srcval as node) as doublefn:lang($testlang as string) as booleanlang(strong) => booleanfn:count($srcval as item*?) as unsignedIntcount(node-set) => numberfn:sum($srcval as item*?) as doublesum(node-set) => numberfn:id($srcval as string*?) as element*?id(object) => node-setfn:document($srcval1 as anyURI*?, $srcval2 as node*?) as node*?document(object, node-set?) =>
    node-setfn:position() as unsignedIntposition()fn:last() as unsignedIntlast() => numberCertain functions that were proposed for inclusion in this function library have been excluded on the basis that it is straightforward for users to implement these functions themselves using XSLT 2.0 or XQuery 1.0.
This Appendix provides sample implementations of these functions.
To emphasize that these functions are examples of functions that vendors may write, their names carry the prefix 'eg'. Vendors are free to define such functions in any namespace. A group of vendors may also choose to create a collection of such useful functions and put them in a common namespace.
eg:if-empty($node as node?, $value as anySimpleType) as anySimpleType*If the first argument is the empty sequence or an element withput simple or complex content, if-empty() returns the second argument; otherwise, it returns the content of the first argument.
XSLT implementation
<xsl:function name="eg:if-empty">
  <xsl:param name="node" type="node?"/>
  <xsl:param name="value" type="xs:anySimpleType"/>
  <xsl:result type="xs:anySimpleType*"
    select="if ($node and $node/child::node())
            then fn:data($node)
            else $value"/>
</xsl:function>
XQuery implementation
define function eg:if-empty (
  node? $node,
  anySimpleType $value ) 
returns xs:anySimpleType* {
  if ($node and $node/child::node())
            then fn:data($node)
            else $value"
}
eg:if-absent($node as node?, $value as anySimpleType) as anySimpleType*If the first argument is the empty sequence, if-absent() returns the second argument; otherwise, it returns the content of the first argument.
XSLT implementation
<xsl:function name="eg:if-absent">
  <xsl:param name="node" type="node?"/>
  <xsl:param name="value" type="xs:anySimpleType"/>
  <xsl:result type="xs:anySimpleType*"
    select="if ($node)
            then fn:data($node)
            else $value"/>
</xsl:function>
XQuery implementation
define function eg:if-absent (
  node? $node,
  anySimpleType $value ) 
returns xs:anySimpleType* {
  if ($node)
    then fn:data($node)
    else $value"
}
eg:value-union($operand1 as item*, $operand2 as item*) as item*This function returns a sequence containing all the distinct items in $operand1 and $operand2, in an undefined order.
XSLT implementation
<xsl:function name="eg:value-union">
  <xsl:param name="operand1" type="item*"/>
  <xsl:param name="operand2" type="item*"/>
  <xsl:result type="item*"
     select="fn:distinct-values(($operand1, $operand2))"/> </xsl:function>
XQuery implementation
define function eg:value-union (
  item* $operand1,
  item* $operand2 )
returns item* {
  fn:distinct-values(($operand1, $operand2))
}
eg:value-intersect($operand1 as item*, $operand2 as item*) as item*This function returns a sequence containing all the distinct items that appear in both $operand1 and $operand2, in undefined order.
XSLT implementation>
<xsl:function name="eg:value-intersect">
  <xsl:param name="operand1" type="item*"/>
  <xsl:param name="operand2" type="item*"/>
  <xsl:result type="item*"
     select="fn:distinct-values($operand1[.=$operand2])"/>
</xsl:function>
XQuery implementation
define function eg:value-intersect (
  item* $operand1,
  item* $operand2 )
returns item* {
  fn:distinct-values($operand1[.=$operand2])
}
eg:value-except($operand1 as item*, $operand2 as item*) as item*This function returns a sequence containing all the distinct items that appear in $operand1 but not in $operand2, in undefined order.
XSLT implementation
<xsl:function name="eg:value-except">
  <xsl:param name="operand1" type="item*"/>
  <xsl:param name="operand2" type="item*"/>
  <xsl:result type="item*"
     select="fn:distinct-values($operand1[not(.=$operand2)])"/>
</xsl:function>
XQuery implementation
define function eg:value-except (
  item* $operand1,
  item* $operand2 )
returns item* {
  fn:distinct-values($operand1[not(.=$operand2)])
}
This appendix contains the current issues related to the operators specification.
| Originator: | Operators Task Force F2F 2001-03-21 | 
| Locus: | Syntax | 
What is the precise type returned by various functions? Is the specific type of the argument the returned type, or does it get "upcast" to "string"? Some operations might not be able to keep the most specific type (e.g., SUBSTRING(NCNAME,2) may not be a NCNAME!)
Resolution:
None recorded.
This issue occurs in 6.4 Functions on String Values
| Originator: | Michael Sperberg-McQueen | 
| Locus: | Syntax | 
In a presentation at the July, 2001 F2F, it was said that collations would be referred to by URI references. Michael Rys said one rationale is to allow relative URI(-reference)s so one can refer to "French" rather than http://www.example.com/i18n/collation-sequences/case-sensitive/French, and so on. There may be negative impacts on the interoperability results caused by allowing relative URI referneces for this function. It is tempting to suggest requiring collation names to be absolute URIs without fragment identifiers. If brevity is really important, perhaps we should invent a way to assign short names to collations. See, also, issue 70.
Issue resulted from e-mail: Michael Sperberg-McQueen (member-only message)
Resolution:
None recorded.
This issue occurs in 6.3 Equality and Comparison of Strings
| Originator: | Michael Kay | 
| Locus: | Syntax | 
index-of. Need find-by-value and find-by-identity. Currently index-of takes a sequence of nodes *or* valies. Do we need to change this?
Issue resulted from e-mail: Michael Kay (member-only message)
Resolution:
None recorded.
This issue occurs in 14.2 Functions and Operators on Sequences
| Originator: | Andrew Eisenberg | 
| Locus: | Syntax | 
I believe that we should have an fn:compare-between function (analogous to SQL's BETWEEN predicate, allowing quick determination of whether one value lies between two other values).
Issue resulted from e-mail: Andrew Eisenberg (member-only message)
Resolution:
None recorded.
This issue occurs in 6.3 Equality and Comparison of Strings
| Originator: | Steve Tolkin | 
| Locus: | Syntax | 
The fn:numeric-mod() function, the
div operator, and others do not specify what the required number
of digits of precision is in the result.
Resolution:
The resolution depends on (1)how many digits Schema supports for decimals, and (2)what Functions and Operators does about overflow.
This issue occurs in 5.4 Functions on Numeric Values
| Originator: | Phil Wadler (member-only message) | 
| Locus: | Syntax | 
Functions with AnyType in the return are problematic for two reasons. To be concrete, I discuss the following.
-- fn:item-at(anyType* $seqParam, decimal $posParam) => anyType
(1) Note that the types anyType* and anyType are equivalent, which suggests that the typing here is not quite right. We should define
-- define group AnyItem = AnyElement | AnyAttribute | AnySimpleType
and then give the above the type
-- fn:item-at(anyItem* $seqParam, decimal $posParam) => anyItem
(2) Even having made the above change, the type is too broad to be useful, and one will almost always have to cast the result of calling fn:item-at (and similarly for other functions with anyItem or anyType in the result).
Instead, we should allow parametric polymorphism when specifying the signatures of built-in functions.
-- fn:item-at($anyItem* $seqParam, decimal $posParam) => $anyItem
Here $anyItem is a type variable which ranges over any group $anyItem such that $anyItem <: AnyItem. (Recall that s <: t if the extent of type s is a subset of the extent of type t, where the extent of a type is the set of values that have that type.)
Here are two examples of functions written with the current signature.
-- define function second-integer (integer* $integer-sequence) integer { treat as integer (fn:item($integer-sequence, 2)) }
-- define function third-book (Book* $book-sequence) book { treat as Book (fn:item($book-sequence, 3)) }
Here are two examples of functions that would type check under this scheme.
-- define function second-integer (integer* $integer-sequence) integer { fn:item($integer-sequence, 2) }
-- define function third-book (Book* $book-sequence) book { fn:item($book-sequence, 3) }
The definitions are easier to write and more efficient to execute (since no "treat as" needs to check the structure of the result).
Parametric polymorphism would also be useful for user-defined functions, it were clear how to define it for user-defined functions in general. But at the very least, we should allow parametric polymorphism for the built-in functions defined in the functions and operators document.
Resolution:
This issue occurs in 14 Functions and Operators on Sequences
| Originator: | (member-only message) Anders Berglund. | 
| Locus: | Syntax | 
Should we have functions that convert a date/time time value from one timezone to another? If the original value has no timezone, the timezone is added. If it has a timezone, the value is changed to conform to the specified timezone. Perhaps an alternate signature takes a timezone delta.
Resolution:
This issue occurs in 8 Functions and Operators on Durations, Dates, and Times
| Originator: | (member-only message) Minutes of December 5, 2001 meeting. | 
| Locus: | Syntax | 
What do floor, ceiling and round return? The document says integer. But NaN and the empty sequnce are allowed. Should they return the same type as their operand (without a fractional part)? This allows them to operate on numbers larger than a decimal or integer can accomodate.
See related issue at [Issue 179: What is the appropriate return type for fn:floor, fn:celing, and fn:round?]
Resolution:
This issue occurs in 5.4 Functions on Numeric Values,
| Originator: | (member-only message) Minutes of December 5, 2001 meeting. | 
| Locus: | Syntax | 
Should the concat function accept sequences as arguments? Should sequences of strings be flattened? Should string-values be used if the items in the sequence are not strings?
Resolution:
This issue occurs in 6.4.1 fn:concat
| Originator: | Andrew Eisenberg. (member-only message) | 
| Locus: | Syntax | 
For fractional seconds precision we should choose a limit that matched SQL's TIMESTAMP data type, which is 6 digits of fractional seconds precision.
Resolution:
This issue occurs in 8.1 Duration, Date, and Time Types
| Originator: Andrew Eisenberg | Email 2002-04-18 (member-only message) | 
| Locus: | Syntax | 
In the description of some functions it is possible to justify more than one result for an invocation. Rules to disambiguate these situations are necessary.
For example, for the function invocation fn:normalize-unicode ( (), "NFANDREW"),
there are rules in the specification that justify returning either () or
error. Such ambiguities must be resolved.
Resolution:
This issue is not referenced!
| Originator: Functions and Operators Task Force | Email 2002-06-26 (member-only message) | 
| Locus: | Syntax | 
The expression currently alllows implementations to provide extensions to the regular expression syntax. Some participants would prefer a stricter conformance requirement than this.
Resolution:
This issue occurs in 6.4.16.1 Regular Expression Syntax
| Originator: | Ashok Malhotra (member-only message) | 
| Locus: | Syntax | 
There is precedence in XSLT for not always reporting overflow and underflow resulting from multiplication and division. Should this specification require that such errors always be reported or should it be more permissive, perhaps using XSLT as a guide?
Resolution:
This issue occurs in 5.2 Operators on Numeric Values,
| Originator: | |
| Locus: | Syntax | 
The signatures of the fn:floor and fn:ceiling functions ("integer | double") are not valid SequenceTypes. One of the following should be done: (Solution 1) Make fn:floor, fn:ceiling, and fn:round return integers. You call these functions to get an integer. If the argument is NaN or infinity, an error is raised. (Solution 2) Make these functions return the same type as their argument. The signature and return type should be listed as "numeric", meaning it accepts any numeric type and returns the same type. In this case, an argument of NaN or infinity should still raise an error. (What does the floor of infinity mean??). There appears to be inclination towards Solution 2, but the final decision has not yet been made.
See related issue at [Issue 142: Should floor ceiling and round return the same type as their argument? ].
Resolution:
This issue occurs in 5.4 Functions on Numeric Values,
| Originator: | Functions & Operators editorial team | 
| Locus: | Syntax | 
We now have an fn:error function that is implicitly invoked by our specs and possibly even explicitly by XQuery applications. However, the precise semantics of this function are not at all clear.
Resolution:
This issue occurs in 3 The Error Function
| Originator: Item 4 in | Don Chamberlin (member-only message) | 
| Locus:class="diff-add" | Syntax | 
Resolution:
Don says: I suggest deleting this function, since we do not in general know how to decide whether two durations are equal. I think an "equal" function that returns False when comparing 24 hours with 1 day does more harm than good.
This issue occurs in , 8.3.1 op:duration-equal
| Originator: Item 3 in | Ashok Malhotra (member-only message) | 
| Locus:class="diff-add" | Syntax | 
Resolution:
The issue of whether the original timezone in the lexical form of date/time values is under discussion. This issue as added to track it's progress.
This issue occurs in , 8.3 Comparisons of Duration, Date and Time Values
| Originator: Michael Rys | Minutes of 11/6 telcon (member-only message) | 
| Locus:class="diff-add" | Syntax | 
Resolution:
What are the semantics of handling untyped values in min, max and other aggregate functions.
This issue occurs in 14.4 Aggregate Functions
This appendix tracks gross changes in the document; it is not intended to provide a fine-grained revision history.
06-Nov-2002 (AM) Added issue on the treatment of untyped values in aggregate functions. Minutes of 11/6 telcon.
06-Nov-2002 (AM) Aligned the semantics of passing parameters to function calls with Appendix B of XQuery using the terms subtype substitution and type promotion. Minutes of 11/6 telcon.
29-Oct-2002 (AM) Closed issue 47 (operator-datetime-internationalization). Added note as recommended in (member-only message) http://lists.w3.org/Archives/Member/w3c-query-operators/2002Sep/0140.html and agreed to in 10/17 meeting.
26-Oct-2002 (AM) Added note to fn:substring(), fn:string-length and fn:translate re. surrogate pairs based on MHK note to XSL WG on 10/24.
25-Oct-2002 (AM) Added text to collection() and input() to say that these functions yield the same result if executed repeatedly within a XQuery or XPath. As approved by the WGs on 10/17.
25-Oct-2002 (AM) Rewrote the aggregate functions to bring them in line with the Consolidation Proposal as approved by the WGs on 10/17.
25-Oct-2002 (AM) Added issue 186 preserve-timezone as requested in taskforce in telcon on 10/24.
25-Oct-2002 (AM) Added issue 185 remove-duration-equal as requested by Don Chamberlin and approved by taskforce in telcon on 10/24.
24-Oct-2002 (AM) Made changes to fn:name and added functions xf:get-in-scope-namespaces() and xf:get-namespace-uri-for-prefix() based on proposal by Mike Kay: http://lists.w3.org/Archives/Member/w3c-xml-query-wg/2002Oct/0206.html. WGs approved on 10/18.
24-Oct-2002 (AM) Made changes to fn:string(), fn:not(), fn:number(), fn:boolean() based on Consolidation Proposal 3.2 http://lists.w3.org/Archives/Member/w3c-query-editors/2002Oct/0051.html.15. WGs approved on 10/17.
24-Oct-2002 (AM) Added functions to create a string from codepoints and vice-versa. Closed issue 77 (operator-string-from-char). Taskforce agreed to close on 10/15. WGs approved on 10/17.
24-Oct-2002 (AM) Added fn:unordered() as approved in the joint WGs meeting on 10/18.
24-Oct-2002 (AM) Closed issue 122 (operators-namespaces-in-scope). The term "namespaces in scope" does not appear in the document. Taskforce agreed to close on 10/15. WGs approved on 10/17.
23-Oct-2002 (AM) Closed issue 145(need-to-specify-resource-limits) ). Taskforce agreed to close on 10/15 by asking the language documents to add text as suggested in (member-only message) http://lists.w3.org/Archives/Member/w3c-query-operators/2002Sep/0133.html. Note send to query-editors on 10/23. WGs approved on 10/17.
23-Oct-2002 (AM) Closed issue 122(operators-namespaces-in-scope) ). The term "namespaces in scope" does not appear in the document. Taskforce agreed to close on 10/15. WGs approved on 10/17.
23-Oct-2002 (AM) Closed issue 155 (Define-if-empty) ). Since if-empty and if-absent now moved to Appendix, term does not appear in the document. Taskforce agreed to close on 10/15. WGs approved on 10/17.
23-Oct-2002 (AM) Closed issue 170 (Need-note-on-capability-of-collations) ). Note added to section 6.2 based on (member-only message) http://lists.w3.org/Archives/Member/w3c-query-operators/2002Oct/0078.html. Taskforce agreed to close on 10/15 if note was added. WGs approved on 10/17.
23-Oct-2002 (AM) Closed issue 182 (raise-predefined-error-values). Taskforce voted to close on 10/15 and WGs approved on 10/17. Few words of text added whenever raising an error is mentioned.
23-Oct-2002 (AM) Closed issue 108 (operators-always-normalize). Taskforce voted to close on 10/15 and WGs approved on 10/17. We mention that some functions can return non-normalized strings. Also the I18N has softened its position on this issue.
23-Oct-2002 (AM) Closed issue 160 (align-string-function-with-cast). The xs:string() constructor and 'cast xxx as xs:string' have identical semantics. fn:string() is retained for XPath 1.0 compatibility. FandO taskforce voted to close on 10/15 and agreed to at 10/17 joint XSL/XML Query meeting.
23-Oct-2002 (AM) Closed issue 109 (operators-calendar-context). Withdrawn by originator. FandO taskforce voted to close on 10/15 and agreed to at 10/17 joint XSL/XML Query meeting.
23-Oct-2002 (AM) Closed issue 110 (operators-timezone-empty-sequence) ) as recommended by the FandO taskforce on 10/15 and agreed to at 10/17 joint XSL/XML Query meeting. Overtaken by events. Timezones are now returned as dayTimeDurations.
23-Oct-2002 (AM) Closed issue 84 (operator-cast-to-token) as recommended by the FandO taskforce on 10/15 and agreed to at 10/17 joint XSL/XML Query meeting.
23-Oct-2002 (AM) Closed issue 83 (operator-cast-table-structure) as recommended by the FandO taskforce on 10/15 and agreed to at 10/17 joint XSL/XML Query meeting.
23-Oct-2002 (AM) Closed issue 168 (should-id-take-a-list-of-strings) as recommended by the FandO taskforce on 10/15 and agreed to at 10/17 joint XSL/XML Query meeting. fn:id() function has been fixed to be compatible with XPath 1.0.
23-Oct-2002 (AM) Closed issue 152 (parameterized-extraction-functions-for-date-and-times) as recommended by the FandO taskforce on 10/15 and agreed to at 10/17 joint XSL/XML Query meeting.
23-Oct-2002 (AM) Closed issue 20 (operator-codepoint-vs-character). Added note as recommended in (member-only message) http://lists.w3.org/Archives/Member/w3c-query-operators/2002Sep/0140.html and agreed to in 10/17 meeting.
22-Oct-2002 (AM) Added fn:default-collation and fn:implicit-timezone() functions as agreed to in 10/17 meeting.
22-Oct-2002 (AM) Added fn:string-join() function as agreed to in 10/17 meeting.
22-Oct-2002 (AM) Added fn:base-uri() with no argument to return the base uri from the static context. As agreed to in 10/17 meeting.
22-Oct-2002 (AM) Changed fn:expanded-QName to QName-in-context according to MHK proposal of 10/7. As agreed to in 10/17 meeting.
22-Oct-2002 (AM) Changed fn:substring to align with XPath 1.0 function. As agreed to in 10/17 meeting.
20-Oct-2002 (AM) Expanded casting table with rows and columns for anySimpleType, yearMonthDuration and dayTimeDuration.
20-Oct-2002 (AM) Added sections on constructing and casting to user-defined types. As agreed to in 10/17 meeting.
18-Oct-2002 (AM) Changed function prefix to fn: from xf:. As agreed to in 10/17 meeting.
17-Oct-2002 (AM) Restricted legal string values to boolean casting and constructor to 0,1,true, false to bring in line with schema semnatics. As decided in 10/17 meeting.
17-Oct-2002 (AM) Added fn:error function with no arguments. As decided in 10/17 meeting.
17-Oct-2002 (AM) Removed special note on string function re. decimal values with no fractional part. As decided in 10/17 meeting.
08-Oct-2002 (AM) Removed if-absent and if-empty functions and put sample implenmentations in Appendix D. As decided 8/1 in Redmond. Closed two issues on these functions: Issue 171 Do-we-need-if-empty-and-if-absent and Issue 183 if-absent-static-typing.
08-Oct-2002 (AM) Added value-except, value-union and value-intersect to Appendix D.
26-Sep-2002 (AM) Opened and closed issue on changing function signatures for 7 functions from decimal to integer now that integer is available as primitive. Proposal by MHK approved by FandO 9-12-2002.
25-Sep-2002 (AM) Closed issue 23 "operator-copy-returns" as per mail 9/13.
25-Sep-2002 (AM) Closed issue 48 "operator-datetime-suntime" as per mail 9/13.
25-Sep-2002 (AM) Closed issue 60 "operator-copy-semantics" as per mail 9/13. Removed the xf:copy() function.
25-Sep-2002 (AM) Closed issue 64 "operator-generic-reverse" as per mail 9/13.
25-Sep-2002 (AM) Closed issue 66 "operator-docorder-function" as per mail 9/13.
25-Sep-2002 (AM) Closed issue 82 "operator-nodeset-list-sequence" as per mail 9/13.
25-Sep-2002 (AM) Closed issue 157 "boolean-from-string-legal-literals" as per mail 9/13.
25-Sep-2002 (AM) Closed issue 118 "operators-string-nonscalar-error" as per mail 9/13.
25-Sep-2002 (AM) Closed issue 154 "second-order-distinct-function" as per mail 9/13.
25-Sep-2002 (AM) Allowed xf:root() to be called without an argument and closed issue 162 "can-the-node-parameter-to-root-be-omitted" as per mail 9/13.
25-Sep-2002 (AM) Created appendicies to hold requirements for future versions and example functions.
25-Sep-2002 (AM) Changed the decimal operands of xf:substring, xf:string-pad, xf:item-at, xf:insert, xf:remove, xf:subsequence, op:to to integer as per mail 9/13.
25-Sep-2002 (AM) Changed xf:resolve-uri as per MHK proposal http://lists.w3.org/Archives/Member/w3c-query-operators/2002Aug/0022.html as approved per mail 9/13.
23-Aug-2002 (AM) Changed section 1.5 to include material that constructors use XML Schema namespace.
23-Aug-2002 (AM) Changed section 16.10 and the casting table to allow casting from string and anySimpleType to base64Binary and hexBinary.
23-Aug-2002 (AM) Changed names of get-dayTimeDuration-from-dateTime and get-yearMonthDuration-from-dateTimes to subtract-dateTimes-yielding-dayTimeDuration and subtract-dateTimes-yielding-yearMonthDuration. See Sept archives.
fn:substring-before($operand1 as string?,
            $operand2 as string?,
            $collationLiteral as anyURI) as string?fn:substring-after($operand1 as string?,
            $operand2 as string?,
            $collationLiteral as anyURI) as string?fn:replace($input as string?,
            $pattern as string?,
            $replacement as string?,
            $flags as string?) as string?op:yearMonthDuration-equal($operand1 as yearMonthDuration,
            $operand2 as yearMonthDuration) as booleanop:yearMonthDuration-less-than($operand1 as yearMonthDuration,
            $operand2 as yearMonthDuration) as booleanop:yearMonthDuration-greater-than($operand1 as yearMonthDuration,
            $operand2 as yearMonthDuration) as booleanop:dayTimeDuration-greater-than($operand1 as dayTimeDuration,
            $operand2 as dayTimeDuration) as booleanop:add-yearMonthDurations($srcval1 as yearMonthDuration,
            $srcval2 as yearMonthDuration) as yearMonthDurationop:subtract-yearMonthDurations($srcval1 as yearMonthDuration,
            $srcval2 as yearMonthDuration) as yearMonthDurationop:multiply-yearMonthDuration($srcval1 as yearMonthDuration,
            $srcval2 as decimal) as yearMonthDurationop:divide-yearMonthDuration($srcval1 as yearMonthDuration,
            $srcval2 as decimal) as yearMonthDurationop:add-dayTimeDurations($srcval1 as dayTimeDuration,
            $srcval2 as dayTimeDuration) as dayTimeDurationop:subtract-dayTimeDurations($srcval1 as dayTimeDuration,
            $srcval2 as dayTimeDuration) as dayTimeDurationfn:subtract-dateTimes-yielding-yearMonthDuration($srcval1 as dateTime,
            $srcval2 as dateTime) as yearMonthDurationfn:subtract-dateTimes-yielding-dayTimeDuration($srcval1 as dateTime,
            $srcval2 as dateTime) as dayTimeDurationop:add-yearMonthDuration-to-dateTime($srcval1 as dateTime,
            $srcval2 as yearMonthDuration) as dateTimeop:subtract-yearMonthDuration-from-dateTime($srcval1 as dateTime,
            $srcval2 as yearMonthDuration) as dateTimeop:subtract-dayTimeDuration-from-dateTime($srcval1 as dateTime,
            $srcval2 as dayTimeDuration) as dateTimefn:sequence-deep-equal($parameter1 as item*,
            $parameter2 as item*,
            $collationLiteral as anyURI) as boolean?op:add-dayTimeDurations($srcval1 as dayTimeDuration,
$srcval2 as dayTimeDuration) as dayTimeDurationop:add-yearMonthDuration-to-dateTime($srcval1 as dateTime,
$srcval2 as yearMonthDuration) as dateTimeop:add-yearMonthDurations($srcval1 as yearMonthDuration,
$srcval2 as yearMonthDuration) as yearMonthDurationop:dayTimeDuration-greater-than($operand1 as dayTimeDuration,
$operand2 as dayTimeDuration) as booleanop:divide-yearMonthDuration($srcval1 as yearMonthDuration,
$srcval2 as decimal) as yearMonthDurationop:multiply-yearMonthDuration($srcval1 as yearMonthDuration,
$srcval2 as decimal) as yearMonthDurationfn:replace($input as string?,
$pattern as string?,
$replacement as string?,
$flags as string?) as string?fn:sequence-deep-equal($parameter1 as item*,
$parameter2 as item*,
$collationLiteral as anyURI) as boolean?fn:substring-after($operand1 as string?,
$operand2 as string?,
$collationLiteral as anyURI) as string?fn:substring-after($operand1 as string?,
$operand2 as string?,
$collationLiteral as anyURI) as string?fn:substring-before($operand1 as string?,
$operand2 as string?,
$collationLiteral as anyURI) as string?fn:substring-before($operand1 as string?,
$operand2 as string?,
$collationLiteral as anyURI) as string?fn:subtract-dateTimes-yielding-dayTimeDuration($srcval1 as dateTime,
$srcval2 as dateTime) as dayTimeDurationfn:subtract-dateTimes-yielding-yearMonthDuration($srcval1 as dateTime,
$srcval2 as dateTime) as yearMonthDurationop:subtract-dayTimeDuration-from-dateTime($srcval1 as dateTime,
$srcval2 as dayTimeDuration) as dateTimeop:subtract-dayTimeDurations($srcval1 as dayTimeDuration,
$srcval2 as dayTimeDuration) as dayTimeDurationop:subtract-yearMonthDuration-from-dateTime($srcval1 as dateTime,
$srcval2 as yearMonthDuration) as dateTimeop:subtract-yearMonthDurations($srcval1 as yearMonthDuration,
$srcval2 as yearMonthDuration) as yearMonthDurationop:yearMonthDuration-equal($operand1 as yearMonthDuration,
$operand2 as yearMonthDuration) as booleanop:yearMonthDuration-greater-than($operand1 as yearMonthDuration,
$operand2 as yearMonthDuration) as booleanop:yearMonthDuration-less-than($operand1 as yearMonthDuration,
$operand2 as yearMonthDuration) as boolean