<!--XSLT Processor: Saxonica SAXON HE 9.6.0.7--><!--DO NOT EDIT: GENERATED BY merge-function-specs.xsl--><!--DO NOT EDIT: GENERATED BY merge-function-specs.xsl--><!--DO NOT EDIT: GENERATED BY merge-function-specs.xsl--><!--DO NOT EDIT: GENERATED BY merge-function-specs.xsl--><!--DO NOT EDIT: GENERATED BY merge-function-specs.xsl--><!--DO NOT EDIT: GENERATED BY merge-function-specs.xsl--><!--DO NOT EDIT: GENERATED BY merge-function-specs.xsl--><!--DO NOT EDIT: GENERATED BY merge-function-specs.xsl--><!--DO NOT EDIT: GENERATED BY merge-function-specs.xsl--><!--DO NOT EDIT: GENERATED BY merge-function-specs.xsl--><!--DO NOT EDIT: GENERATED BY merge-function-specs.xsl--><!--DO NOT EDIT: GENERATED BY merge-function-specs.xsl--><!--DO NOT EDIT: GENERATED BY merge-function-specs.xsl--><!--DO NOT EDIT: GENERATED BY merge-function-specs.xsl--><!--DO NOT EDIT: GENERATED BY merge-function-specs.xsl--><!--DO NOT EDIT: GENERATED BY merge-function-specs.xsl--><!--DO NOT EDIT: GENERATED BY merge-function-specs.xsl--><!--DO NOT EDIT: GENERATED BY merge-function-specs.xsl--><!--DO NOT EDIT: GENERATED BY merge-function-specs.xsl--><!--DO NOT EDIT: GENERATED BY merge-function-specs.xsl--><spec xmlns:e="http://www.w3.org/1999/XSL/Spec/ElementSyntax" id="spec-top" w3c-doctype="rec" status="ext-review"><header><title>XPath and XQuery Functions and Operators 3.1</title><version/><w3c-designation>REC-xpath-functions-31</w3c-designation><w3c-doctype>W3C Recommendation</w3c-doctype><pubdate><day>21</day><month>March</month><year>2017</year></pubdate><publoc>
            <loc xmlns:xlink="http://www.w3.org/1999/xlink" href="https://www.w3.org/TR/2017/REC-xpath-functions-31-20170321/" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">https://www.w3.org/TR/2017/REC-xpath-functions-31-20170321/</loc>
        </publoc><altlocs><loc xmlns:xlink="http://www.w3.org/1999/xlink" href="https://www.w3.org/TR/2017/REC-xpath-functions-31-20170321/xpath-functions-31.xml" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">Specification in XML format using HTML5 vocabulary</loc><loc xmlns:xlink="http://www.w3.org/1999/xlink" href="https://www.w3.org/TR/2017/REC-xpath-functions-31-20170321/function-catalog.xml" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">XML function catalog</loc><loc xmlns:xlink="http://www.w3.org/1999/xlink" href="https://www.w3.org/TR/2017/REC-xpath-functions-31-20170321/xpath-functions-31-diff.html" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">HTML with change markings relative to version 3.0</loc></altlocs><latestloc doc="XPath and XQuery Functions and Operators 3.1">
            <loc xmlns:xlink="http://www.w3.org/1999/xlink" href="https://www.w3.org/TR/xpath-functions-31/" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">https://www.w3.org/TR/xpath-functions-31/</loc>
        </latestloc><prevlocs doc="XPath and XQuery Functions and Operators 3.1">
           <loc xmlns:xlink="http://www.w3.org/1999/xlink" href="https://www.w3.org/TR/2017/PR-xpath-functions-31-20170117/" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">https://www.w3.org/TR/2017/PR-xpath-functions-31-20170117/</loc>
           <loc xmlns:xlink="http://www.w3.org/1999/xlink" href="https://www.w3.org/TR/2016/CR-xpath-functions-31-20161213/" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">https://www.w3.org/TR/2016/CR-xpath-functions-31-20161213/</loc>
           <loc xmlns:xlink="http://www.w3.org/1999/xlink" href="https://www.w3.org/TR/2014/CR-xpath-functions-31-20141218/" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">https://www.w3.org/TR/2014/CR-xpath-functions-31-20141218/</loc>
           <loc xmlns:xlink="http://www.w3.org/1999/xlink" href="https://www.w3.org/TR/2014/WD-xpath-functions-31-20141007/" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">https://www.w3.org/TR/2014/WD-xpath-functions-31-20141007/</loc>
           <loc xmlns:xlink="http://www.w3.org/1999/xlink" href="https://www.w3.org/TR/2014/WD-xpath-functions-31-20140424/" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">https://www.w3.org/TR/2014/WD-xpath-functions-31-20140424/</loc>
        </prevlocs><latestloc-major doc="XPath and XQuery Functions and Operators 3">
    <loc xmlns:xlink="http://www.w3.org/1999/xlink" href="https://www.w3.org/TR/xpath-functions-3/" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">https://www.w3.org/TR/xpath-functions-3/</loc>
  </latestloc-major><latestloc-tech doc="XPath and XQuery Functions and Operators">
    <loc xmlns:xlink="http://www.w3.org/1999/xlink" href="https://www.w3.org/TR/xpath-functions/" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">https://www.w3.org/TR/xpath-functions/</loc>
  </latestloc-tech><prevrec doc="XPath and XQuery Functions and Operators">
    <loc xmlns:xlink="http://www.w3.org/1999/xlink" href="https://www.w3.org/TR/2014/REC-xpath-functions-30-20140408/" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">https://www.w3.org/TR/2014/REC-xpath-functions-30-20140408/</loc>
  </prevrec><authlist><author role="3.1"><name>Michael Kay (XSLT WG)</name><affiliation>Saxonica</affiliation><email xmlns:xlink="http://www.w3.org/1999/xlink" href="http://www.saxonica.com/" xlink:type="simple" xlink:show="new" xlink:actuate="onRequest">http://www.saxonica.com/</email></author></authlist><errataloc xmlns:xlink="http://www.w3.org/1999/xlink" href="https://www.w3.org/XML/2017/qt-errata/xpath-functions-31-errata.html" xlink:type="simple"/><translationloc xmlns:xlink="http://www.w3.org/1999/xlink" href="https://www.w3.org/2003/03/Translations/byTechnology?technology=xpath-functions-31" xlink:type="simple"/><abstract><p>This document defines constructor functions, operators, and functions on the datatypes defined in
                    <bibref ref="xmlschema-2"/> and the datatypes defined in <bibref ref="xpath-datamodel-31"/>.  It also defines
                functions and operators on nodes and node sequences as defined in the <bibref ref="xpath-datamodel-31"/>.  These functions and operators are defined for use in <bibref ref="xpath-31"/> and <bibref ref="xquery-31"/> and
                    <bibref ref="xslt-30"/> and other related XML standards.  The signatures and summaries of functions defined in this document are available at:
<loc xmlns:xlink="http://www.w3.org/1999/xlink" href="http://www.w3.org/2005/xpath-functions/" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">http://www.w3.org/2005/xpath-functions/</loc>.</p><p><emph>At the time of writing, XSLT 3.0 requires support for XPath 3.0, and therefore version 3.0 of this function library;
              but it makes support for XPath 3.1 optional. It also replicates some of the functions defined herein, notably those
              concerned with processing of maps, so that these functions are available in XSLT 3.0 whether or not the processor supports
              XPath 3.1.</emph></p><p>This is the fourth version of the specification of this function library. The first version was included as an intrinsic part of the
<bibref ref="xpath"/> specification published on 16 November 1999. The second version was published under the title
<emph>XQuery 1.0 and XPath 2.0 Functions and Operators</emph> on 23 January 2007, 
   subsequently revised in a second edition published on 14 December 2010.
   The third version, published on 8 April 2014, was the first to carry its own version
number, 3.0. This version 3.1 is a revision of 3.0 that adds additional functions and operators, notably to work with the
new datatypes of maps and arrays.</p><p>A summary of changes since version 3.0 is provided at <specref ref="changelog"/>.</p></abstract><status id="status"><p><emph>This section describes the status of this
         document at the time of its publication.
         Other documents may supersede this document.
         A list of current W3C publications and the latest
         revision of this technical report can be found in the
         <loc xmlns:xlink="http://www.w3.org/1999/xlink" href="https://www.w3.org/TR/" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">W3C technical reports index</loc>
         at https://www.w3.org/TR/.</emph></p><p>This document is governed by the
         <loc xmlns:xlink="http://www.w3.org/1999/xlink" id="w3c_process_revision" href="https://www.w3.org/2017/Process-20170301/" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">1 March 2017 W3C Process Document</loc>. </p><p>This is a <loc xmlns:xlink="http://www.w3.org/1999/xlink" href="https://www.w3.org/2015/Process-20150901/#rec-publication" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">Recommendation</loc> of the W3C. 
It was jointly developed by the W3C 
<loc xmlns:xlink="http://www.w3.org/1999/xlink" href="https://www.w3.org/XML/Query/" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">XML Query Working Group</loc> and the W3C <loc xmlns:xlink="http://www.w3.org/1999/xlink" href="https://www.w3.org/Style/XSL/" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">XSLT Working Group</loc>, each of which is part of the <loc xmlns:xlink="http://www.w3.org/1999/xlink" href="https://www.w3.org/XML/Activity" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">XML Activity</loc>.</p><p diff="chg" at="2013-12-06">This Recommendation specifies XSLT and XQuery Functions and Operators (F&amp;O)
                              version 3.1, a fully compatible extension of <loc xmlns:xlink="http://www.w3.org/1999/xlink" href="https://www.w3.org/TR/xpath-functions-30/" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">F&amp;O version 3.0</loc>.
                              This publication differs from its version 3.0 primarily by the addition of maps and arrays.  There are numerous
                              smaller differences as well, all documented in the change log. </p><p>This specification is designed to be referenced normatively from
other specifications defining a host language for it; it is not
intended to be implemented outside a host language.  The
implementability of this specification has been tested in the context
of its normative inclusion in host languages defined by the
<loc xmlns:xlink="http://www.w3.org/1999/xlink" href="https://www.w3.org/TR/xquery-31/" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">XQuery 3.1</loc>
and
XSLT 3.0 (expected in 2017) specifications;
see the
<loc xmlns:xlink="http://www.w3.org/1999/xlink" href="https://dev.w3.org/2011/QT3-test-suite/ReportingResults31/report.html" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">XQuery 3.1 implementation report</loc>
(and, in the future, the WGs expect that there will also be an
XSLT 3.0 implementation report) for details.</p><p>This document incorporates minor changes made against the <loc xmlns:xlink="http://www.w3.org/1999/xlink" href="https://www.w3.org/2015/Process-20150901/#rec-pr" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">Proposed Recommendation</loc> of 17 January 2017.
  Changes to this document since the <loc xmlns:xlink="http://www.w3.org/1999/xlink" href="https://www.w3.org/2015/Process-20150901/#rec-pr" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">Proposed Recommendation</loc> are detailed in
  <specref ref="changes-since-Jan-2017"/>.</p><p>Please report errors in this document using W3C's
         <loc xmlns:xlink="http://www.w3.org/1999/xlink" href="https://www.w3.org/Bugs/Public/" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">public Bugzilla system</loc>
         (instructions can be found at
         <loc xmlns:xlink="http://www.w3.org/1999/xlink" href="https://www.w3.org/XML/2005/04/qt-bugzilla" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">https://www.w3.org/XML/2005/04/qt-bugzilla</loc>).
         If access to that system is not feasible, you may send your comments
         to the W3C XSLT/XPath/XQuery public comments mailing list,
         <loc xmlns:xlink="http://www.w3.org/1999/xlink" href="mailto:public-qt-comments@w3.org" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">public-qt-comments@w3.org</loc>.
         It will be very helpful if you include the string 
         “[FO31]”
         in the subject line of your report, whether made in Bugzilla or in email.
         Please use multiple Bugzilla entries (or, if necessary, multiple email messages)
         if you have more than one comment to make.
         Archives of the comments and responses are available at
         <loc xmlns:xlink="http://www.w3.org/1999/xlink" href="https://lists.w3.org/Archives/Public/public-qt-comments/" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">https://lists.w3.org/Archives/Public/public-qt-comments/</loc>. </p><p>This document has been reviewed by W3C Members, by
software developers, and by other W3C groups and interested parties,
and is endorsed by the Director as a W3C Recommendation. 
It is a stable document and may be used as reference material or cited from
another document. 
W3C's role in making the Recommendation is to draw attention to
the specification and to promote its widespread deployment. 
This enhances the functionality and interoperability of
the Web.</p><p>This document was produced by groups operating under the
   <loc xmlns:xlink="http://www.w3.org/1999/xlink" href="https://www.w3.org/Consortium/Patent-Policy-20040205/" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">5 February 2004 W3C Patent Policy</loc>.
   W3C maintains a <loc xmlns:xlink="http://www.w3.org/1999/xlink" href="https://www.w3.org/2004/01/pp-impl/18797/status#disclosures" rel="disclosure" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">public list of any 
   patent disclosures (W3C XML Query Working Group)</loc> and a <loc xmlns:xlink="http://www.w3.org/1999/xlink" href="https://www.w3.org/2004/01/pp-impl/19552/status#disclosures" rel="disclosure" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">public list of any patent 
   disclosures (W3C XSLT Working Group)</loc> made in connection with the deliverables of 
   each group; these pages also include instructions for disclosing a patent.
   An individual who has actual knowledge of a patent which the individual believes contains
   <loc xmlns:xlink="http://www.w3.org/1999/xlink" href="https://www.w3.org/Consortium/Patent-Policy-20040205/#def-essential" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">Essential Claim(s)</loc>
   must disclose the information in accordance with
   <loc xmlns:xlink="http://www.w3.org/1999/xlink" href="https://www.w3.org/Consortium/Patent-Policy-20040205/#sec-Disclosure" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">section 6 of the W3C Patent Policy</loc>. </p></status><langusage><language id="EN">English</language></langusage><revisiondesc><p/></revisiondesc></header><body><div1 id="intro"><head>Introduction</head><p>The purpose of this document is to catalog the functions and operators required for
                XPath 3.1, XQuery 3.1, and XSLT 3.0 (at the time of writing, XSLT 3.0 requires support for
                version 3.0 of this specification, and makes support for version 3.1 optional). 
                The exact syntax used to call these
                functions and operators is specified in <bibref ref="xpath-31"/>, <bibref ref="xquery-31"/> and 
            <bibref ref="xslt-30"/>. </p><p>This document defines three classes of functions:</p><ulist><item><p>General purpose functions, available for direct use in user-written queries, stylesheets, and XPath expressions,
               whose arguments and results are values defined by the <bibref ref="xpath-datamodel-31"/>.</p></item><item><p>Constructor functions, used for creating instances of a datatype from values of (in general) a different
            datatype. These functions are also available for general use; they are named after the datatype that they return,
            and they always take a single argument.</p></item><item><p>Functions that specify the semantics of operators defined in <bibref ref="xpath-31"/> and <bibref ref="xquery-31"/>.
            These exist for specification purposes only, and are not intended for direct calling from user-written code.</p></item></ulist><p>
                <bibref ref="xmlschema-2"/> defines a number of primitive and derived datatypes,
                collectively known as built-in datatypes. This document defines functions and
                operations on these datatypes as well as the other types 
                (for example, nodes and sequences of nodes) defined in <xspecref spec="DM31" ref="types"/> of 
            the <bibref ref="xpath-datamodel-31"/>.
                These functions and operations are available for use in <bibref ref="xpath-31"/>,
                    <bibref ref="xquery-31"/> and any other host language that chooses to reference them.
                In particular, they may be referenced in future versions of XSLT and related XML standards. </p><p><bibref ref="xmlschema11-2"/> adds to the datatypes defined
            in <bibref ref="xmlschema-2"/>. It introduces a new derived type <code>xs:dateTimeStamp</code>, and it
         incorporates as built-in types the two types <code>xs:yearMonthDuration</code> and <code>xs:dayTimeDuration</code>
         which were previously XDM additions to the type system. In addition, XSD 1.1 clarifies and updates many
         aspects of the definitions of the existing datatypes: for example, it extends the value space of
         <code>xs:double</code> to allow both positive and negative zero, and extends the lexical space to allow <code>+INF</code>;
            it modifies the value space of <code>xs:Name</code>
         to permit additional Unicode characters; it allows year zero and disallows leap seconds in <code>xs:dateTime</code>
         values; and it allows any character string to appear as the value of an <code>xs:anyURI</code> item.
         Implementations of this specification <rfc2119>may</rfc2119> support either XSD 1.0 or XSD 1.1 or both.</p><p>References to specific sections of some of the above documents are indicated by
                cross-document links in this document. Each such link consists of a pointer to a
                specific section followed a superscript specifying the linked document. The
                superscripts have the following meanings: 'XQ' <bibref ref="xquery-31"/>, 'XT' <bibref ref="xslt-30"/>,
            'XP' <bibref ref="xpath-31"/>, and 'DM' <bibref ref="xpath-datamodel-31"/>.</p><div2 id="conformance" diff="chg" at="D"><head>Conformance</head><p>
               This recommendation contains a set of function specifications. 
               It defines conformance at the level of individual functions. An implementation of a function conforms to a function specification 
               in this recommendation if all the following conditions are satisfied:</p><ulist><item><p>For all combinations of valid inputs to the function (both explicit arguments and implicit context dependencies), 
                  the result of the function meets the mandatory requirements of this specification.
               </p></item><item><p>For all invalid inputs to the function, the implementation signals (in some way appropriate to the calling environment) that a dynamic error has occurred.
               </p></item><item><p>For a sequence of calls within the same <termref def="execution-scope">execution scope</termref>, the requirements of this recommendation 
                  regarding the <termref def="dt-deterministic">determinism</termref> of results are satisfied (see <specref ref="properties-of-functions"/>).
               </p></item></ulist><p>Other recommendations ("host languages") that reference this document may dictate:</p><ulist><item><p>Subsets or supersets of this set of functions to be available in particular environments;</p></item><item><p>Mechanisms for invoking functions, supplying arguments, initializing the static and dynamic context, receiving results, and handling errors;
               </p></item><item><p>A concrete realization of concepts such as <termref def="execution-scope">execution scope</termref>;</p></item><item><p>Which versions of other specifications referenced herein (for example, XML, XSD, or Unicode) are to be used.</p></item></ulist><p>Any behavior that is discretionary (implementation-defined or implementation-dependent) in this specification may be constrained by a host language.</p><note><p>Adding such constraints in a host language, however, is discouraged because it makes it difficult to re-use implementations of 
               the function library across host languages.</p></note><p>This specification allows flexibility in the choice of versions of specifications on which it depends:</p><ulist><item><p>It is <termref def="implementation-defined"/> which version of Unicode is supported, 
                     but it is recommended that the most recent version of Unicode be used.  </p></item><item><p>It is <termref def="implementation-defined"/> whether the type system is based
                     on XML Schema 1.0 or XML Schema 1.1.  </p></item><item><p>It is <termref def="implementation-defined"/> whether definitions that rely on
                     XML (for example, the set of valid XML characters) should use the definitions in XML 1.0 or XML 1.1.</p></item></ulist><note><p>The XML Schema 1.1 recommendation
                  introduces one new concrete datatype: <code>xs:dateTimeStamp</code>; it also incorporates
                  the types <code>xs:dayTimeDuration</code>, <code>xs:yearMonthDuration</code>,
                  and <code>xs:anyAtomicType</code> which were previously defined in earlier versions of <bibref ref="xpath-datamodel-31"/>.
                  Furthermore, XSD 1.1
                  includes the option of supporting revised definitions of types such as <code>xs:NCName</code>
                  based on the rules in XML 1.1 rather than 1.0.</p></note><p>In this document, text labeled as an example or as a Note is
            provided for explanatory purposes and is not normative.</p></div2><div2 id="namespace-prefixes"><head>Namespaces and prefixes</head><p>The functions and operators defined in this document are contained in one of
                    several namespaces (see <bibref ref="xml-names"/>) and referenced using an
                    <code>xs:QName</code>.</p><p>This document uses conventional prefixes to refer to these namespaces. User-written
               applications can choose a different prefix to refer to the namespace, so long as it is
               bound to the correct URI. The host language may also define a default namespace for
               function calls, in which case function names in that namespace need not be prefixed
               at all. In many cases the default namespace will be 
               <code>http://www.w3.org/2005/xpath-functions</code>, allowing a call on the <code>fn:name</code>
               function (for example) to be written as <code>name()</code> rather than <code>fn:name()</code>; 
               in this document, however, all example function calls are explicitly prefixed.</p><p>The URIs of the namespaces and the conventional prefixes associated with them are:</p><ulist><item><p><code>http://www.w3.org/2001/XMLSchema</code> for constructors —
                            associated with <code>xs</code>.
                  </p><p>The section <specref ref="constructor-functions"/> defines 
                     constructor functions for the built-in datatypes defined
                     in <bibref ref="xmlschema-2"/> and in <xspecref spec="DM31" ref="types"/>
                     of <bibref ref="xpath-datamodel-31"/>. These datatypes and the corresponding constructor functions  
                     are in the XML Schema namespace, <code>http://www.w3.org/2001/XMLSchema</code>,
                     and are named in this document using the <code>xs</code> prefix. </p></item><item><p><code>http://www.w3.org/2005/xpath-functions</code>
                     for functions — associated with <code>fn</code>. </p><p>The namespace
                     prefix used in this document for most functions that are available to users is
                     <code>fn</code>.</p></item><item><p><code>http://www.w3.org/2005/xpath-functions/math</code>
                     for functions — associated with <code>math</code>. </p><p>This namespace is used for some mathematical functions. The namespace
                     prefix used in this document for these functions is <code>math</code>.
                     These functions are available to users in exactly the same way as those in the
                     <code>fn</code> namespace.</p></item><item><p><code>http://www.w3.org/2005/xpath-functions/map</code>
                     for functions — associated with <code>map</code>. </p><p>This namespace is used for some functions that manipulate maps (see
                     <specref ref="map-functions"/>). The namespace
                     prefix used in this document for these functions is <code>map</code>.
                     These functions are available to users in exactly the same way as those in the
                     <code>fn</code> namespace.</p></item><item><p><code>http://www.w3.org/2005/xpath-functions/array</code>
                     for functions — associated with <code>array</code>. </p><p>This namespace is used for some functions that manipulate maps (see
                     <specref ref="array-functions"/>). The namespace
                     prefix used in this document for these functions is <code>array</code>.
                     These functions are available to users in exactly the same way as those in the
                     <code>fn</code> namespace.</p></item><item><p><code>http://www.w3.org/2005/xqt-errors</code> — associated with
                            <code>err</code>. </p><p>There are no functions in this namespace; it is used for error codes.</p><p>This document uses the prefix <code>err</code> to represent the namespace URI 
                     <code>http://www.w3.org/2005/xqt-errors</code>, which is the namespace for all XPath 
                     and XQuery error codes and messages. This namespace prefix is not predeclared and 
                     its use in this document is not normative.</p></item><item><p><code>http://www.w3.org/2010/xslt-xquery-serialization</code> — associated with
                     <code>output</code>. </p><p>There are no functions in this namespace: it is
                     used for serialization parameters, as described in <bibref ref="xslt-xquery-serialization-31"/></p></item><item><p>
                     Functions defined with the <code>op</code> prefix are described here to
                     underpin the definitions of the operators in <bibref ref="xpath-31"/>, <bibref ref="xquery-31"/> 
                     and <bibref ref="xslt-30"/>. These functions are not available
                     directly to users, and there is no requirement that implementations should
                     actually provide these functions. For this reason, no namespace is associated
                     with the <code>op</code> prefix. For example, multiplication is generally
                     associated with the <code>*</code> operator, but it is described as a function
                     in this document:</p><example role="signature"><proto role="example" name="numeric-multiply" return-type="xs:numeric" isOp="yes" prefix="op" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg1" type="xs:numeric"/><arg name="arg2" type="xs:numeric"/></proto></example></item></ulist><note><p>The above namespace URIs are not expected to change from one version of this 
                  document to another. The contents of these namespaces may be extended to allow 
                  additional functions (and errors, and serialization parameters) to be defined.</p></note></div2><div2 id="func-overloading"><head>Function overloading</head><p>A function is uniquely defined by its name and arity (number of arguments); it is therefore
            not possible to have two different functions that have the same name and arity, but different
            types in their signature. That is, function overloading in this sense of the term is not permitted.
            Consequently, functions such as <code>fn:string</code> which accept arguments of many different
            types have a signature that defines a very general argument type, in this case <code>item()?</code>
            which accepts any single item; supplying an inappropriate item (such as a function item) causes
            a dynamic error.</p><p>Some functions on numeric types include the type <code>xs:numeric</code> in their signature
               as an argument or result type. In this version of the specification, <code>xs:numeric</code>
               has been redefined as a built-in union type representing the union of 
               <code>xs:decimal</code>, <code>xs:float</code>, <code>xs:double</code> (and thus automatically
               accepting types derived from these, including <code>xs:integer</code>).</p><p>Operators such as "+" may be overloaded: they map to different underlying functions depending
            on the dynamic types of the supplied operands.</p><p>It is possible for two functions to have the same name provided they have different arity (number of arguments).
               For the functions defined in this specification, where two functions have the same name and different arity,
               they also have closely related behavior, so they are defined in the same section of this document.</p></div2><div2 id="func-signatures"><head>Function signatures and descriptions</head><p>Each function (or group of functions having the same name) is defined in this specification using
            a standard proforma.</p><p>The function name is a <code>QName</code> as defined in <bibref ref="xmlschema-2"/>
               and must adhere to its syntactic conventions. Following the precedent set by <bibref ref="xpath"/>,
               function names are generally composed of English words separated by hyphens ("-"). Abbreviations are
               used only where there is a strong precedent in other programming languages (as with <code>math:sin</code> and 
               <code>math:cos</code> for sine and cosine). If a
               function name contains a <bibref ref="xmlschema-2"/> datatype name, it may have
               intercapitalized spelling and is used in the function name as such. An example is <code>fn:timezone-from-dateTime</code>.</p><p>The first section in the proforma is a short summary of what the function does. This is intended
            to be informative rather than normative.</p><p>Each function is then defined by specifying its signature, which defines the
               types of the parameters and of the result value.</p><p>Each function's signature is presented in a form like this:</p><example role="signature"><proto role="example" name="function-name" return-type="return-type" returnEmptyOk="no" returnSeq="no" prefix="fn" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no" isOp="no"><arg name="parameter-name" type="parameter-type"/><arg name="..." type=""/></proto></example><p>In this notation, <term>function-name</term>, in bold-face, 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 parameter list:
                    "<code>()</code>"; otherwise, the name is followed by a parenthesized list of
                    parameter declarations, in which each declaration specifies the static type of the
                    parameter, in italics, and a descriptive, but non-normative, name. If there are
                    two or more parameter declarations, they are separated by a comma. The <emph>
                        <code>return-type</code></emph>, also in italics, specifies the static type of the value returned by the
                    function. The dynamic type of the value returned by the function is the same as its static
                    type or derived from the static type. All parameter types and return types are
                    specified using the SequenceType notation defined in <xspecref spec="XP31" ref="id-sequencetype-syntax"/>.</p><p>One function, <code>fn:concat</code>, has a variable number of arguments (two or more).
            More strictly, there is an infinite set of functions having the name <code>fn:concat</code>, with arity
            ranging from 2 to infinity. For this special case, a single function signature is given, with an ellipsis
            indicating an indefinite number of arguments.</p><p>The next section in the proforma defines the semantics of the function as a set of rules. 
               The order in which the rules appear is significant; they are to be applied in the order in which
               they are written. Error conditions, however, are generally listed in a separate section that follows
            the main rules, and take precedence over non-error rules except where otherwise stated. The principles outlined
            in <xspecref spec="XP31" ref="id-errors-and-opt"/> apply by default: to paraphrase, if the result of the function
            can be determined without evaluating all its arguments, then it is not necessary to evaluate the remaining arguments
            merely in order to determine whether any error conditions apply.</p><p>Where the proforma includes sections headed <emph>Notes</emph> or <emph>Examples</emph>, these are non-normative.</p><p>Rules for passing parameters to operators are described in the relevant sections
                    of <bibref ref="xquery-31"/> and <bibref ref="xpath-31"/>. For example, the rules for
                    passing parameters to arithmetic operators are described in <xspecref spec="XP31" ref="id-arithmetic"/>. Specifically, rules for parameters of
                    type <code>xs:untypedAtomic</code> and the empty sequence are specified in this section.</p><p>As is customary, the parameter type name indicates that the function or operator
                    accepts arguments of that type, or types derived from it, in that position. This
                    is called <emph>subtype substitution</emph> (See <xspecref spec="XP31" ref="id-sequencetype-matching"/>). In addition, numeric type instances and
                    instances of type <code>xs:anyURI</code> can be promoted to produce an argument
                    of the required type. (See <xspecref spec="XP31" ref="promotion"/>).</p><olist><item><p><emph>Subtype Substitution</emph>: A derived type may substitute for
                                its base type. In particular, <code>xs:integer</code> may be used
                                where <code>xs:decimal</code> is expected.</p></item><item><p><emph>Numeric Type Promotion</emph>: <code>xs:decimal</code> may be
                                promoted to <code>xs:float</code> or <code>xs:double</code>. 
								Promotion to <code>xs:double</code> should be done directly, not via
								 <code>xs:float</code>, to avoid loss of precision.</p></item><item><p><emph>anyURI Type Promotion</emph>: A value of
                                type <code>xs:anyURI</code> can be promoted to the
                                type <code>xs:string</code>. </p></item></olist><p>Some functions accept a single value or the empty sequence as an argument and
                    some may return a single value or the empty sequence. This is indicated in the
                    function signature by following the parameter or return type name with a
                    question mark: "<code>?</code>", indicating that either a single value or the
                    empty sequence must appear. See below.</p><example role="signature"><proto role="example" name="function-name" return-type="return-type" returnEmptyOk="yes" returnSeq="no" prefix="fn" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no" isOp="no"><arg name="parameter-name" type="parameter-type" emptyOk="yes"/></proto></example><p>Note that this function signature is different from a signature in which the
                    parameter is omitted. See, for example, the two signatures
                    for <code>fn:string</code>. In the first signature, the parameter is omitted
                    and the argument defaults to the context item, referred to as <code>.</code>.
                    In the second signature, the argument must be present but may be the empty
                    sequence, written as <code>()</code>.
                </p><p>Some functions accept a sequence of zero or more values as an argument. This is
                    indicated by following the name of the type of the items in the sequence with
                    <code>*</code>. The sequence may contain zero or more items of the named type.
                    For example, the function below accepts a sequence of <code>xs:double</code> and
                    returns a <code>xs:double</code> or the empty sequence.</p><example role="signature"><proto role="example" name="median" return-type="xs:double" returnEmptyOk="yes" returnSeq="no" prefix="fn" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no" isOp="no"><arg name="arg" type="xs:double*" emptyOk="no"/></proto></example></div2><div2 id="options" diff="add" at="D"><head>Options</head><p>As a matter of convention, a number of functions defined in this document take
            a parameter whose value is a map, defining options controlling the detail of how
            the function is evaluated. Maps are a new datatype introduced in XPath 3.1.</p><p>For example, the function <code>fn:xml-to-json</code> has an options parameter
            allowing specification of whether the output is to be indented. A call might be written:</p><eg xml:space="preserve">fn:xml-to-json($input, map{'indent':true()})</eg><p><termdef id="option-parameter-conventions" term="option parameter conventions">Functions
            that take an options parameter adopt common conventions on how the
            options are used. These are referred to as the <term>option parameter conventions</term>. These
            rules apply only to functions that explicitly refer to them.</termdef></p><p>Where a function adopts the <termref def="option-parameter-conventions"/>, the following rules
            apply:</p><olist><item><p>The value of the relevant argument must be a map. The entries in the map are
                  referred to as options: the key of the entry is called the option name, and the
                  associated value is the option value. Option names defined in this specification
               are always strings (single <code>xs:string</code> values). Option values may
               be of any type.</p></item><item><p>The type of the options parameter in the function signature is always
               given as <code>map(*)</code>.</p></item><item><p>Although option names are described above as strings, the actual key may be
                  any value that compares equal to the required string (using the <code>eq</code> operator
                  with Unicode codepoint collation; or equivalently, the <code>op:same-key</code> relation). 
                  For example, instances of <code>xs:untypedAtomic</code>
                  or <code>xs:anyURI</code> are equally acceptable.</p><note><p>This means that the implementation of the function can check for the
               presence and value of particular options using the functions <code>map:contains</code>
               and/or <code>map:get</code>.</p></note></item><item><p>It is not an error if the options map contains options with names other than those
               described in this specification. Implementations <rfc2119>may</rfc2119> attach an 
                  <termref def="implementation-defined">implementation-defined</termref> meaning to such entries,
                  and <rfc2119>may</rfc2119> define errors that arise if such entries are present with invalid values.
               Implementations <rfc2119>must</rfc2119> ignore such entries unless they have a specific 
                  <termref def="implementation-defined">implementation-defined</termref> meaning.
               Implementations that define additional options in this way <rfc2119>should</rfc2119>
               use values of type <code>xs:QName</code> as the option names, using an appropriate namespace.</p></item><item><p>All entries in the options map are optional, and supplying an empty map has the same
               effect as omitting the relevant argument in the function call, assuming this is permitted.</p></item><item><p>For each named option, the function
               specification defines a required type for the option value. The value that is actually
               supplied in the map is converted to this required type using the 
                  <xtermref spec="XP31" ref="dt-function-conversion">function conversion rules</xtermref>.
                  <phrase diff="chg" at="F">This will result in an error (typically 
                     <xerrorref spec="XP" class="TY" code="0004" type="type"/> or
                     <xerrorref spec="FO" class="RG" code="0001" type="type"/>)</phrase>
                  if conversion of the supplied value to the required type is not possible. 
                  <phrase diff="chg" at="F">A type error also occurs if this conversion
                  delivers a coerced function whose invocation fails with a type error.</phrase>
                  A dynamic error occurs if the supplied value 
               after conversion is not one of the permitted values for the option in question: the error codes
               for this error are defined in the specification of each function.</p><note><p>It is the responsibility of each function implementation to invoke this conversion; it
               does not happen automatically as a consequence of the function calling rules.</p></note></item><item><p>In cases where an option is list-valued, by convention the value may be supplied
               either as a sequence or as an array. Accepting a sequence is convenient if the
               value is generated programmatically using an XPath expression; while accepting an array 
               allows the options to be held in an external file in JSON format, to be read using
               a call on the <code>fn:json-doc</code> function.</p></item><item><p>In cases where the value of an option is itself a map, the specification
               of the particular function must indicate whether or not these rules apply recursively 
               to the contents of that map.</p></item></olist></div2><div2 id="datatypes"><head>Type System</head><p diff="chg" at="20140909">The diagrams in this section show how nodes, functions,
primitive simple types,
and user defined types fit together into a type system.
This type system comprises two distinct subsystems that both include
the primitive atomic types. 
In the diagrams, connecting lines represent relationships between derived types
and the types from which they are derived;
the arrowheads point toward the type from which they are derived. 
The dashed line represents relationships not present in this diagram,
but that appear in one of the other diagrams. 
Dotted lines represent additional relationships that follow an evident pattern.
The information that appears in each diagram is recapitulated in tabular form.
</p><p diff="chg" at="20140909">The <code>xs:IDREFS</code>, <code>xs:NMTOKENS</code>,
<code>xs:ENTITIES</code> types, and <code>xs:numeric</code> and both the
<code>user-defined list types</code> and
<code>user-defined union types</code>
are special types in that these types are lists or unions
rather than types derived by extension or restriction.</p><div3 id="item-type-hierarchy"><head>Item Types</head><p diff="chg" at="20140909">The first diagram and its corresponding table illustrate
the relationship of various item types.</p><p>Item types are used to characterize the various types of item that can appear
      in a sequence (nodes, atomic values, and functions), and they are therefore used
      in declaring the types of variables or the argument types and result types of functions.</p><p>Item types in the data model
form a directed graph, rather than a hierarchy or lattice: in the relationship defined
by the <code>derived-from(A, B)</code> function, some types are derived
   from more than one other type. Examples include functions (<code>function(xs:string) as xs:int</code>
   is substitutable for <code>function(xs:NCName) as xs:int</code> and also for 
   <code>function(xs:string) as xs:decimal</code>), and union types (<code>A</code>
 is substitutable for <code>union(A, B)</code> and also for <code>union(A, C)</code>.
   In XDM, item types include node types, function types, and built-in atomic types. 
The diagram, which shows only hierarchic relationships, is therefore a simplification of
the full model.</p><graphic xmlns:xlink="http://www.w3.org/1999/xlink" source="XPathTypeHierarchy-1-items-3.1.png" alt="Type hierarchy graphic, item hierarchy" role="full-width" xlink:type="simple" xlink:show="embed" xlink:actuate="onLoad"/><p>In the table, each type whose name is indented is derived from the type
whose name appears nearest above it with one less level of indentation.</p><table border="0" role="hierarchy" diff="chg"><caption>Item Type Hierarchy</caption><tbody><tr><td rowspan="1" colspan="1">item</td></tr><tr><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1">xs:anyAtomicType</td></tr><tr><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1">node</td></tr><tr><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1">attribute</td></tr><tr><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1">user-defined attribute types</td></tr><tr><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1">comment</td></tr><tr><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1">document</td></tr><tr><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1">user-defined document types</td></tr><tr><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1">element</td></tr><tr><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1">user-defined element types</td></tr><tr><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1">namespace</td></tr><tr><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1">processing-instruction</td></tr><tr><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1">text</td></tr><tr><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1">function(*)</td><td rowspan="1" colspan="1"/></tr><tr><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1">array(*)</td></tr><tr><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1">map(*)</td></tr></tbody></table></div3><div3 id="schema-type-hierarchy"><head>Schema Type Hierarchy</head><p diff="chg" at="20140909">The next diagram and table illustrate the schema type subsystem, in which
all types are derived from the distinguished type <code>xs:anyType</code>. </p><p>Schema types include built-in types defined in the XML Schema specification, and user-defined
      types defined using mechanisms described in the XML Schema specification. Schema types define the
      permitted contents of nodes. The main categories are complex types, which define the permitted content
      of elements, and simple types, which can be used to constrain the values of both elements and attributes.</p><graphic xmlns:xlink="http://www.w3.org/1999/xlink" source="XPathTypeHierarchy-2-anyTypes-3.1.png" alt="Type hierarchy graphic, anyType hierarchy" diff="chg" at="20140909" role="full-width" xlink:type="simple" xlink:show="embed" xlink:actuate="onLoad"/><p>In the table, each type whose name is indented is derived from the type
whose name appears nearest above it with one less level of indentation.</p><table border="0" role="hierarchy" diff="chg"><tbody><tr><td rowspan="1" colspan="1">xs:anyType</td></tr><tr><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1">xs:anySimpleType</td></tr><tr><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1">xs:anyAtomicType</td></tr><tr><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1">list types</td></tr><tr><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1">xs:IDREFS</td></tr><tr><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1">xs:NMTOKENS</td></tr><tr><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1">xs:ENTITIES</td></tr><tr><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1">user-defined list types</td></tr><tr><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1">union types</td></tr><tr><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1">xs:numeric</td></tr><tr><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1">user-defined union types</td></tr><tr><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1">complex types</td></tr><tr><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1">xs:untyped</td></tr><tr><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1">user-defined complex types</td></tr></tbody></table></div3><div3 id="atomic-type-hierarchy"><head>Atomic Type Hierarchy</head><p diff="chg" at="20140909">The final diagram and table show all of the atomic types, including the primitive simple types and the
built-in types derived from the primitive simple types. 
This includes all the built-in datatypes defined in <bibref ref="xmlschema-2"/>.</p><p>Atomic types are both item types and schema types, so the root type <code>xs:anyAtomicType</code> may be found
      in both the previous diagrams.</p><graphic xmlns:xlink="http://www.w3.org/1999/xlink" source="XPathTypeHierarchy-3-anyAtomicTypes-3.1.png" alt="Type hierarchy graphic, anyAtomicType hierarchy" diff="chg" at="20140909" role="full-width" xlink:type="simple" xlink:show="embed" xlink:actuate="onLoad"/><p>In the table, each type whose name is indented is derived from the type
whose name appears nearest above it with one less level of indentation.</p><table border="0" role="hierarchy"><tbody><tr><td rowspan="1" colspan="1">xs:untypedAtomic</td></tr><tr><td rowspan="1" colspan="1">xs:dateTime</td></tr><tr><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1">xs:dateTimeStamp</td></tr><tr><td rowspan="1" colspan="1">xs:date</td></tr><tr><td rowspan="1" colspan="1">xs:time</td></tr><tr><td rowspan="1" colspan="1">xs:duration</td></tr><tr><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1">xs:yearMonthDuration</td></tr><tr><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1">xs:dayTimeDuration</td></tr><tr><td rowspan="1" colspan="1">xs:float</td></tr><tr><td rowspan="1" colspan="1">xs:double</td></tr><tr><td rowspan="1" colspan="1">xs:decimal</td></tr><tr><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1">xs:integer</td></tr><tr><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1">xs:nonPositiveInteger</td></tr><tr><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1">xs:negativeInteger</td></tr><tr><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1">xs:long</td></tr><tr><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1">xs:int</td></tr><tr><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1">xs:short</td></tr><tr><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1">xs:byte</td></tr><tr><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1">xs:nonNegativeInteger</td></tr><tr><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1">xs:unsignedLong</td></tr><tr><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1">xs:unsignedInt</td></tr><tr><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1">xs:unsignedShort</td></tr><tr><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1">xs:unsignedByte</td></tr><tr><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1">xs:positiveInteger</td></tr><tr><td rowspan="1" colspan="1">xs:gYearMonth</td></tr><tr><td rowspan="1" colspan="1">xs:gYear</td></tr><tr><td rowspan="1" colspan="1">xs:gMonthDay</td></tr><tr><td rowspan="1" colspan="1">xs:gDay</td></tr><tr><td rowspan="1" colspan="1">xs:gMonth</td></tr><tr><td rowspan="1" colspan="1">xs:string</td></tr><tr><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1">xs:normalizedString</td></tr><tr><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1">xs:token</td></tr><tr><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1">xs:language</td></tr><tr><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1">xs:NMTOKEN</td></tr><tr><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1">xs:Name</td></tr><tr><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1">xs:NCName</td></tr><tr><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1">xs:ID</td></tr><tr><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1">xs:IDREF</td></tr><tr><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1">xs:ENTITY</td></tr><tr><td rowspan="1" colspan="1">xs:boolean</td></tr><tr><td rowspan="1" colspan="1">xs:base64Binary</td></tr><tr><td rowspan="1" colspan="1">xs:hexBinary</td></tr><tr><td rowspan="1" colspan="1">xs:anyURI</td></tr><tr><td rowspan="1" colspan="1">xs:QName</td></tr><tr><td rowspan="1" colspan="1">xs:NOTATION</td></tr></tbody></table></div3></div2><div2 id="terminology"><head>Terminology</head><p>The terminology used to describe the functions and operators on types defined in <bibref ref="xmlschema-2"/> is defined in the body of this specification. The terms defined
            in this section are used in building those definitions.</p><note><p>Following in the tradition of <bibref ref="xmlschema-2"/>, the terms <term>type</term>
            and <term>datatype</term> are used interchangeably.</p></note><div3 id="character-terminology"><head>Strings, characters, and codepoints</head><p diff="chg" at="D">This document uses the terms <code>string</code>, <code>character</code>, and <code>codepoint</code>
               with meanings that are normatively defined in <bibref ref="xpath-datamodel-31"/>, and which are paraphrased here
                  for ease of reference:</p><p><termdef id="character" term="character">A <term>character</term> is an instance of the 
                  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XML" ref="NT-Char" xlink:type="simple">Char</xnt> production of <bibref ref="xml"/>.</termdef></p><note><p>This
               definition excludes Unicode characters in the surrogate blocks as well as xFFFE and xFFFF, while
               including characters with codepoints greater than xFFFF which some programming languages treat
               as two characters. The valid characters are defined by their codepoints, and include some
               whose codepoints have not been assigned by the Unicode consortium to any character.</p></note><p><termdef id="string" term="string">A <term>string</term> is a sequence of zero or more 
                  <termref def="character">characters</termref>, or equivalently,
               a value in the value space of the <code>xs:string</code> datatype.</termdef></p><p><termdef id="codepoint" term="codepoint">A <term>codepoint</term> is an <phrase diff="del" at="D">non-negative</phrase> integer
               assigned to a <termref def="character">character</termref> by the Unicode consortium, 
               or reserved for future assignment to a character.</termdef>
               </p><note><p>The set of codepoints is thus wider than the set of characters.</p><p>This specification spells "codepoint" as one word; the Unicode specification spells
                     it as "code point".
                  Equivalent terms found in other specifications are
                  "character number" or "code position". See <bibref ref="charmod"/></p></note><p>Because these terms appear so frequently, they are hyperlinked to the definition only when there
                  is a particular desire to draw the reader's attention to the definition; the absence of a hyperlink
                  does not mean that the term is being used in some other sense.</p><p>It is <termref def="implementation-defined"/> which version of <bibref ref="Unicode"/> is supported, but it is recommended that the most recent version of Unicode be used.</p><p>Unless explicitly stated, the <code>xs:string</code> values returned by the
                  functions in this document are not normalized in the sense of <bibref ref="charmod"/>.</p><notes><p>In functions that involve character counting such
                     as <code>fn:substring</code>, <code>fn:string-length</code> and
                     <code>fn:translate</code>, what is counted is the number of XML <termref def="character">characters</termref>
                     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.</p></notes></div3><div3 id="namespace-terminology"><head>Namespaces and URIs</head><p>This document uses the phrase "namespace URI" to identify the concept identified
                  in <bibref ref="xml-names"/> as "namespace name", and the phrase "local name"
                  to identify the concept identified in <bibref ref="xml-names"/> as "local part".</p><p>It also uses the term <quote>expanded-QName</quote> defined below.</p><p diff="chg" at="D"><termdef id="expanded-name" term="expanded-QName"> An <term>expanded-QName</term> 
                  is a value in the value space of the <code>xs:QName</code> datatype as defined in the XDM data model 
                  (see <bibref ref="xpath-datamodel-31"/>): that is, a triple containing namespace prefix (optional), namespace URI (optional), 
                  and local name. Two expanded QNames are equal if the namespace URIs are the same (or both absent) 
                  and the local names are the same. The prefix plays no part in the comparison, but is used only 
                  if the expanded QName needs to be converted back to a string.</termdef></p><p>The term URI is used as follows:</p><p><termdef id="dt-uri" term="URI">Within this specification, the term <term>URI</term> refers to Universal Resource Identifiers as
                  defined in <bibref ref="rfc3986"/> and extended in <bibref ref="rfc3987"/> with a new name <term>IRI</term>.  The term <term>URI   
                     Reference</term>, unless otherwise stated, refers to a string in the lexical space of the <code>xs:anyURI</code> datatype 
                  as defined in <bibref ref="xmlschema-2"/>.</termdef></p><note><p>
                     Note that this means, in practice, that where this 
                     specification requires a "URI Reference", an IRI as defined in <bibref ref="rfc3987"/> will be 
                     accepted, provided that other relevant specifications also permit an IRI. The term URI has been 
                     retained in preference to IRI to avoid introducing new names for concepts such as "Base URI" that 
                     are defined or referenced across the whole family of XML specifications.  Note also that the 
                     definition of <code>xs:anyURI</code> is a wider definition than the definition in <bibref ref="rfc3987"/>; 
                     for example it does not require non-ASCII characters to be escaped.
                  </p></note></div3><div3 id="conformance-terminology" diff="chg" at="D"><head>Conformance terminology</head><p>In this specification:</p><ulist><item><p>The auxiliary verb <rfc2119>must</rfc2119>, when rendered in small capitals, indicates a precondition for conformance.</p><ulist><item><p>When the sentence relates to an implementation of a function (for example "All implementations <rfc2119>must</rfc2119> 
                        recognize URIs of the form ...") then an implementation is not conformant unless it behaves as stated.
                     </p></item><item><p>When the sentence relates to the result of a function (for example "The result <rfc2119>must</rfc2119> have the same type as 
                        <code>$arg</code>") then the implementation is not conformant unless it delivers a result as stated.
                     </p></item><item><p>When the sentence relates to the arguments to a function (for example "The value of <code>$arg</code> <rfc2119>must</rfc2119> 
                        be a valid regular expression") then the implementation is not conformant unless it enforces the condition by raising a dynamic error 
                        whenever the condition is not satisfied. 
                     </p></item></ulist></item><item><p>The auxiliary verb <rfc2119>may</rfc2119>, when rendered in small capitals, indicates optional or discretionary behavior. 
                     The statement "An implementation <rfc2119>may</rfc2119> do X" implies that it is implementation-dependent whether or not it does X.</p></item><item><p>The auxiliary verb <rfc2119>should</rfc2119>, when rendered in small capitals, indicates desirable or recommended behavior. 
                     The statement "An implementation <rfc2119>should</rfc2119> do X" implies that it is desirable to do X, but implementations may choose
                     to do otherwise if this is judged appropriate.</p></item></ulist><p><termdef id="implementation-defined" term="implementation-defined">Where behavior is described as 
               <term>implementation-defined</term>, variations between processors are permitted, but a 
                  conformant implementation <rfc2119>must</rfc2119> document the choices it has made.</termdef></p><p><termdef id="implementation-dependent" term="implementation-dependent">Where behavior is described as 
                  <term>implementation-dependent</term>, variations between processors are permitted, and  
                  conformant implementations are not required to document the choices they have made.</termdef></p><note><p>Where this specification states that something is implementation-defined or implementation-dependent, it is
               open to host languages to place further constraints on the behavior.</p></note></div3><div3 id="properties-of-functions"><head>Properties of functions</head><p>This section is concerned with the question of whether two calls on a function, with the same arguments, may
               produce different results.</p><p><termdef id="execution-scope" term="execution scope">An <term>execution scope</term> is a sequence of
                  calls to the function library during which certain aspects of the state are required to remain invariant.
                  For example, two calls to <code>fn:current-dateTime</code> within the same execution scope will return the same result.
                  The execution scope is defined by the host language that invokes the function library.</termdef>
                  In XSLT, for example, any two function calls executed during
                  the same transformation are in the same execution scope (except that static expressions, such as those used in
                  <code>use-when</code> attributes, are in a separate execution scope).
                  </p><p>The following definition explains more precisely what it means for two function calls to return the same result:</p><p><termdef id="dt-identical" term="identical"/>Two values are
                  defined to be <term>identical</term> if they
                  contain the same number of items and the items are pairwise identical. Two items are identical
                  if and only if one of the following conditions applies:</p><olist><item><p>Both items are atomic values, of precisely the same type, and the values are equal as defined using the <code>eq</code> operator,
                     using the Unicode codepoint collation when comparing strings.</p></item><item><p>Both items are nodes, and represent the same node.</p></item><item diff="add" at="D"><p>Both items are maps, both maps have the same number of entries, 
                     and for every entry <var>E1</var> in the first map there is an entry <var>E2</var> in the second map such 
                     that the keys of <var>E1</var> and <var>E2</var> are <termref def="dt-same-key">the same key</termref>, 
                     and the corresponding values <var>V1</var> and <var>V2</var> are <termref def="dt-identical"/>.</p></item><item diff="add" at="D"><p>Both items are arrays, both arrays have the same number of members, and the members
                     are pairwise <termref def="dt-identical"/>.</p></item><item diff="chg" at="B"><p>Both items are function items, 
                     <phrase diff="add" at="D">neither item is a map or array</phrase>, and all the following conditions apply:</p><olist><item><p>Either both functions have the same name, or both names are 
                           <xtermref ref="dt-absent" spec="DM31">absent</xtermref>.</p></item><item><p>Both functions have the same arity.</p></item><item><p>Both functions have the same function signature. <phrase diff="add" at="E">Two
                        function signatures are defined to be the same if the declared result types are identical and the declared
                        argument types are pairwise identical. Two types <var>S</var> and <var>T</var> are defined to be
                           identical if and only if <code>subtype(S, T)</code> and <code>subtype(T, S)</code>
                           both hold, where the subtype relation is defined in <xspecref spec="XP31" ref="id-seqtype-subtype"/>.</phrase></p><note diff="add" at="E"><p>Under this definition, a union type with <code>memberTypes="xs:double xs:decimal"</code>
                           is identical to a union type with <code>memberTypes="xs:decimal xs:double"</code>. However, two functions
                        whose signatures differ in this way will probably be deemed non-identical under rule (e) below, because they are likely to
                        have different effect when invoked with an argument of type <code>xs:untypedAtomic</code>.</p></note></item><item><p>Both functions have the same nonlocal variable bindings (sometimes called the function's closure).</p></item><item><p>The processor is able to determine that the implementations of the two functions are equivalent,
                        in the sense that for all possible combinations of arguments, the two functions have the same effect.</p></item></olist><note><p>There is no function or operator defined in the specification that tests whether two function items 
                        are identical. Where the specification requires two function items to be identical, for example in the 
                        results of repeated calls of a function whose result is a function, then the processor must ensure that 
                        it returns functions that are indistinguishable in their observable effect. Where the specification defines 
                        behavior conditional on two function items being identical, the determination of identity is to some degree 
                        implementation-dependent. There are cases where function items are definitely not identical (for example 
                        if they have different name or arity), but positive determination of identity is possible only using 
                        implementation-dependent techniques, for example when both items contain references to the same piece of 
                        code representing the function's implementation.
                     </p></note></item></olist><p>Some functions produce results that depend not only on their explicit arguments, 
                  but also on the static and dynamic context.</p><p><termdef id="dt-context-dependent" term="context-dependent">A function may have 
                  the property of being <term>context-dependent</term>: the result of such a
               function depends on the values of properties in the static and dynamic
               evaluation context as well as on the actual supplied arguments (if any).</termdef></p><p><termdef id="dt-context-independent" term="context-independent">A function that is
               not <termref def="dt-context-dependent">context-dependent</termref> is called 
                  <term>context-independent</term>.</termdef></p><p>A function that is context-dependent can be used as a named
               function reference, can be partially applied, and can be found using <code>fn:function-lookup</code>. 
               The principle in such cases is that the static context used for the function evaluation
               is taken from the static context of the named function reference, partial function application, or the call
               on <code>fn:function-lookup</code>; and the dynamic context for the function evaluation is taken from the dynamic
               context of the evaluation of the named function reference, partial function application, or the call
               of <code>fn:function-lookup</code>. In effect, the static and dynamic part of the context thus act
               as part of the closure of the function item.</p><p>Context-dependent functions fall into a number of categories:</p><olist><item><p>The functions <code>fn:current-date</code>, <code>fn:current-dateTime</code>, <code>fn:current-time</code>, 
                  <code>fn:default-language</code>, <code>fn:implicit-timezone</code>,
               <code>fn:adjust-date-to-timezone</code>, <code>fn:adjust-dateTime-to-timezone</code>, and
               <code>fn:adjust-time-to-timezone</code> depend on properties of the dynamic context that are
               fixed within the <termref def="execution-scope">execution scope</termref>. The same applies to a
               number of functions in the <code>op:</code> namespace that manipulate dates and times and
               that make use of the implicit timezone. These functions will return the same
               result if called repeatedly during a single <termref def="execution-scope">execution scope</termref>.</p></item><item><p>A number of functions including <code>fn:base-uri#0</code>, <code>fn:data#0</code>, 
                     <code>fn:document-uri#0</code>, <code>fn:element-with-id#1</code>, <code>fn:id#1</code>, 
                     <code>fn:idref#1</code>, <code>fn:lang#1</code>, <code>fn:last#0</code>, <code>fn:local-name#0</code>,
                     <code>fn:name#0</code>, <code>fn:namespace-uri#0</code>, <code>fn:normalize-space#0</code>, 
                     <code>fn:number#0</code>, <code>fn:path#0</code>, <code>fn:position#0</code>, 
                     <code>fn:root#0</code>, <code>fn:string#0</code>, and
               <code>fn:string-length#0</code> depend on the <phrase diff="chg" at="D"><xtermref ref="dt-focus" spec="XP31">focus</xtermref></phrase>. 
                     These functions will in general return
               different results on different calls if the focus is different.</p><p><termdef id="dt-focus-dependent" term="focus-dependent">A function is <term>focus-dependent</term>
                     if its result depends on the <phrase diff="chg" at="D"><xtermref ref="dt-focus" spec="XP31">focus</xtermref></phrase>
                     (that is, the context item, position, or size).</termdef></p><p><termdef id="dt-focus-independent" term="focus-dependent">A function that
                        is not <termref def="dt-focus-dependent">focus-dependent</termref> is called
                        <term>focus-independent</term></termdef></p></item><item><p>The function <code>fn:default-collation</code> and many string-handling operators and functions depend
               on the default collation and the in-scope collations, which are both properties
               of the static context. If a particular call of one of these functions is
               evaluated twice with the same arguments then it will return the same result
               each time (because the static context, by definition, does not change at run
               time). However, two distinct calls (that is, two calls on the function
               appearing in different places in the source code) may produce different results
               even if the explicit arguments are the same.</p></item><item><p>Functions such as <code>fn:static-base-uri</code>, <code>fn:doc</code>, and <code>fn:collection</code> depend on
               other aspects of the static context. As with functions that depend on
               collations, a single call will produce the same results on each call if the
               explicit arguments are the same, but two calls appearing in different places in
               the source code may produce different results.</p></item></olist><p>The <code>fn:function-lookup</code> function is a special case because it is
               potentially dependent on everything in the static and dynamic context. This is because the static and dynamic
               context of the call to <code>fn:function-lookup</code> are used as the static and dynamic context of the
               function that <code>fn:function-lookup</code> returns.</p><p><termdef id="dt-implicit-arguments" term="implicit argument">For a
                  <termref def="dt-context-dependent">context-dependent</termref> function, 
                  the parts of the context on which it depends are
               referred to as <term>implicit arguments</term>.</termdef></p><p><termdef id="dt-deterministic" term="deterministic">A function that is guaranteed to produce <termref def="dt-identical">identical</termref> results 
                  from repeated calls <phrase diff="add" at="Q">within a single <termref def="execution-scope">execution scope</termref></phrase>
               if the explicit and implicit arguments are identical is referred to as
               <term>deterministic</term>.</termdef></p><p><termdef id="dt-nondeterministic" term="nondeterministic">A function that is not
                  <termref def="dt-deterministic">deterministic</termref> is referred to as <term>nondeterministic</term>.</termdef></p><p>All functions defined in this specification are <termref def="dt-deterministic">deterministic</termref> unless otherwise stated.
               Exceptions include the following:</p><ulist><item><p><termdef id="dt-nondeterministic-wrt-ordering" term="nondeterministic with respect to ordering">Some 
                  functions (such as <code>fn:distinct-values</code>, <code>fn:unordered</code>, <phrase diff="add" at="E"><code>map:keys</code>,
                  and <code>map:for-each</code></phrase>) produce results in an
                  <termref def="implementation-defined">implementation-defined</termref> or 
                  <termref def="implementation-dependent">implementation-dependent</termref> order. 
                  In such cases two calls with the same arguments are not guaranteed to produce the results in the same order. These functions are
               said to be <term>nondeterministic with respect to ordering</term>.</termdef></p></item><item><p><phrase diff="chg" at="D">Some functions (such as <code>fn:analyze-string</code>,
                  <phrase diff="add" at="E"><code>fn:parse-xml</code>, <code>fn:parse-xml-fragment</code>,</phrase> and <code>fn:json-to-xml</code>) </phrase>
                  construct a tree of nodes to
               represent their results. There is no guarantee that repeated calls with the same
               arguments will return the same identical node (in the sense of the <code>is</code>
               operator). However, if non-identical nodes are returned, their content will be the
               same in the sense of the <code>fn:deep-equal</code> function. Such a function is said 
               to be <term>non-deterministic with respect to node identity</term>.</p></item><item><p>Some functions (such as <code>fn:doc</code> and <code>fn:collection</code>) create new nodes by reading external
               documents. Such functions are guaranteed to be <termref def="dt-deterministic">deterministic</termref> with the exception that
               an implementation is allowed to make them non-deterministic as a user option.</p></item></ulist><p>Where the results of a function are described as being (to a greater or lesser
                  extent) <termref def="implementation-defined">implementation-defined</termref> or 
                  <termref def="implementation-dependent">implementation-dependent</termref>, this does not by
               itself remove the requirement that the results should be deterministic: that is, that
               repeated calls with the same explicit and implicit arguments <rfc2119>must</rfc2119> return
               identical results.</p></div3></div2></div1><div1 id="accessors"><head>Accessors</head><p>Accessors and their semantics are described in <bibref ref="xpath-datamodel-31"/>. Some of
                these accessors are exposed to the user through the functions described below.</p><p>Each of these functions has an arity-zero signature which is equivalent to the arity-one
         form, with the context item supplied as the implicit first argument. In addition, each of the
         arity-one functions accepts an empty sequence as the argument, in which case it generally delivers
         an empty sequence as the result: the exception is <code>fn:string</code>, which delivers
         a zero-length string.</p><table role="data"><col width="25%" span="1"/><col width="25%" span="1"/><col width="25%" span="1"/><col width="25%" span="1"/><thead><tr><th rowspan="1" colspan="1">Function</th><th rowspan="1" colspan="1">Accessor</th><th rowspan="1" colspan="1">Accepts</th><th rowspan="1" colspan="1">Returns</th></tr></thead><tbody><tr><td rowspan="1" colspan="1">
                            <code>fn:node-name</code>
                        </td><td rowspan="1" colspan="1">
                            <code>node-name</code>
                        </td><td rowspan="1" colspan="1">node (optional)</td><td rowspan="1" colspan="1"><code>xs:QName</code> (optional)
                        </td></tr><tr><td rowspan="1" colspan="1">
                            <code>fn:nilled</code>
                        </td><td rowspan="1" colspan="1">
                            <code>nilled</code>
                        </td><td rowspan="1" colspan="1">node (optional)</td><td rowspan="1" colspan="1"><code>xs:boolean</code> (optional)
                        </td></tr><tr><td rowspan="1" colspan="1">
                            <code>fn:string</code>
                        </td><td rowspan="1" colspan="1">
                            <code>string-value</code>
                        </td><td rowspan="1" colspan="1">item (optional)</td><td rowspan="1" colspan="1">
                            <code>xs:string</code>
                        </td></tr><tr><td rowspan="1" colspan="1">
                            <code>fn:data</code>
                        </td><td rowspan="1" colspan="1">
                            <code>typed-value</code>
                        </td><td rowspan="1" colspan="1">zero or more items</td><td rowspan="1" colspan="1">a sequence of atomic values</td></tr><tr><td rowspan="1" colspan="1">
                            <code>fn:base-uri</code>
                        </td><td rowspan="1" colspan="1">
                            <code>base-uri</code>
                        </td><td rowspan="1" colspan="1">node (optional)</td><td rowspan="1" colspan="1"><code>xs:anyURI</code> (optional)
                        </td></tr><tr><td rowspan="1" colspan="1">
                            <code>fn:document-uri</code>
                        </td><td rowspan="1" colspan="1">
                            <code>document-uri</code>
                        </td><td rowspan="1" colspan="1">node (optional)</td><td rowspan="1" colspan="1"><code>xs:anyURI</code> (optional)
                        </td></tr></tbody></table><div2 id="func-node-name"><head>fn:node-name</head><glist><gitem><label>Summary</label><def><p>Returns the name of a node, as an <code>xs:QName</code>.</p></def></gitem><gitem><label>Signatures</label><def><example role="signature"><proto name="node-name" return-type="xs:QName?" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"/></example><example role="signature"><proto name="node-name" return-type="xs:QName?" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg" type="node()?"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>The zero-argument form of this function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-dependent">context-dependent</termref>,  and <termref def="dt-focus-dependent">focus-dependent</termref>. </p><p>The one-argument form of this function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>If the argument is omitted, it defaults to the context item (<code>.</code>). The
            behavior of the function if the argument is omitted is exactly the same as if the
            context item had been passed as the argument.</p><p>If <code>$arg</code> is the empty sequence, the empty sequence is returned.</p><p>Otherwise, the function returns the result of the <code>dm:node-name</code> accessor as
            defined in <bibref ref="xpath-datamodel-31"/> (see <xspecref spec="DM31" ref="dm-node-name"/>).</p></def></gitem><gitem><label>Error Conditions</label><def><p>The following errors may be raised when <code>$arg</code> is omitted:</p><ul><li>
               <p>If the context item is <xtermref ref="dt-absent" spec="DM31">absent</xtermref>,
                  dynamic error <xerrorref spec="XP" class="DY" code="0002" type="dynamic"/></p>
            </li><li>
               <p>If the context item is not a node, type error <xerrorref spec="XP" class="TY" code="0004" type="type"/>.</p>
            </li></ul></def></gitem><gitem><label>Notes</label><def><p role="note">For element and attribute nodes, the name of the node is returned as an
               <code>xs:QName</code>, retaining the prefix, namespace URI, and local part.</p><p role="note">For processing instructions, the name of the node is returned as an
               <code>xs:QName</code> in which the prefix and namespace URI are <xtermref ref="dt-absent" spec="DM31">absent</xtermref>.</p><p role="note">For a namespace node, the function returns an empty sequence if the node represents the
            default namespace; otherwise it returns an <code>xs:QName</code> in which prefix and
            namespace URI are <xtermref ref="dt-absent" spec="DM31">absent</xtermref> and the local
            part is the namespace prefix being bound.</p><p role="note">For all other kinds of node, the function returns the empty sequence.</p></def></gitem></glist></div2><div2 id="func-nilled"><head>fn:nilled</head><glist><gitem><label>Summary</label><def><p>Returns true for an element that is <term>nilled</term>.</p></def></gitem><gitem><label>Signatures</label><def><example role="signature"><proto name="nilled" return-type="xs:boolean?" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"/></example><example role="signature"><proto name="nilled" return-type="xs:boolean?" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg" type="node()?"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>The zero-argument form of this function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-dependent">context-dependent</termref>,  and <termref def="dt-focus-dependent">focus-dependent</termref>. </p><p>The one-argument form of this function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>If the argument is omitted, it defaults to the context item (<code>.</code>). The
            behavior of the function if the argument is omitted is exactly the same as if the
            context item had been passed as the argument.</p><p>If <code>$arg</code> is the empty sequence, the function returns the empty sequence.</p><p>Otherwise the function returns the result of the <code>dm:nilled</code> accessor as
            defined in <bibref ref="xpath-datamodel-31"/> (see <xspecref spec="DM31" ref="dm-nilled"/>).</p></def></gitem><gitem><label>Error Conditions</label><def><p>The following errors may be raised when <code>$arg</code> is omitted:</p><ul><li>
               <p>If the context item is <xtermref ref="dt-absent" spec="DM31">absent</xtermref>,
                  dynamic error <xerrorref spec="XP" class="DY" code="0002" type="dynamic"/></p>
            </li><li>
               <p>If the context item is not a node, type error <xerrorref spec="XP" class="TY" code="0004" type="type"/>.</p>
            </li></ul></def></gitem><gitem><label>Notes</label><def><p role="note">If <code>$arg</code> is not an element node, the function returns the empty
            sequence.</p><p role="note">If <code>$arg</code> is an untyped element node, the function returns false.</p><p role="note">In practice, the function returns <code>true</code> only for an element node that has
            the attribute <code>xsi:nil="true"</code> and that is successfully validated against a
            schema that defines the element to be nillable; the detailed rules, however, are defined
            in <bibref ref="xpath-datamodel-31"/>.</p></def></gitem></glist></div2><div2 id="func-string"><head>fn:string</head><glist><gitem><label>Summary</label><def><p>Returns the value of <code>$arg</code> represented as an <code>xs:string</code>.</p></def></gitem><gitem><label>Signatures</label><def><example role="signature"><proto name="string" return-type="xs:string" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"/></example><example role="signature"><proto name="string" return-type="xs:string" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg" type="item()?"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>The zero-argument form of this function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-dependent">context-dependent</termref>,  and <termref def="dt-focus-dependent">focus-dependent</termref>. </p><p>The one-argument form of this function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>In the zero-argument version of the function, <code>$arg</code> defaults to the context
            item. That is, calling <code>fn:string()</code> is equivalent to calling
               <code>fn:string(.)</code>.</p><p>If <code>$arg</code> is the empty sequence, the function returns the zero-length
            string.</p><p>If <var>$arg</var> is a node, the function returns the string value of the node, as obtained using the
                     <code>dm:string-value</code> accessor defined in <bibref ref="xpath-datamodel-31"/> (see <xspecref spec="DM31" ref="dm-string-value"/>).</p><p>If <var>$arg</var> is an atomic value, the function returns the result of the expression <code>$arg cast
                     as xs:string</code> (see <specref ref="casting"/>).</p><p>In all other cases, a dynamic error occurs (see below).</p></def></gitem><gitem><label>Error Conditions</label><def><p>A dynamic error is raised <xerrorref spec="XP" class="DY" code="0002" type="type"/> by
            the zero-argument version of the function if the context item is <xtermref ref="dt-absent" spec="DM31">absent</xtermref>. </p><p>A type error is raised <errorref class="TY" code="0014" type="type"/> if
               <code>$arg</code> is a function item (this includes maps and arrays).</p></def></gitem><gitem><label>Notes</label><def><p role="note">Every node has a string value, even an element with element-only
            content (which has no typed value). Moreover, casting an atomic value to a string always
            succeeds. Functions, maps, and arrays have no string value, so these are the
            only arguments that satisfy the type signature but cause failure.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>string(23)</code> returns <code>"23"</code>.</p><p>The expression <code>string(false())</code> returns <code>"false"</code>.</p><p>The expression <code>string("Paris")</code> returns <code>"Paris"</code>.</p><p>The expression <code>string((1, 2, 3))</code> raises error <code>XPTY0004</code>.</p><p>The expression <code>string([[1, 2], [3, 4]])</code> raises error <code>FOTY0014</code>.</p><p>The expression <code>string(abs#1)</code> raises error <code>FOTY0014</code>.</p><eg xml:space="preserve">let $para := 
&lt;para&gt;In a hole in the ground there lived a &lt;term author="Tolkien"&gt;hobbit&lt;/term&gt;.&lt;/para&gt;
         </eg><p>The expression <code>string($para)</code> returns <code>"In a hole in the ground there lived a hobbit."</code>.</p></def></gitem></glist></div2><div2 id="func-data"><head>fn:data</head><glist><gitem><label>Summary</label><def><p diff="chg" at="C">Returns the result of atomizing a sequence. This process flattens arrays, and replaces nodes by their typed values.</p></def></gitem><gitem><label>Signatures</label><def><example role="signature"><proto name="data" return-type="xs:anyAtomicType*" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"/></example><example role="signature"><proto name="data" return-type="xs:anyAtomicType*" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg" type="item()*"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>The zero-argument form of this function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-dependent">context-dependent</termref>,  and <termref def="dt-focus-dependent">focus-dependent</termref>. </p><p>The one-argument form of this function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>If the argument is omitted, it defaults to the context item (<code>.</code>). The
            behavior of the function if the argument is omitted is exactly the same as if the
            context item had been passed as the argument.</p><p> The result of <code>fn:data</code> is the sequence of atomic values produced by
            applying the following rules to each item in <code>$arg</code>:</p><ulist><item><p>If the item is an atomic value, it is appended to the result sequence.</p></item><item><p>If the item is a node, the typed value of the node is appended to the result
                  sequence. The typed value is a sequence of zero or more atomic values:
                  specifically, the result of the <code>dm:typed-value</code> accessor as defined in
                     <bibref ref="xpath-datamodel-31"/> (See <xspecref spec="DM31" ref="dm-typed-value"/>).</p></item><item diff="add" at="A"><p>If the item is an array, the result of applying <code>fn:data</code> to
                  each member of the array, in order, is appended to the result sequence.</p></item></ulist></def></gitem><gitem><label>Error Conditions</label><def><p>A type error is raised <errorref class="TY" code="0012" type="type"/> if an item in the
            sequence <code>$arg</code> is a node that does not have a typed value. </p><p>A type error is raised <errorref class="TY" code="0013" type="dynamic"/> if an item in
            the sequence <code>$arg</code> is a function item <phrase diff="add" at="A">other than
               an array</phrase>. </p><p>A dynamic error is raised if <code>$arg</code> is omitted and the context item is
               <xtermref ref="dt-absent" spec="DM31">absent</xtermref>.</p></def></gitem><gitem><label>Notes</label><def><p role="note">The process of applying the <code>fn:data</code> function to a sequence is referred to
            as <code>atomization</code>. In many cases an explicit call on <code>fn:data</code> is
            not required, because atomization is invoked implicitly when a node or sequence of nodes
            is supplied in a context where an atomic value or sequence of atomic values is
            required.</p><p role="note">The result of atomizing an empty sequence is an empty sequence.</p><p role="note">The result of atomizing an empty array is an empty sequence.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>data(123)</code> returns <code>123</code>.</p><p>The expression <code>data((123, 456))</code> returns <code>123, 456</code>.</p><p>The expression <code>data([[1,2],[3,4]])</code> returns <code>1, 2, 3, 4</code>.</p><eg xml:space="preserve">let $para := 
&lt;para&gt;In a hole in the ground there lived a &lt;term author="Tolkien"&gt;hobbit&lt;/term&gt;.&lt;/para&gt;
         </eg><p>The expression <code>data($para)</code> returns <code>xs:untypedAtomic("In a hole in the ground there lived a hobbit.")</code>.</p><p>The expression <code>data($para/term/@author)</code> returns <code>xs:untypedAtomic("Tolkien")</code>.</p><p>The expression <code>data(abs#1)</code> raises error <code>FOTY0013</code>.</p></def></gitem></glist></div2><div2 id="func-base-uri"><head>fn:base-uri</head><glist><gitem><label>Summary</label><def><p>Returns the base URI of a node.</p></def></gitem><gitem><label>Signatures</label><def><example role="signature"><proto name="base-uri" return-type="xs:anyURI?" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"/></example><example role="signature"><proto name="base-uri" return-type="xs:anyURI?" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg" type="node()?"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>The zero-argument form of this function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-dependent">context-dependent</termref>,  and <termref def="dt-focus-dependent">focus-dependent</termref>. </p><p>The one-argument form of this function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>The zero-argument version of the function returns the base URI of the context node: it
            is equivalent to calling <code>fn:base-uri(.)</code>.</p><p>The single-argument version of the function behaves as follows:</p><olist><item>If <code>$arg</code> is the empty sequence, the function returns the empty
               sequence.</item><item>Otherwise, the function returns the value of the <code>dm:base-uri</code> accessor
               applied to the node <code>$arg</code>. This accessor is defined, for each kind of
               node, in the XDM specification (See <xspecref spec="DM31" ref="dm-base-uri"/>).</item></olist><note>As explained in XDM, document, element and processing-instruction nodes have a
            base-uri property which may be empty. The base-uri property for all other node kinds is
            the empty sequence. The dm:base-uri accessor returns the base-uri property of a node if
            it exists and is non-empty; otherwise it returns the result of applying the dm:base-uri
            accessor to its parent, recursively. If the node does not have a parent, or if the
            recursive ascent up the ancestor chain encounters a parentless node whose base-uri
            property is empty, the empty sequence is returned. In the case of namespace nodes,
            however, the result is always an empty sequence — it does not depend on the base URI of
            the parent element.</note><p>See also <code>fn:static-base-uri</code>.</p></def></gitem><gitem><label>Error Conditions</label><def><p>The following errors may be raised when <code>$arg</code> is omitted:</p><ul><li>
               <p>If the context item is <xtermref ref="dt-absent" spec="DM31">absent</xtermref>,
                  dynamic error <xerrorref spec="XP" class="DY" code="0002" type="dynamic"/></p>
            </li><li>
               <p>If the context item is not a node, type error <xerrorref spec="XP" class="TY" code="0004" type="type"/>.</p>
            </li></ul></def></gitem></glist></div2><div2 id="func-document-uri"><head>fn:document-uri</head><glist><gitem><label>Summary</label><def><p>Returns the URI of a resource where a document can be found, if available.</p></def></gitem><gitem><label>Signatures</label><def><example role="signature"><proto name="document-uri" return-type="xs:anyURI?" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"/></example><example role="signature"><proto name="document-uri" return-type="xs:anyURI?" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg" type="node()?"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>The zero-argument form of this function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-dependent">context-dependent</termref>,  and <termref def="dt-focus-dependent">focus-dependent</termref>. </p><p>The one-argument form of this function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>If the argument is omitted, it defaults to the context item (<code>.</code>). The
            behavior of the function if the argument is omitted is exactly the same as if the
            context item had been passed as the argument.</p><p>If <code>$arg</code> is the empty sequence, the function returns the empty sequence.</p><p>If <code>$arg</code> is not a document node, the function returns the empty
            sequence.</p><p>Otherwise, the function returns the value of the <code>document-uri</code> accessor
            applied to <code>$arg</code>, as defined in <bibref ref="xpath-datamodel-31"/> (See
               <xspecref spec="DM31" ref="DocumentNodeAccessors"/>).</p></def></gitem><gitem><label>Error Conditions</label><def><p>The following errors may be raised when <code>$arg</code> is omitted:</p><ul><li>
               <p>If the context item is <xtermref ref="dt-absent" spec="DM31">absent</xtermref>,
                  dynamic error <xerrorref spec="XP" class="DY" code="0002" type="dynamic"/></p>
            </li><li>
               <p>If the context item is not a node, type error <xerrorref spec="XP" class="TY" code="0004" type="type"/>.</p>
            </li></ul></def></gitem><gitem><label>Notes</label><def><p role="note">In the case of a document node <code>$D</code> returned by the <code>fn:doc</code>
            function, or a document node at the root of a tree containing a node returned by the
               <code>fn:collection</code> function, it will always be true that either
               <code>fn:document-uri($D)</code> returns the empty sequence, or that the following
            expression is true: <code>fn:doc(fn:document-uri($D))</code> is <code>$D</code>. It is
               <termref def="implementation-defined">implementation-defined</termref> whether this guarantee also holds for
            document nodes obtained by other means, for example a document node passed as the
            initial context node of a query or transformation.</p></def></gitem></glist></div2></div1><div1 id="errors-and-diagnostics"><head>Errors and diagnostics</head><div2 id="errors"><head>Raising errors</head><p>In this document, as well as in <bibref ref="xquery-31"/> and <bibref ref="xpath-31"/>,
	            the phrase <quote>an error is raised</quote>
	                is used. Raising an error is equivalent to calling the <code>fn:error</code>
	                function defined in this section with the provided error code. Except where otherwise
	                specified, errors defined in this specification are dynamic errors. Some errors,
	                however, are classified as type errors. Type errors are typically used where the presence
	         of the error can be inferred from knowledge of the type of the actual arguments to a function, for
	         example with a call such as <code>fn:string(fn:abs#1)</code>. Host languages may allow type errors
	         to be reported statically if they are discovered during static analysis.</p><p> When function specifications indicate that an error is to be raised, the notation 
	            <quote>[<emph>error code</emph>]</quote>. os used to specify an error code. Each error defined
	                in this document is identified by an <code>xs:QName</code> that is in the
	                <code>http://www.w3.org/2005/xqt-errors</code> namespace, represented in this document by the <code>err</code> prefix. It is this
	                <code>xs:QName</code> that is actually passed as an argument to the
	                <code>fn:error</code> function. Calling this function raises an error.  For a
	                more detailed treatment of error handing, see <xspecref spec="XP31" ref="id-handling-dynamic"/>.</p><p>The <code>fn:error</code> function is a general function that may be called as above
	                but may also be called from <bibref ref="xquery-31"/> or <bibref ref="xpath-31"/>
	                applications with, for example, an <code>xs:QName</code> argument. </p><div3 id="func-error"><head>fn:error</head><glist><gitem><label>Summary</label><def><p>Calling the <code>fn:error</code> function raises an application-defined error.</p></def></gitem><gitem><label>Signatures</label><def><example role="signature"><proto name="error" return-type="none" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"/></example><example role="signature"><proto name="error" return-type="none" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="code" type="xs:QName?"/></proto></example><example role="signature"><proto name="error" return-type="none" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="code" type="xs:QName?"/><arg name="description" type="xs:string"/></proto></example><example role="signature"><proto name="error" return-type="none" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="code" type="xs:QName?"/><arg name="description" type="xs:string"/><arg name="error-object" type="item()*"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-nondeterministic">nondeterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>This function never returns a value. Instead it always raises an error. The effect of
            the error is identical to the effect of dynamic errors raised implicitly, for example
            when an incorrect argument is supplied to a function.</p><p>The parameters to the <code>fn:error</code> function supply information that is
            associated with the error condition and that is made available to a caller that asks for
            information about the error. The error may be caught either by the host language (using
            a try/catch construct in XSLT or XQuery, for example), or by the calling application or
            external processing environment. The way in which error information is returned to the
            external processing environment is <termref def="implementation-dependent">implementation-dependent</termref>.</p><p>There are three pieces of information that may be associated with an error:</p><ulist><item><p>The <code>$code</code> is an error code that distinguishes this error from others.
                  It is an <code>xs:QName</code>; the namespace URI conventionally identifies the
                  component, subsystem, or authority responsible for defining the meaning of the
                  error code, while the local part identifies the specific error condition. The
                  namespace URI <code>http://www.w3.org/2005/xqt-errors</code> is used for errors
                  defined in this specification; other namespace URIs may be used for errors defined
                  by the application.</p><p>If the external processing environment expects the error code to be returned as a
                  URI or a string rather than as an <code>xs:QName</code>, then an error code with
                  namespace URI <code>NS</code> and local part <code>LP</code> will be returned in
                  the form <code>NS#LP</code>. The namespace URI part of the error code should
                  therefore not include a fragment identifier.</p><p diff="add" at="B">If no value is supplied for the <code>$code</code> argument (that is,
                  if the function is called with no arguments or if the first argument is an empty sequence),
                  the effective value of the error code is <code>fn:QName('http://www.w3.org/2005/xqt-errors', 'err:FOER0000')</code>.</p></item><item><p>The <code>$description</code> is a natural-language description of the error
                  condition.</p><p diff="add" at="B-bug24359">If no value is supplied for the <code>$description</code>
                  argument (that is, if the function is called with less than two arguments), then the
                  effective value of the description is <termref def="implementation-dependent">implementation-dependent</termref>.</p></item><item><p>The <code>$error-object</code> is an arbitrary value used to convey additional
                  information about the error, and may be used in any way the application
                  chooses.</p><p diff="add" at="B-bug24359">If no value is supplied for the <code>$error-object</code>
                  argument (that is, if the function is called with less than three arguments), then the
                  effective value of the error object is <termref def="implementation-dependent">implementation-dependent</termref>.</p></item></ulist></def></gitem><gitem><label>Error Conditions</label><def><p>This function always raises a dynamic error. By default, it raises <errorref class="ER" code="0000"/></p></def></gitem><gitem><label>Notes</label><def><p role="note">The value of the <code>$description</code> parameter may need to be localized.</p><p role="note">The type <quote>none</quote> is a special type defined in <bibref ref="xquery-semantics"/> and is not available to the user. It indicates that the function never returns and
            ensures that it has the correct static type.</p><p role="note">Any QName may be used as an error code; there are no reserved names or namespaces. The
            error is always classified as a dynamic error, even if the error code used is one that
            is normally used for static errors or type errors.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>fn:error()</code> raises error <code>FOER0000</code>. <emph>(This returns the URI
                     <code>http://www.w3.org/2005/xqt-errors#FOER0000</code> (or the corresponding
                     <code>xs:QName</code>) to the external processing environment, unless the error
                  is caught using a try/catch construct in the host language.)</emph></p><p>The expression <code>fn:error(fn:QName('http://www.example.com/HR', 'myerr:toohighsal'),
                  'Does not apply because salary is too high')</code> raises error <code>myerr:toohighsal</code>. <emph>(This returns <code>http://www.example.com/HR#toohighsal</code> and the
                     <code>xs:string</code>
                  <code>"Does not apply because salary is too high"</code> (or the corresponding
                     <code>xs:QName</code>) to the external processing environment, unless the error
                  is caught using a try/catch construct in the host language.)</emph></p></def></gitem></glist></div3></div2><div2 id="diagnostics"><head>Diagnostic tracing</head><div3 id="func-trace"><head>fn:trace</head><glist><gitem><label>Summary</label><def><p>Provides an execution trace intended to be used in debugging queries.</p></def></gitem><gitem><label>Signatures</label><def><example role="signature"><proto name="trace" return-type="item()*" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="value" type="item()*"/></proto></example><example role="signature"><proto name="trace" return-type="item()*" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="value" type="item()*"/><arg name="label" type="xs:string"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>The function returns the value of <code>$value</code>, unchanged.</p><p>In addition, the values of <code>$value</code>, converted to an <code>xs:string</code>,
            and <code>$label</code> <phrase diff="add" at="B">(if supplied)</phrase>
            <rfc2119>may</rfc2119> be directed to a trace data set. The destination of the trace
            output is <termref def="implementation-defined">implementation-defined</termref>. The format of the trace output is
            <termref def="implementation-dependent">implementation-dependent</termref>. The ordering of output from calls of the
            <code>fn:trace</code> function is <termref def="implementation-dependent">implementation-dependent</termref>.</p></def></gitem><gitem><label>Notes</label><def><p role="note">Sometimes there is a need to output trace information unrelated to a specific value.
            In such cases it can be useful to set <code>$value</code> to an empty string or an empty
            sequence, and to compute the value of the <code>$label</code> argument: 
            <code>fn:trace((), "Processing item " || $i)</code>.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>Consider a situation in which a user wants to investigate the actual value passed to
               a function. Assume that in a particular execution, <code>$v</code> is an
                  <code>xs:decimal</code> with value <code>124.84</code>. Writing <code>fn:trace($v,
                  'the value of $v is:')</code> will put the strings <code>"124.84"</code> and
                  <code>"the value of $v is:"</code> in the trace data set in implementation
               dependent order.</p></def></gitem></glist></div3></div2></div1><div1 id="numeric-functions"><head>Functions and operators on numerics</head><p>This section specifies arithmetic operators on the numeric datatypes defined in
                    <bibref ref="xmlschema-2"/>.</p><div2 id="numeric-types"><head>Numeric types</head><p>The operators described in this section are defined on the following <phrase diff="chg" at="B">atomic</phrase>
                    types. Each type whose name is indented is derived from the type whose name
                    appears nearest above with one less level of indentation.</p><table border="0" summary="Numeric types" role="hierarchy"><tbody><tr><td rowspan="1" colspan="1">xs:decimal</td></tr><tr><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1">xs:integer</td></tr><tr><td rowspan="1" colspan="1">xs:float</td></tr><tr><td rowspan="1" colspan="1">xs:double</td></tr></tbody></table><p>They also apply to types derived by restriction from the above types. </p><p diff="add" at="B">The type <code>xs:numeric</code> is defined as a union type whose member types are
            (in order) <code>xs:double</code>, <code>xs:float</code>, and <code>xs:decimal</code>. This type is implicitly imported
            into the static context, so it can also be used in defining the signature of user-written functions. Apart from the fact that
            it is implicitly imported, it behaves exactly like a user-defined type with the same definition. This means, for example:</p><ulist diff="add" at="B"><item><p>If the expected type of a function parameter is given as <code>xs:numeric</code>, the actual value supplied
               can be an instance of any of these three types, or any type derived from these three by restriction (this includes the built-in
               type <code>xs:integer</code>, which is derived from <code>xs:decimal</code>).</p></item><item><p>If the expected type of a function parameter is given as <code>xs:numeric</code>, and the actual value supplied
                  is <code>xs:untypedAtomic</code> (or a node whose atomized value is <code>xs:untypedAtomic</code>), then it will
                  be cast to the union type <code>xs:numeric</code> using the rules in <specref ref="casting-to-union"/>.
               Because the lexical space of <code>xs:double</code> subsumes the lexical space of the other member types, and
               <code>xs:double</code> is listed first, the effect is that if the untyped atomic value is in the lexical space of
               <code>xs:double</code>, it will be converted to an <code>xs:double</code>, and if not, a dynamic error occurs.</p></item><item><p>When the return type of a function is given as <code>xs:numeric</code>, the actual value returned will be
               an instance of one of the three member types (and perhaps also of types derived from these by restriction). The rules
               for the particular function will specify how the type of the result depends on the values supplied as arguments.
               In many cases, for the functions in this specification, the result is defined to be the same type as the first
               argument.</p></item></ulist><note><p>
This specification uses  <bibref ref="ieee754-2008"/> arithmetic for <code>xs:float</code> and <code>xs:double</code> values.
One consequence of this is that some operations result in the value <code>NaN</code> (not-a number), which
has the unusual property that it is not equal to itself. Another consequence is that some operations return the value negative zero.
This differs from <bibref ref="xmlschema-2"/> which defines
<code>NaN</code> as being equal to itself and defines only a single zero in the value space.
 The text accompanying several functions defines behavior for both positive and negative zero inputs and outputs 
 in the interest of alignment with <bibref ref="ieee754-2008"/>. A conformant implementation must
 respect these semantics. In consequence, the expression <code>-0.0e0</code> (which is actually a unary minus operator 
    applied to an <code>xs:double</code> value) will always return negative zero: see <specref ref="func-numeric-unary-minus"/>. 
    As a concession to implementations that rely on implementations of XSD 1.0, however, when casting from string to double
 the lexical form <code>-0</code> <rfc2119>may</rfc2119> be converted to positive zero, though negative zero
 is <rfc2119>recommended</rfc2119>.
</p><p>XML Schema 1.1 introduces support for positive and negative zero as distinct values, and also uses the <bibref ref="ieee754-2008"/>
               semantics for comparisons involving <code>NaN</code>.</p></note></div2><div2 id="op.numeric"><head>Arithmetic operators on numeric values</head><p>The following functions define the semantics of arithmetic operators defined in 
			<bibref ref="xquery-31"/> and <bibref ref="xpath-31"/> on these numeric types. </p><table role="no-code-break data"><thead><tr><th rowspan="1" colspan="1">Operator</th><th rowspan="1" colspan="1">Meaning</th></tr></thead><tbody><tr><td rowspan="1" colspan="1">
                                <code>op:numeric-add</code>
                            </td><td rowspan="1" colspan="1">Addition</td></tr><tr><td rowspan="1" colspan="1">
                                <code>op:numeric-subtract</code>
                            </td><td rowspan="1" colspan="1">Subtraction</td></tr><tr><td rowspan="1" colspan="1">
                                <code>op:numeric-multiply</code>
                            </td><td rowspan="1" colspan="1">Multiplication</td></tr><tr><td rowspan="1" colspan="1">
                                <code>op:numeric-divide</code>
                            </td><td rowspan="1" colspan="1">Division</td></tr><tr><td rowspan="1" colspan="1">
                                <code>op:numeric-integer-divide</code>
                            </td><td rowspan="1" colspan="1">Integer division</td></tr><tr><td rowspan="1" colspan="1">
                                <code>op:numeric-mod</code>
                            </td><td rowspan="1" colspan="1">Modulus</td></tr><tr><td rowspan="1" colspan="1">
                                <code>op:numeric-unary-plus</code>
                            </td><td rowspan="1" colspan="1">Unary plus</td></tr><tr><td rowspan="1" colspan="1">
                                <code>op:numeric-unary-minus</code>
                            </td><td rowspan="1" colspan="1">Unary minus (negation)</td></tr></tbody></table><p><phrase diff="chg" at="B">The parameters and return types for the above operators are in most cases declared to be of type
               <code>xs:numeric</code>, which permits the basic numeric
                    types: <code>xs:integer</code>, <code>xs:decimal</code>, <code>xs:float</code>
                    and <code>xs:double</code>, and types derived from them.
               In general the two-argument functions require that both arguments are of the same primitive type,
            and they return a value of this same type.</phrase>
               The exceptions are <code>op:numeric-divide</code>, which returns
                    an <code>xs:decimal</code> if called with two <code>xs:integer</code> operands,
                    and <code>op:numeric-integer-divide</code> which always returns an <code>xs:integer</code>.</p><p>If the two operands of an arithmetic expression are not of the same type, <emph>subtype substitution</emph>
                    and <emph>numeric type promotion</emph> are used to obtain two operands of the
                    same type. <xspecref spec="XP31" ref="promotion"/> and <xspecref spec="XP31" ref="mapping"/> describe the semantics of these operations in
                    detail. </p><p>The result type of operations depends on their argument datatypes and is defined
                    in the following table:</p><table role="no-code-break data"><thead><tr><th rowspan="1" colspan="1">Operator</th><th rowspan="1" colspan="1">Returns</th></tr></thead><tbody><tr><td rowspan="1" colspan="1">
                                <code>op:operation(xs:integer, xs:integer)</code>
                            </td><td rowspan="1" colspan="1">
                                <code>xs:integer</code> (except for <code>op:numeric-divide(integer,
                                integer)</code>, which returns <code>xs:decimal</code>)</td></tr><tr><td rowspan="1" colspan="1">
                                <code>op:operation(xs:decimal, xs:decimal)</code>
                            </td><td rowspan="1" colspan="1">
                                <code>xs:decimal</code>
                            </td></tr><tr><td rowspan="1" colspan="1">
                                <code>op:operation(xs:float, xs:float)</code>
                            </td><td rowspan="1" colspan="1">
                                <code>xs:float</code>
                            </td></tr><tr><td rowspan="1" colspan="1">
                                <code>op:operation(xs:double, xs:double)</code>
                            </td><td rowspan="1" colspan="1">
                                <code>xs:double</code>
                            </td></tr><tr><td rowspan="1" colspan="1">
                                <code>op:operation(xs:integer)</code>
                            </td><td rowspan="1" colspan="1">
                                <code>xs:integer</code>
                            </td></tr><tr><td rowspan="1" colspan="1">
                                <code>op:operation(xs:decimal)</code>
                            </td><td rowspan="1" colspan="1">
                                <code>xs:decimal</code>
                            </td></tr><tr><td rowspan="1" colspan="1">
                                <code>op:operation(xs:float)</code>
                            </td><td rowspan="1" colspan="1">
                                <code>xs:float</code>
                            </td></tr><tr><td rowspan="1" colspan="1">
                                <code>op:operation(xs:double)</code>
                            </td><td rowspan="1" colspan="1">
                                <code>xs:double</code>
                            </td></tr></tbody></table><p>These rules define any operation on any pair of arithmetic types. Consider the
                    following example:</p><eg xml:space="preserve">op:operation(xs:int, xs:double) =&gt; op:operation(xs:double, xs:double)</eg><p>For this operation, <code>xs:int</code> must be converted to
                    <code>xs:double</code>. This can be done, since by the rules above:
                    <code>xs:int</code> can be substituted for <code>xs:integer</code>,
                    <code>xs:integer</code> can be substituted for <code>xs:decimal</code>,
                    <code>xs:decimal</code> can be promoted to <code>xs:double</code>. As far as possible, the promotions should be done in a
                    single step. Specifically, when an <code>xs:decimal</code> is promoted to an
                    <code>xs:double</code>, it should not be converted to an <code>xs:float</code>
                    and then to <code>xs:double</code>, as this risks loss of precision.</p><p>As another example, a user may define <code>height</code> as a derived type of
                    <code>xs:integer</code> with a minimum value of 20 and a maximum value of 100.
                    They may then derive <code>fenceHeight</code> using an enumeration to restrict the
                    permitted set of values to, say, 36, 48 and 60.</p><eg xml:space="preserve">op:operation(fenceHeight, xs:integer) =&gt; op:operation(xs:integer, xs:integer)</eg><p>
                    <code>fenceHeight</code> can be substituted for its base type
                    <code>height</code> and <code>height</code> can be substituted for its base type
                    <code>xs:integer</code>. </p><p>The basic rules for addition, subtraction, and multiplication
			of ordinary numbers are not set out in this specification; they are taken as given. In the case of <code>xs:double</code>
			and <code>xs:float</code> the rules are as defined in <bibref ref="ieee754-2008"/>. The rules for handling
			division and modulus operations, as well as the rules for handling special values such as infinity and <code>NaN</code>,
			and exception conditions such as overflow and underflow, are described more explicitly since they are not necessarily obvious.</p><p>On overflow and underflow situations during arithmetic operations conforming
                    implementations <rfc2119>must</rfc2119> behave as follows:</p><ulist><item><p>For <code>xs:float</code> and <code>xs:double</code> operations, overflow
                            behavior <rfc2119>must</rfc2119> be conformant with <bibref ref="ieee754-2008"/>. This specification allows the following options:</p><ulist><item><p>Raising a dynamic error <errorref class="AR" code="0002"/> via an
                                    overflow trap.</p></item><item><p>Returning <code>INF</code> or <code>-INF</code>.</p></item><item><p>Returning the largest (positive or negative) non-infinite number.</p></item></ulist></item><item><p>For <code>xs:float</code> and <code>xs:double</code> operations,
                            underflow behavior <rfc2119>must</rfc2119> be conformant with <bibref ref="ieee754-2008"/>. This specification allows the following options:</p><ulist><item><p>Raising a dynamic error <errorref class="AR" code="0002"/> via an
                                    underflow trap.</p></item><item><p>Returning <code>0.0E0</code> or <code>+/- 2**Emin</code> or a
                                    denormalized value; where <code>Emin</code> is the smallest
                                    possible <code>xs:float</code> or <code>xs:double</code> exponent.</p></item></ulist></item><item><p>For <code>xs:decimal</code> operations, overflow behavior <rfc2119>must</rfc2119> 
                     raise a dynamic error <errorref class="AR" code="0002"/>. On
                            underflow, <code>0.0</code> must be returned.</p></item><item><p>For <code>xs:integer</code> operations, implementations that support
                            limited-precision integer operations <rfc2119>must</rfc2119> select from
                            the following options:</p><ulist><item><p> They <rfc2119>may</rfc2119> choose to always raise a dynamic
                                        error <errorref class="AR" code="0002"/>.</p></item><item><p> They <rfc2119>may</rfc2119> provide an <termref def="implementation-defined"/> mechanism that allows users to
                                    choose between raising an error and returning a result that is
                                    modulo the largest representable integer value. See <bibref ref="ISO10967"/>.</p></item></ulist></item></ulist><p>The functions <code>op:numeric-add</code>, <code>op:numeric-subtract</code>,
                    <code>op:numeric-multiply</code>, <code>op:numeric-divide</code>,
                    <code>op:numeric-integer-divide</code> and <code>op:numeric-mod</code> are each
                    defined for pairs of numeric operands, each of which has the same
                    type:<code>xs:integer</code>, <code>xs:decimal</code>, <code>xs:float</code>, or
                    <code>xs:double</code>. The functions <code>op:numeric-unary-plus</code> and
                    <code>op:numeric-unary-minus</code> are defined for a single operand whose type
                    is one of those same numeric types.</p><p> For <code>xs:float</code> and <code>xs:double</code> arguments, if either
                    argument is <code>NaN</code>, the result is <code>NaN</code>.</p><p>For <code>xs:decimal</code> values<phrase diff="add" at="D">, let <var>N</var> be the number of digits
            of precision supported by the implementation, and let <var>M</var> (<code>M &lt;= N</code>) be the minimum limit on the number of digits
            required for conformance (18 digits for XSD 1.0, 16 digits for XSD 1.1). Then for addition, subtraction, and multiplication
               operations, the returned result <rfc2119>should</rfc2119> be accurate to <var>N</var> digits of precision, and for division and modulus operations,
               the returned result <rfc2119>should</rfc2119> be accurate to at least <var>M</var> digits of precision.</phrase> 
               The actual precision is <termref def="implementation-defined"/>. If the number
                    of digits in the mathematical result exceeds the number of digits that the implementation
                    retains for that operation, the result is truncated or rounded in an <termref def="implementation-defined"/> manner.</p><note><p diff="add" at="D">This Recommendation does not specify whether <code>xs:decimal</code> operations are fixed point or floating point.
            In an implementation using floating point it is possible for very simple operations to require more digits of precision than
            are available; for example adding <code>1e100</code> to <code>1e-100</code> requires 200 digits of precision for an
               accurate representation of the result.</p></note><p>The <bibref ref="ieee754-2008"/> specification also describes handling of
            two exception conditions called <code>divideByZero</code> and <code>invalidOperation</code>. The 
            IEEE <code>divideByZero</code> exception is raised not only by a direct attempt to divide by zero, but also by
            operations such as <code>log(0)</code>. The IEEE <code>invalidOperation</code> exception is raised by
            attempts to call a function with an argument that is outside the function's domain (for example,
            <code>sqrt(-1)</code> or <code>log(-1)</code>). 
               <phrase diff="add" at="D">Although IEEE defines these as exceptions, it also defines "default non-stop exception handling" in 
                  which the operation returns a defined result, typically positive or negative infinity, or NaN. With this 
                  function library,</phrase>
               these IEEE exceptions do not cause a dynamic error
            at the application level; rather they result in the relevant function or operator returning
            <phrase diff="chg" at="D">the defined non-error result.</phrase> 
               The underlying IEEE exception <rfc2119>may</rfc2119> be notified to the application
            or to the user by some <termref def="implementation-defined">implementation-defined</termref>
               warning condition, but the observable effect on an application 
               using the functions and operators defined in this specification is simply to return
               <phrase diff="chg" at="D">the defined 
                  result (typically -INF, +INF, or NaN)</phrase> with no error.</p><p>The <bibref ref="ieee754-2008"/> specification distinguishes two NaN values,
               a quiet NaN and a signaling NaN. These two values are not distinguishable in the XDM model:
               the value spaces of <code>xs:float</code> and <code>xs:double</code> each include only a single
               <code>NaN</code> value. This does not prevent the implementation distinguishing them internally,
               and triggering different <termref def="implementation-defined">implementation-defined</termref>
               warning conditions, but such distinctions do not affect the observable behavior of an application 
               using the functions and operators defined in this specification.</p><div3 id="func-numeric-add"><head>op:numeric-add</head><glist><gitem><label>Summary</label><def><p>Returns the arithmetic sum of its operands: (<code>$arg1 + $arg2</code>).</p></def></gitem><gitem><label>Operator Mapping</label><def><p>Defines the semantics of the "+" operator when
         applied to two numeric values</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="numeric-add" return-type="xs:numeric" isOp="yes" prefix="op" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg1" type="xs:numeric"/><arg name="arg2" type="xs:numeric"/></proto></example></def></gitem><gitem><label>Rules</label><def><p>General rules: see <specref ref="op.numeric"/>.</p></def></gitem><gitem><label>Notes</label><def><p role="note"> For <code>xs:float</code> or <code>xs:double</code> values, if one of the operands is a
            zero or a finite number and the other is <code>INF</code> or <code>-INF</code>,
               <code>INF</code> or <code>-INF</code> is returned. If both operands are
               <code>INF</code>, <code>INF</code> is returned. If both operands are
               <code>-INF</code>, <code>-INF</code> is returned. If one of the operands is
               <code>INF</code> and the other is <code>-INF</code>, <code>NaN</code> is
            returned.</p></def></gitem></glist></div3><div3 id="func-numeric-subtract"><head>op:numeric-subtract</head><glist><gitem><label>Summary</label><def><p>Returns the arithmetic difference of its operands: (<code>$arg1 - $arg2</code>).</p></def></gitem><gitem><label>Operator Mapping</label><def><p>Defines the semantics of the "-" operator when
         applied to two numeric values. </p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="numeric-subtract" return-type="xs:numeric" isOp="yes" prefix="op" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg1" type="xs:numeric"/><arg name="arg2" type="xs:numeric"/></proto></example></def></gitem><gitem><label>Rules</label><def><p>General rules: see <specref ref="op.numeric"/>.</p></def></gitem><gitem><label>Notes</label><def><p role="note"> For <code>xs:float</code> or <code>xs:double</code> values, if one of the operands is a
            zero or a finite number and the other is <code>INF</code> or <code>-INF</code>, an
            infinity of the appropriate sign is returned. If both operands are <code>INF</code> or
               <code>-INF</code>, <code>NaN</code> is returned. If one of the operands is
               <code>INF</code> and the other is <code>-INF</code>, an infinity of the appropriate
            sign is returned.</p></def></gitem></glist></div3><div3 id="func-numeric-multiply"><head>op:numeric-multiply</head><glist><gitem><label>Summary</label><def><p>Returns the arithmetic product of its operands: (<code>$arg1 * $arg2</code>).</p></def></gitem><gitem><label>Operator Mapping</label><def><p>Defines the semantics of the "*" operator when
         applied to two numeric values.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="numeric-multiply" return-type="xs:numeric" isOp="yes" prefix="op" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg1" type="xs:numeric"/><arg name="arg2" type="xs:numeric"/></proto></example></def></gitem><gitem><label>Rules</label><def><p>General rules: see <specref ref="op.numeric"/>.</p></def></gitem><gitem><label>Notes</label><def><p role="note"> For <code>xs:float</code> or <code>xs:double</code> values, if one of the operands is a
            zero and the other is an infinity, <code>NaN</code> is returned. If one of the operands
            is a non-zero number and the other is an infinity, an infinity with the appropriate sign
            is returned.</p></def></gitem></glist></div3><div3 id="func-numeric-divide"><head>op:numeric-divide</head><glist><gitem><label>Summary</label><def><p>Returns the arithmetic quotient of its operands: (<code>$arg1 div $arg2</code>).</p></def></gitem><gitem><label>Operator Mapping</label><def><p>Defines the semantics of the "div" operator when
         applied to two numeric values.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="numeric-divide" return-type="xs:numeric" isOp="yes" prefix="op" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg1" type="xs:numeric"/><arg name="arg2" type="xs:numeric"/></proto></example></def></gitem><gitem><label>Rules</label><def><p>General rules: see <specref ref="op.numeric"/>.</p><p>As a special case, if the types of both <code>$arg1</code> and <code>$arg2</code> are
               <code>xs:integer</code>, then the return type is <code>xs:decimal</code>.</p></def></gitem><gitem><label>Error Conditions</label><def><p>A dynamic error is raised <errorref class="AR" code="0001"/> for <code>xs:decimal</code>
            and <code>xs:integer</code> operands, if the divisor is (positive or negative) zero.</p></def></gitem><gitem><label>Notes</label><def><p role="note">For <code>xs:float</code> and <code>xs:double</code> operands, floating point division
            is performed as specified in <bibref ref="ieee754-2008"/>. A positive number divided by
            positive zero returns <code>INF</code>. A negative number divided by positive zero
            returns <code>-INF</code>. Division by negative zero returns <code>-INF</code> and
               <code>INF</code>, respectively. Positive or negative zero divided by positive or
            negative zero returns <code>NaN</code>. Also, <code>INF</code> or <code>-INF</code>
            divided by <code>INF</code> or <code>-INF</code> returns <code>NaN</code>.</p></def></gitem></glist></div3><div3 id="func-numeric-integer-divide"><head>op:numeric-integer-divide</head><glist><gitem><label>Summary</label><def><p>Performs an integer division.</p></def></gitem><gitem><label>Operator Mapping</label><def><p>Defines the semantics of the "idiv" operator when
         applied to two numeric values.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="numeric-integer-divide" return-type="xs:integer" isOp="yes" prefix="op" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg1" type="xs:numeric"/><arg name="arg2" type="xs:numeric"/></proto></example></def></gitem><gitem><label>Rules</label><def><p>General rules: see <specref ref="op.numeric"/>.</p><p>If <code>$arg2</code> is <code>INF</code> or <code>-INF</code>, and <code>$arg1</code>
            is not <code>INF</code> or <code>-INF</code>, then the result is zero.</p><p>Otherwise, subject to limits of precision and overflow/underflow conditions, the result
            is the largest (furthest from zero) <code>xs:integer</code> value <code>$N</code> such
            that the following expression is true:</p><eg xml:space="preserve">fn:abs($N * $arg2) le fn:abs($arg1) 
               and fn:compare($N * $arg2, 0) eq fn:compare($arg1, 0).</eg><note><p>The second term in this condition ensures that the result has the correct sign.</p></note><p>The implementation may adopt a different algorithm provided that it is equivalent to
            this formulation in all cases where <termref def="implementation-dependent">implementation-dependent</termref> or <termref def="implementation-defined">implementation-defined</termref> behavior does not affect the outcome, for example,
            the implementation-defined precision of the result of <code>xs:decimal</code>
            division.</p></def></gitem><gitem><label>Error Conditions</label><def><p>A dynamic error is raised <errorref class="AR" code="0001"/> if the divisor is (positive
            or negative) zero.</p><p>A dynamic error is raised <errorref class="AR" code="0002"/> if either operand is
               <code>NaN</code> or if <code>$arg1</code> is <code>INF</code> or
            <code>-INF</code>.</p></def></gitem><gitem><label>Notes</label><def><p role="note">Except in situations involving errors, loss of precision, or overflow/underflow, the
            result of <code>$a idiv $b</code> is the same as <code>($a div $b) cast as
               xs:integer</code>.</p><p role="note">The semantics of this function are different from integer division as defined in
            programming languages such as Java and C++.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>op:numeric-integer-divide(10,3)</code> returns <code>3</code>.</p><p>The expression <code>op:numeric-integer-divide(3,-2)</code> returns <code>-1</code>.</p><p>The expression <code>op:numeric-integer-divide(-3,2)</code> returns <code>-1</code>.</p><p>The expression <code>op:numeric-integer-divide(-3,-2)</code> returns <code>1</code>.</p><p>The expression <code>op:numeric-integer-divide(9.0,3)</code> returns <code>3</code>.</p><p>The expression <code>op:numeric-integer-divide(-3.5,3)</code> returns <code>-1</code>.</p><p>The expression <code>op:numeric-integer-divide(3.0,4)</code> returns <code>0</code>.</p><p>The expression <code>op:numeric-integer-divide(3.1E1,6)</code> returns <code>5</code>.</p><p>The expression <code>op:numeric-integer-divide(3.1E1,7)</code> returns <code>4</code>.</p></def></gitem></glist></div3><div3 id="func-numeric-mod"><head>op:numeric-mod</head><glist><gitem><label>Summary</label><def><p>Returns the remainder resulting from dividing <code>$arg1</code>, the dividend, by
               <code>$arg2</code>, the divisor. </p></def></gitem><gitem><label>Operator Mapping</label><def><p>Defines the semantics of the "mod" operator when
         applied to two numeric values.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="numeric-mod" return-type="xs:numeric" isOp="yes" prefix="op" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg1" type="xs:numeric"/><arg name="arg2" type="xs:numeric"/></proto></example></def></gitem><gitem><label>Rules</label><def><p>General rules: see <specref ref="op.numeric"/>.</p><p>The operation <code>a mod b</code> for operands that are <code>xs:integer</code> or
               <code>xs:decimal</code>, or types derived from them, produces a result such that
               <code>(a idiv b)*b+(a mod b)</code> is equal to <code>a</code> and the magnitude of
            the result is always less than the magnitude of <code>b</code>. This identity holds even
            in the special case that the dividend is the negative integer of largest possible
            magnitude for its type and the divisor is -1 (the remainder is 0). It follows from this
            rule that the sign of the result is the sign of the dividend.</p><p> For <code>xs:float</code> and <code>xs:double</code> operands the following rules
            apply:</p><ulist><item><p>If either operand is <code>NaN</code>, the result is <code>NaN</code>.</p></item><item><p>If the dividend is positive or negative infinity, or the divisor is positive or
                  negative zero (0), or both, the result is <code>NaN</code>.</p></item><item><p>If the dividend is finite and the divisor is an infinity, the result equals the
                  dividend.</p></item><item><p>If the dividend is positive or negative zero and the divisor is finite, the result
                  is the same as the dividend.</p></item><item><p>In the remaining cases, where neither positive or negative infinity, nor positive
                  or negative zero, nor <code>NaN</code> is involved, the result obeys <code>(a idiv
                     b)*b+(a mod b)</code> = <code>a</code>.
                  
                  Division is truncating division, analogous to integer division, not <bibref ref="ieee754-2008"/> rounding division i.e. additional digits are truncated,
                  not rounded to the required precision.</p></item></ulist></def></gitem><gitem><label>Error Conditions</label><def><p>A dynamic error is raised <errorref class="AR" code="0001"/> for <code>xs:integer</code>
            and <code>xs:decimal</code> operands, if <code>$arg2</code> is zero.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>op:numeric-mod(10,3)</code> returns <code>1</code>.</p><p>The expression <code>op:numeric-mod(6,-2)</code> returns <code>0</code>.</p><p>The expression <code>op:numeric-mod(4.5,1.2)</code> returns <code>0.9</code>.</p><p>The expression <code>op:numeric-mod(1.23E2, 0.6E1)</code> returns <code>3.0E0</code>.</p></def></gitem></glist></div3><div3 id="func-numeric-unary-plus"><head>op:numeric-unary-plus</head><glist><gitem><label>Summary</label><def><p>Returns its operand with the sign unchanged: (<code>+ $arg</code>).</p></def></gitem><gitem><label>Operator Mapping</label><def><p>Defines the semantics of the unary "+" operator
         applied to a numeric value.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="numeric-unary-plus" return-type="xs:numeric" isOp="yes" prefix="op" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg" type="xs:numeric"/></proto></example></def></gitem><gitem><label>Rules</label><def><p>General rules: see <specref ref="op.numeric"/>.</p><p>The returned value is equal to <code>$arg</code>, and is an instance of
               <code>xs:integer</code>, <code>xs:decimal</code>, <code>xs:double</code>, or
               <code>xs:float</code> depending on the type of <code>$arg</code>.</p></def></gitem><gitem><label>Notes</label><def><p role="note">Because function conversion rules are applied in the normal way, the unary
               <code>+</code> operator can be used to force conversion of an untyped node to a
            number: the result of <code>+@price</code> is the same as <code>xs:double(@price)</code>
            if the type of <code>@price</code> is <code>xs:untypedAtomic</code>.</p></def></gitem></glist></div3><div3 id="func-numeric-unary-minus"><head>op:numeric-unary-minus</head><glist><gitem><label>Summary</label><def><p>Returns its operand with the sign reversed: (<code>- $arg</code>).</p></def></gitem><gitem><label>Operator Mapping</label><def><p>Defines the semantics of the unary "-" operator when
         applied to a numeric value.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="numeric-unary-minus" return-type="xs:numeric" isOp="yes" prefix="op" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg" type="xs:numeric"/></proto></example></def></gitem><gitem><label>Rules</label><def><p>General rules: see <specref ref="op.numeric"/>.</p><p>The returned value is an instance of <code>xs:integer</code>, <code>xs:decimal</code>,
               <code>xs:double</code>, or <code>xs:float</code> depending on the type of
               <code>$arg</code>.</p><p>For <code>xs:integer</code> and <code>xs:decimal</code> arguments, <code>0</code> and
               <code>0.0</code> return <code>0</code> and <code>0.0</code>, respectively. For
               <code>xs:float</code> and <code>xs:double</code> arguments, <code>NaN</code> returns
               <code>NaN</code>, <code>0.0E0</code> returns <code>-0.0E0</code> and vice versa.
               <code>INF</code> returns <code>-INF</code>. <code>-INF</code> returns
               <code>INF</code>.</p></def></gitem></glist></div3></div2><div2 id="comp.numeric"><head>Comparison operators on numeric values</head><p>This specification defines 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 as described
                    above in <specref ref="op.numeric"/>. Each comparison operator returns a boolean
                    value. If either, or both, operands are <code>NaN</code>, <code>false</code> is
                    returned. </p><table class="index"><thead><tr><th rowspan="1" colspan="1">Function</th><th rowspan="1" colspan="1">Meaning</th></tr></thead><tbody><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">op:numeric-equal</code></td><td rowspan="1" colspan="1">Returns true if and only if the value of <code>$arg1</code> is equal to the value of
               <code>$arg2</code>.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">op:numeric-less-than</code></td><td rowspan="1" colspan="1">Returns <code>true</code> if and only if <code>$arg1</code> is numerically less than
               <code>$arg2</code>. </td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">op:numeric-greater-than</code></td><td rowspan="1" colspan="1">Returns <code>true</code> if and only if <code>$arg1</code> is numerically greater than
               <code>$arg2</code>.</td></tr></tbody></table><div3 id="func-numeric-equal"><head>op:numeric-equal</head><glist><gitem><label>Summary</label><def><p>Returns true if and only if the value of <code>$arg1</code> is equal to the value of
               <code>$arg2</code>.</p></def></gitem><gitem><label>Operator Mapping</label><def><p>Defines the semantics of
         the "eq" operator when applied to two numeric values, and is also used in defining the
         semantics of "ne", "le" and "ge".</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="numeric-equal" return-type="xs:boolean" isOp="yes" prefix="op" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg1" type="xs:numeric"/><arg name="arg2" type="xs:numeric"/></proto></example></def></gitem><gitem><label>Rules</label><def><p>General rules: see <specref ref="op.numeric"/> and <specref ref="comp.numeric"/>.</p><p> For <code>xs:float</code> and <code>xs:double</code> values, positive zero and negative
            zero compare equal. <code>INF</code> equals <code>INF</code>, and <code>-INF</code>
            equals <code>-INF</code>. <code>NaN</code> does not equal itself.</p></def></gitem></glist></div3><div3 id="func-numeric-less-than"><head>op:numeric-less-than</head><glist><gitem><label>Summary</label><def><p>Returns <code>true</code> if and only if <code>$arg1</code> is numerically less than
               <code>$arg2</code>. </p></def></gitem><gitem><label>Operator Mapping</label><def><p>Defines the semantics of the
         "lt" operator when applied to two numeric values, and is also used in defining the
         semantics of "le".</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="numeric-less-than" return-type="xs:boolean" isOp="yes" prefix="op" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg1" type="xs:numeric"/><arg name="arg2" type="xs:numeric"/></proto></example></def></gitem><gitem><label>Rules</label><def><p>General rules: see <specref ref="op.numeric"/> and <specref ref="comp.numeric"/>.</p><p>For <code>xs:float</code> and <code>xs:double</code> values, positive infinity is
            greater than all other non-<code>NaN</code> values; negative infinity is less than all
            other non-<code>NaN</code> values. If <code>$arg1</code> or <code>$arg2</code> is
               <code>NaN</code>, the function returns <code>false</code>.</p></def></gitem></glist></div3><div3 id="func-numeric-greater-than"><head>op:numeric-greater-than</head><glist><gitem><label>Summary</label><def><p>Returns <code>true</code> if and only if <code>$arg1</code> is numerically greater than
               <code>$arg2</code>.</p></def></gitem><gitem><label>Operator Mapping</label><def><p>Defines the semantics of the
         "gt" operator when applied to two numeric values, and is also used in defining the
         semantics of "ge".</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="numeric-greater-than" return-type="xs:boolean" isOp="yes" prefix="op" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg1" type="xs:numeric"/><arg name="arg2" type="xs:numeric"/></proto></example></def></gitem><gitem><label>Rules</label><def><p>The function call <code>op:numeric-greater-than($A, $B)</code> is defined to return the
            same result as <code>op:numeric-less-than($B, $A)</code></p></def></gitem></glist></div3></div2><div2 id="numeric-value-functions"><head>Functions on numeric values</head><p>The following functions are defined on numeric types. Each function returns a
                    value of the same type as the type of its argument.</p><ulist><item><p>If the argument is the empty sequence, the empty sequence is returned.</p></item><item><p>For <code>xs:float</code> and <code>xs:double</code> arguments, if the
                            argument is "NaN", "NaN" is returned.</p></item><item><p>Except for <code>fn:abs</code>, for <code>xs:float</code> and
                            <code>xs:double</code> arguments, if the argument is positive or
                            negative infinity, positive or negative infinity is returned.</p></item></ulist><table class="index"><thead><tr><th rowspan="1" colspan="1">Function</th><th rowspan="1" colspan="1">Meaning</th></tr></thead><tbody><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:abs</code></td><td rowspan="1" colspan="1">Returns the absolute value of <code>$arg</code>.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:ceiling</code></td><td rowspan="1" colspan="1">Rounds <code>$arg</code> upwards to a whole number.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:floor</code></td><td rowspan="1" colspan="1">Rounds <code>$arg</code> downwards to a whole number.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:round</code></td><td rowspan="1" colspan="1">Rounds a value to a specified number of decimal places, rounding upwards if two such
            values are equally near.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:round-half-to-even</code></td><td rowspan="1" colspan="1">Rounds a value to a specified number of decimal places, rounding to make the last digit
            even if two such values are equally near.</td></tr></tbody></table><note><p><code>fn:round</code> and <code>fn:round-half-to-even</code> produce the same result in all cases
except when the argument is exactly midway between two values with the required precision.</p><p>Other ways of rounding midway values can be achieved as follows:</p><ulist><item><p>Towards negative infinity: <code>-fn:round(-$x)</code></p></item><item><p>Away from zero: <code>fn:round(fn:abs($x))*fn:compare($x,0)</code></p></item><item><p>Towards zero: <code>fn:abs(fn:round(-$x))*-fn:compare($x,0)</code></p></item></ulist></note><div3 id="func-abs"><head>fn:abs</head><glist><gitem><label>Summary</label><def><p>Returns the absolute value of <code>$arg</code>.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="abs" return-type="xs:numeric?" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg" type="xs:numeric?"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>General rules: see <specref ref="numeric-value-functions"/>.</p><p>If <code>$arg</code> is negative the function returns <code>-$arg</code>, otherwise it
            returns <code>$arg</code>.</p><p diff="chg" at="B">For the four types <code>xs:float</code>,
               <code>xs:double</code>, <code>xs:decimal</code> and <code>xs:integer</code>, it is
            guaranteed that if the type of <code>$arg</code> is an instance of type <var>T</var> then
            the result will also be an instance of <var>T</var>. The result <rfc2119>may</rfc2119>
            also be an instance of a type derived from one of these four by restriction. For example, if
            <code>$arg</code> is an instance of <code>xs:positiveInteger</code> then the value of
            <code>$arg</code> <rfc2119>may</rfc2119> be returned unchanged.</p><p>For <code>xs:float</code> and <code>xs:double</code> arguments, if the argument is
            positive zero or negative zero, then positive zero is returned. If the argument is
            positive or negative infinity, positive infinity is returned.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>fn:abs(10.5)</code> returns <code>10.5</code>.</p><p>The expression <code>fn:abs(-10.5)</code> returns <code>10.5</code>.</p></def></gitem></glist></div3><div3 id="func-ceiling"><head>fn:ceiling</head><glist><gitem><label>Summary</label><def><p>Rounds <code>$arg</code> upwards to a whole number.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="ceiling" return-type="xs:numeric?" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg" type="xs:numeric?"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>General rules: see <specref ref="numeric-value-functions"/>.</p><p>The function returns the smallest (closest to negative infinity) number with no
            fractional part that is not less than the value of <code>$arg</code>.</p><p diff="chg" at="B">For the four types <code>xs:float</code>,
            <code>xs:double</code>, <code>xs:decimal</code> and <code>xs:integer</code>, it is
            guaranteed that if the type of <code>$arg</code> is an instance of type <var>T</var> then
            the result will also be an instance of <var>T</var>. The result <rfc2119>may</rfc2119>
            also be an instance of a type derived from one of these four by restriction. For example, if
         <code>$arg</code> is an instance of <code>xs:decimal</code> then the result <rfc2119>may</rfc2119>
         be an instance of <code>xs:integer</code>.</p><p>For <code>xs:float</code> and <code>xs:double</code> arguments, if the argument is
            positive zero, then positive zero is returned. If the argument is negative zero, then
            negative zero is returned. If the argument is less than zero and greater than -1,
            negative zero is returned.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>fn:ceiling(10.5)</code> returns <code>11</code>.</p><p>The expression <code>fn:ceiling(-10.5)</code> returns <code>-10</code>.</p></def></gitem></glist></div3><div3 id="func-floor"><head>fn:floor</head><glist><gitem><label>Summary</label><def><p>Rounds <code>$arg</code> downwards to a whole number.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="floor" return-type="xs:numeric?" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg" type="xs:numeric?"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>General rules: see <specref ref="numeric-value-functions"/>.</p><p>The function returns the largest (closest to positive infinity) number with no
            fractional part that is not greater than the value of <code>$arg</code>.</p><p diff="chg" at="B">For the four types <code>xs:float</code>,
         <code>xs:double</code>, <code>xs:decimal</code> and <code>xs:integer</code>, it is
         guaranteed that if the type of <code>$arg</code> is an instance of type <var>T</var> then
         the result will also be an instance of <var>T</var>. The result <rfc2119>may</rfc2119>
         also be an instance of a type derived from one of these four by restriction. For example, if
         <code>$arg</code> is an instance of <code>xs:decimal</code> then the result <rfc2119>may</rfc2119>
         be an instance of <code>xs:integer</code>.</p><p>For <code>xs:float</code> and <code>xs:double</code> arguments, if the argument is
            positive zero, then positive zero is returned. If the argument is negative zero, then
            negative zero is returned.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>fn:floor(10.5)</code> returns <code>10</code>.</p><p>The expression <code>fn:floor(-10.5)</code> returns <code>-11</code>.</p></def></gitem></glist></div3><div3 id="func-round"><head>fn:round</head><glist><gitem><label>Summary</label><def><p>Rounds a value to a specified number of decimal places, rounding upwards if two such
            values are equally near.</p></def></gitem><gitem><label>Signatures</label><def><example role="signature"><proto name="round" return-type="xs:numeric?" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg" type="xs:numeric?"/></proto></example><example role="signature"><proto name="round" return-type="xs:numeric?" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg" type="xs:numeric?"/><arg name="precision" type="xs:integer"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>General rules: see <specref ref="numeric-value-functions"/>.</p><p>The function returns the nearest (that is, numerically closest) value to
               <code>$arg</code> that is a multiple of ten to the power of minus
               <code>$precision</code>. If two such values are equally near (for example, if the
            fractional part in <code>$arg</code> is exactly .5), the function returns the one that
            is closest to positive infinity.</p><p diff="chg" at="B">For the four types <code>xs:float</code>,
            <code>xs:double</code>, <code>xs:decimal</code> and <code>xs:integer</code>, it is
            guaranteed that if the type of <code>$arg</code> is an instance of type <var>T</var> then
            the result will also be an instance of <var>T</var>. The result <rfc2119>may</rfc2119>
            also be an instance of a type derived from one of these four by restriction. For example, if
            <code>$arg</code> is an instance of <code>xs:decimal</code> and <code>$precision</code> is less than one,
            then the result <rfc2119>may</rfc2119>
            be an instance of <code>xs:integer</code>.</p><p>The single-argument version of this function produces the same result as the
            two-argument version with <code>$precision=0</code> (that is, it rounds to a whole
            number).</p><p>When <code>$arg</code> is of type <code>xs:float</code> and <code>xs:double</code>:</p><olist><item><p>If <code>$arg</code> is NaN, positive or negative zero, or positive or negative
                  infinity, then the result is the same as the argument.</p></item><item><p>For other values, the argument is cast to <code>xs:decimal</code> using an
                  implementation of <code>xs:decimal</code> that imposes no limits on the number of
                  digits that can be represented. The function is applied to this
                     <code>xs:decimal</code> value, and the resulting <code>xs:decimal</code> is
                  cast back to <code>xs:float</code> or <code>xs:double</code> as appropriate to
                  form the function result. If the resulting <code>xs:decimal</code> value is zero,
                  then positive or negative zero is returned according to the sign of
                     <code>$arg</code>.</p></item></olist></def></gitem><gitem><label>Notes</label><def><p role="note">This function is typically used with a non-zero <code>$precision</code> in financial
            applications where the argument is of type <code>xs:decimal</code>. For arguments of
            type <code>xs:float</code> and <code>xs:double</code> the results may be
            counter-intuitive. For example, consider <code>round(35.425e0, 2)</code>. The result is
            not 35.43, as might be expected, but 35.42. This is because the <code>xs:double</code>
            written as 35.425e0 has an exact value equal to 35.42499999999..., which is closer to
            35.42 than to 35.43.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>fn:round(2.5)</code> returns <code>3.0</code>.</p><p>The expression <code>fn:round(2.4999)</code> returns <code>2.0</code>.</p><p>The expression <code>fn:round(-2.5)</code> returns <code>-2.0</code>. <emph>(Not the possible alternative, <code>-3</code>).</emph></p><p>The expression <code>fn:round(1.125, 2)</code> returns <code>1.13</code>.</p><p>The expression <code>fn:round(8452, -2)</code> returns <code>8500</code>.</p><p>The expression <code>fn:round(3.1415e0, 2)</code> returns <code>3.14e0</code>.</p></def></gitem></glist></div3><div3 id="func-round-half-to-even"><head>fn:round-half-to-even</head><glist><gitem><label>Summary</label><def><p>Rounds a value to a specified number of decimal places, rounding to make the last digit
            even if two such values are equally near.</p></def></gitem><gitem><label>Signatures</label><def><example role="signature"><proto name="round-half-to-even" return-type="xs:numeric?" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg" type="xs:numeric?"/></proto></example><example role="signature"><proto name="round-half-to-even" return-type="xs:numeric?" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg" type="xs:numeric?"/><arg name="precision" type="xs:integer"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>General rules: see <specref ref="numeric-value-functions"/>.</p><p>The function returns the nearest (that is, numerically closest) value to
               <code>$arg</code> that is a multiple of ten to the power of minus
               <code>$precision</code>. If two such values are equally near (e.g. if the fractional
            part in <code>$arg</code> is exactly .500...), the function returns the one whose least
            significant digit is even.</p><p diff="chg" at="B">For the four types <code>xs:float</code>,
            <code>xs:double</code>, <code>xs:decimal</code> and <code>xs:integer</code>, it is
            guaranteed that if the type of <code>$arg</code> is an instance of type <var>T</var> then
            the result will also be an instance of <var>T</var>. The result <rfc2119>may</rfc2119>
            also be an instance of a type derived from one of these four by restriction. For example, if
            <code>$arg</code> is an instance of <code>xs:decimal</code> and <code>$precision</code>
            is less than one, then the result <rfc2119>may</rfc2119>
            be an instance of <code>xs:integer</code>.</p><p> The first signature of this function produces the same result as the second signature
            with <code>$precision=0</code>.</p><p>For arguments of type <code>xs:float</code> and <code>xs:double</code>:</p><olist><item><p>If the argument is <code>NaN</code>, positive or negative zero, or positive or
                  negative infinity, then the result is the same as the argument.</p></item><item><p>In all other cases, the argument is cast to <code>xs:decimal</code> using an
                  implementation of xs:decimal that imposes no limits on the number of digits that
                  can be represented. The function is applied to this <code>xs:decimal</code> value,
                  and the resulting <code>xs:decimal</code> is cast back to <code>xs:float</code> or
                     <code>xs:double</code> as appropriate to form the function result. If the
                  resulting <code>xs:decimal</code> value is zero, then positive or negative zero is
                  returned according to the sign of the original argument.</p></item></olist></def></gitem><gitem><label>Notes</label><def><p role="note">This function is typically used in financial applications where the argument is of type
               <code>xs:decimal</code>. For arguments of type <code>xs:float</code> and
               <code>xs:double</code> the results may be counter-intuitive. For example, consider
               <code>round-half-to-even(xs:float(150.015), 2)</code>. The result is not 150.02 as
            might be expected, but 150.01. This is because the conversion of the
               <code>xs:float</code> value represented by the literal 150.015 to an
               <code>xs:decimal</code> produces the <code>xs:decimal</code> value 150.014999389...,
            which is closer to 150.01 than to 150.02.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>fn:round-half-to-even(0.5)</code> returns <code>0.0</code>.</p><p>The expression <code>fn:round-half-to-even(1.5)</code> returns <code>2.0</code>.</p><p>The expression <code>fn:round-half-to-even(2.5)</code> returns <code>2.0</code>.</p><p>The expression <code>fn:round-half-to-even(3.567812e+3, 2)</code> returns <code>3567.81e0</code>.</p><p>The expression <code>fn:round-half-to-even(4.7564e-3, 2)</code> returns <code>0.0e0</code>.</p><p>The expression <code>fn:round-half-to-even(35612.25, -2)</code> returns <code>35600</code>.</p></def></gitem></glist></div3></div2><div2 id="parsing-numbers"><head>Parsing numbers</head><p>It is possible to convert strings to values of type <code>xs:integer</code>,
            <code>xs:float</code>, <code>xs:decimal</code>, or <code>xs:double</code>
            using the constructor functions described in <specref ref="constructor-functions"/>
            or using <code>cast</code> expressions as described in <specref ref="casting"/>.</p><p>In addition the <code>fn:number</code> function is available to convert strings
            to values of type <code>xs:double</code>. It differs from the <code>xs:double</code>
            constructor function in that any value outside the lexical space of the <code>xs:double</code>
            datatype is converted to the <code>xs:double</code> value <code>NaN</code>.</p><table class="index"><thead><tr><th rowspan="1" colspan="1">Function</th><th rowspan="1" colspan="1">Meaning</th></tr></thead><tbody><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:number</code></td><td rowspan="1" colspan="1">Returns the value indicated by <code>$arg</code> or, if <code>$arg</code> is not
            specified, the context item after atomization, converted to an <code>xs:double</code>.
         </td></tr></tbody></table><div3 id="func-number"><head>fn:number</head><glist><gitem><label>Summary</label><def><p>Returns the value indicated by <code>$arg</code> or, if <code>$arg</code> is not
            specified, the context item after atomization, converted to an <code>xs:double</code>.
         </p></def></gitem><gitem><label>Signatures</label><def><example role="signature"><proto name="number" return-type="xs:double" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"/></example><example role="signature"><proto name="number" return-type="xs:double" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg" type="xs:anyAtomicType?"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>The zero-argument form of this function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-dependent">context-dependent</termref>,  and <termref def="dt-focus-dependent">focus-dependent</termref>. </p><p>The one-argument form of this function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>Calling the zero-argument version of the function is defined to give the same result as
            calling the single-argument version with the context item (<code>.</code>). That is,
               <code>fn:number()</code> is equivalent to <code>fn:number(.)</code>, as defined by
            the rules that follow.</p><p>If <code>$arg</code> is the empty sequence or if <code>$arg</code> cannot be converted
            to an <code>xs:double</code>, the <code>xs:double</code> value <code>NaN</code> is
            returned. </p><p>Otherwise, <code>$arg</code> is converted to an <code>xs:double</code> following the
            rules of <specref ref="casting-to-double"/>. If the conversion to <code>xs:double</code>
            fails, the <code>xs:double</code> value <code>NaN</code> is returned.</p></def></gitem><gitem><label>Error Conditions</label><def><p>A dynamic error is raised <xerrorref spec="XP" class="DY" code="0002" type="dynamic"/>
            if <code>$arg</code> is omitted and the context item is <xtermref ref="dt-absent" spec="DM31">absent</xtermref>.</p><p>As a consequence of the rules given above, a type error occurs if the context item
            cannot be atomized, or if the result of atomizing the context item is a sequence
            containing more than one atomic value.</p><!-- bug 16745 --></def></gitem><gitem><label>Notes</label><def><p role="note">XSD 1.1 allows the string <code>+INF</code> as a representation of positive infinity;
            XSD 1.0 does not. It is <termref def="implementation-defined">implementation-defined</termref> whether XSD 1.1 is
            supported.</p><p role="note">Generally <code>fn:number</code> returns <code>NaN</code> rather than raising a dynamic
            error if the argument cannot be converted to <code>xs:double</code>. However, a type
            error is raised in the usual way if the supplied argument cannot be atomized or if the
            result of atomization does not match the required argument type.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>fn:number($item1/quantity)</code> returns <code>5.0e0</code>.</p><p>The expression <code>fn:number($item2/description)</code> returns <code>xs:double('NaN')</code>.</p><p>Assume that the context item is the <code>xs:string</code> value "<code>15</code>".
               Then <code>fn:number()</code> returns <code>1.5e1</code>.</p></def></gitem></glist></div3></div2><div2 id="formatting-integers"><head>Formatting integers</head><table class="index"><thead><tr><th rowspan="1" colspan="1">Function</th><th rowspan="1" colspan="1">Meaning</th></tr></thead><tbody><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:format-integer</code></td><td rowspan="1" colspan="1">Formats an integer according to a given picture string, using the conventions of a given
            natural language if specified.</td></tr></tbody></table><div3 id="func-format-integer"><head>fn:format-integer</head><glist><gitem><label>Summary</label><def><p>Formats an integer according to a given picture string, using the conventions of a given
            natural language if specified.</p></def></gitem><gitem><label>Signatures</label><def><example role="signature"><proto name="format-integer" return-type="xs:string" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="value" type="xs:integer?"/><arg name="picture" type="xs:string"/></proto></example><example role="signature"><proto name="format-integer" return-type="xs:string" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="value" type="xs:integer?"/><arg name="picture" type="xs:string"/><arg name="lang" type="xs:string?"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>The two-argument form of this function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-dependent">context-dependent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>.  It depends on 
		default language.
	</p><p>The three-argument form of this function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>If <code>$value</code> is an empty sequence, the function returns a zero-length
            string.</p><p>In all other cases, the <code>$picture</code> argument describes the format in which
               <code>$value</code> is output.</p><p>The rules that follow describe how non-negative numbers are output. If the value of
               <code>$value</code> is negative, the rules below are applied to the absolute value of
               <code>$value</code>, and a minus sign is prepended to the result.</p><p>The value of <code>$picture</code> consists of a primary format token, optionally
            followed by a format modifier. The primary format token is always present and
               <rfc2119>must not</rfc2119> be zero-length. If the string contains one or more
            semicolons then everything that precedes the last semicolon is taken as the primary
            format token and everything that follows is taken as the format modifier; if the string
            contains no semicolon then the entire picture is taken as the primary format token, and
            the format modifier is taken to be absent (which is equivalent to supplying a
            zero-length string).</p><p>The primary format token is classified as one of the following:</p><olist><item><p>A <var>decimal-digit-pattern</var> made up of <var>optional-digit-signs</var>,
                     <var>mandatory-digit-signs</var>, and <var>grouping-separator-signs</var>.</p><ulist><item><p>The <var>optional-digit-sign</var> is the character "#".</p></item><item><p>A <var>mandatory-digit-sign</var> is a <termref def="character">character</termref> in Unicode category <var>Nd</var>. All
                           <var>mandatory-digit-signs</var> within the format token
                           <rfc2119>must</rfc2119> be from the same digit family, where a digit
                        family is a sequence of ten consecutive characters in Unicode category <var>Nd</var>,
                        having digit values 0 through 9. Within the format token, these digits are
                        interchangeable: a three-digit number may thus be indicated equivalently by
                           <code>000</code>, <code>001</code>, or <code>999</code>.</p></item><item><p>a <var>grouping-separator-sign</var> is a non-alphanumeric character, that
                        is a <termref def="character">character</termref> whose Unicode category is
                        other than <var>Nd</var>, <var>Nl</var>, <var>No</var>, <var>Lu</var>, <var>Ll</var>, 
                        <var>Lt</var>, <var>Lm</var> or <var>Lo</var>.</p></item></ulist><p>If the primary format token contains at least one Unicode digit then it is taken
                  as a decimal digit pattern, and in this case it <rfc2119>must</rfc2119> match the
                  regular expression <code>^((\p{Nd}|#|[^\p{N}\p{L}])+?)$</code>. If it contains a
                  digit but does not match this pattern, a dynamic error is raised <errorref class="DF" code="1310"/>.</p><note><p>If a semicolon is to be used as a grouping separator, then the primary format
                     token as a whole must be followed by another semicolon, to ensure that the
                     grouping separator is not mistaken as a separator between the primary format
                     token and the format modifier.</p></note><p>There <rfc2119>must</rfc2119> be at least one <var>mandatory-digit-sign</var>.
                  There may be zero or more <var>optional-digit-signs</var>, and (if present) these
                     <rfc2119>must</rfc2119> precede all <var>mandatory-digit-signs</var>. There may
                  be zero or more <var>grouping-separator-signs</var>. A
                     <var>grouping-separator-sign</var>
                  <rfc2119>must not</rfc2119> appear at the start or end of the
                     <var>decimal-digit-pattern</var>, nor adjacent to another
                     <var>grouping-separator-sign</var>.</p><p>The corresponding output format is a decimal number, using this digit family, with
                  at least as many digits as there are <var>mandatory-digit-signs</var> in the
                  format token. Thus, a format token <code>1</code> generates the sequence <code>0 1
                     2 ... 10 11 12 ...</code>, and a format token <code>01</code> (or equivalently,
                     <code>00</code> or <code>99</code>) generates the sequence <code>00 01 02 ...
                     09 10 11 12 ... 99 100 101</code>. A format token of <code>&amp;#x661;</code>
                  (Arabic-Indic digit one) generates the sequence <code>١</code> then <code>٢</code>
                  then <code>٣</code> ...</p><p diff="chg" at="E">The <var>grouping-separator-signs</var> are handled as follows:</p><olist><item><p>The position of
                        grouping separators within the format token, counting backwards from the last
                        digit, indicates the position of grouping separators to appear within the
                        formatted number, and the character used as the <var>grouping-separator-sign</var>
                        within the format token indicates the character to be used as the corresponding
                        grouping separator in the formatted number.
                     </p></item><item><p>More specifically, the <term>position</term> of a grouping separator is
                        the number of <var>optional-digit-signs</var> and <var>mandatory-digit-signs</var> appearing
                        between the grouping separator and the right-hand end of the primary format token.</p></item><item><p>Grouping separators are defined to be <term>regular</term> if the following conditions apply:</p><olist><item><p>There is at least one grouping separator.</p></item><item><p>Every grouping separator is the same character (call it <var>C</var>).</p></item><item><p>There is a positive integer <var>G</var> (the grouping size) such that:</p><olist><item><p>The position of every grouping separator is an integer multiple of <var>G</var>, and</p></item><item><p>Every positive integer multiple of <var>G</var> that is less than the number of 
                              <var>optional-digit-signs</var> and <var>mandatory-digit-signs</var> in the primary format token
                              is the position of a grouping separator.</p></item></olist></item></olist></item><item><p>The <term>grouping separator template</term> is a (possibly infinite) set of (position, character) pairs.</p></item><item><p>If grouping separators are regular, then the grouping separator template contains one pair of the form <code>(n×G, C)</code>
                     for every positive integer <var>n</var> where <var>G</var> is the grouping size and <var>C</var> is the grouping character.</p></item><item><p>Otherwise (when grouping separators are not regular), the grouping separator template contains one pair of the form
                     <code>(P, C)</code> for every grouping separator found in the primary formatting token, where <var>C</var> is the grouping
                     separator character and <var>P</var> is its position.</p></item><item><note><p>If there are no grouping separators, then the grouping separator template is an empty set.</p></note></item></olist><p>The number is formatted as follows:</p><olist><item><p>Let <var>S/1</var> be the result of formatting the supplied number in decimal notation as if by casting
                  it to <code>xs:string</code>.</p></item><item><p>Let <var>S/2</var> be the result of padding <var>S/1</var> on the left with as many leading zeroes
                  as are needed to ensure that it contains at least as many digits as the number of <var>mandatory-digit-signs</var>
                  in the primary format token.</p></item><item><p>Let <var>S/3</var> be the result of replacing all decimal digits (0-9) in <var>S/2</var> with the corresponding
                     digits from the selected digit family.</p></item><item><p>Let <var>S/4</var> be the result of inserting grouping separators into <var>S/3</var>: for every (position 
                     <var>P</var>, character <var>C</var>) pair in the grouping separator template where <var>P</var> is less than the number
                  of digits in <var>S/3</var>, insert character <var>C</var> into <var>S/3</var> at position <var>P</var>, counting from 
                  the right-hand end.</p></item><item><p>Let <var>S/5</var> be the result of converting <var>S/4</var> into ordinal form, if an ordinal modifier
                  is present, as described below.</p></item><item><p>The result of the function is then <var>S/5</var>.</p></item></olist></item><item><p>The format token <code>A</code>, which generates the sequence <code>A B C ... Z AA
                     AB AC...</code>.</p></item><item><p>The format token <code>a</code>, which generates the sequence <code>a b c ... z aa
                     ab ac...</code>.</p></item><item><p>The format token <code>i</code>, which generates the sequence <code>i ii iii iv v
                     vi vii viii ix x ...</code>.</p></item><item><p>The format token <code>I</code>, which generates the sequence <code>I II III IV V
                     VI VII VIII IX X ...</code>.</p></item><item><p>The format token <code>w</code>, which generates numbers written as lower-case
                  words, for example in English, <code>one two three four ...</code>
               </p></item><item><p>The format token <code>W</code>, which generates numbers written as upper-case
                  words, for example in English, <code>ONE TWO THREE FOUR ...</code>
               </p></item><item><p>The format token <code>Ww</code>, which generates numbers written as title-case
                  words, for example in English, <code>One Two Three Four ...</code>
               </p></item><item><p>Any other format token, which indicates a numbering sequence in which that token
                  represents the number 1 (one) (but see the note below).
                  
                  It is <termref def="implementation-defined">implementation-defined</termref> which
                  numbering sequences, additional to those listed above, are supported. If an
                  implementation does not support a numbering sequence represented by the given
                  token, it <rfc2119>must</rfc2119> use a format token of <code>1</code>.</p><note><p>In some traditional numbering sequences additional signs are added to denote
                     that the letters should be interpreted as numbers; these are not included in
                     the format token. An example (see also the example below) is classical Greek
                     where a <emph>dexia keraia</emph> <phrase role="normalize-nfc">(x0374, ʹ)</phrase> and sometimes an
                     <emph>aristeri keraia</emph> <phrase role="normalize-nfc">(x0375, ͵)</phrase> is added.</p></note></item></olist><p>For all format tokens other than a <var>decimal-digit-pattern</var>, there 
            <rfc2119>may</rfc2119> be <termref def="implementation-defined">implementation-defined</termref> lower and upper bounds on the range of numbers that
            can be formatted using this format token; indeed, for some numbering sequences there may
            be intrinsic limits. For example, the format token <code>&amp;#x2460;</code> (circled
            digit one, ①) has a range imposed by the Unicode character repertoire — <phrase diff="chg" at="D">zero to 20</phrase>
            in Unicode versions prior to <phrase diff="chg" at="D">3.2</phrase>, or <phrase diff="chg" at="D">zero to 50</phrase> in subsequent versions. For the numbering
            sequences described above any upper bound imposed by the implementation <rfc2119>must
               not</rfc2119> be less than 1000 (one thousand) and any lower bound must not be
            greater than 1. Numbers that fall outside this range <rfc2119>must</rfc2119> be
            formatted using the format token <code>1</code>.</p><p>The above expansions of numbering sequences for format tokens such as <code>a</code> and
               <code>i</code> are indicative but not prescriptive. There are various conventions in
            use for how alphabetic sequences continue when the alphabet is exhausted, and differing
            conventions for how roman numerals are written (for example, <code>IV</code> versus
               <code>IIII</code> as the representation of the number 4). Sometimes alphabetic
            sequences are used that omit letters such as <code>i</code> and <code>o</code>. This
            specification does not prescribe the detail of any sequence other than those sequences
            consisting entirely of decimal digits.</p><p>Many numbering sequences are language-sensitive. This applies especially to the sequence
            selected by the tokens <code>w</code>, <code>W</code> and <code>Ww</code>. It also
            applies to other sequences, for example different languages using the Cyrillic alphabet
            use different sequences of characters, each starting with the letter #x410 (Cyrillic
            capital letter A). In such cases, the <code>$lang</code> argument specifies which
            language's conventions are to be used. If the argument is specified, the value
               <rfc2119>should</rfc2119> be either an empty sequence or a value that would be valid
            for the <code>xml:lang</code> attribute (see <bibref ref="xml"/>). Note that this
            permits the identification of sublanguages based on country codes (from ISO 3166-1) as
            well as identification of dialects and regions within a country.</p><p>The set of languages for which numbering is supported is <termref def="implementation-defined">implementation-defined</termref>. If the <code>$lang</code> argument is absent, or is
            set to an empty sequence, or is invalid, or is not a language supported by the
            implementation, then the number is formatted using the default language from the dynamic
            context. </p><p>The format modifier <rfc2119>must</rfc2119> be a string that matches the regular
            expression <code>^([co](\(.+\))?)?[at]?$</code>. That is, if it is present it must
            consist of one or more of the following, in order:</p><ulist><item><p>either <code>c</code> or <code>o</code>, optionally followed by a sequence of
                  characters enclosed between parentheses, to indicate cardinal or ordinal numbering
                  respectively, the default being cardinal numbering</p></item><item><p>either <code>a</code> or <code>t</code>, to indicate alphabetic or traditional
                  numbering respectively, the default being <termref def="implementation-defined">implementation-defined</termref>.</p></item></ulist><p>If the <code>o</code> modifier is present, this indicates a request to output ordinal
            numbers rather than cardinal numbers. For example, in English, when used with the format
            token <code>1</code>, this outputs the sequence <code>1st 2nd 3rd 4th ...</code>, and
            when used with the format token <code>w</code> outputs the sequence <code>first second
               third fourth ...</code>.</p><p>The string of characters between the parentheses, if present, is used to select between
            other possible variations of cardinal or ordinal numbering sequences. The interpretation
            of this string is <termref def="implemementation-defined">implementation-defined</termref>. No error occurs if the implementation does not
            define any interpretation for the defined string.</p><p>It is <termref def="implementation-defined">implementation-defined</termref> what
            combinations of values of the format token, the language, and the cardinal/ordinal
            modifier are supported. If ordinal numbering is not supported for the combination of the
            format token, the language, and the string appearing in parentheses, the request is
            ignored and cardinal numbers are generated instead.</p><p>The use of the <code>a</code> or <code>t</code> modifier disambiguates between numbering
            sequences that use letters. In many languages there are two commonly used numbering
            sequences that use letters. One numbering sequence assigns numeric values to letters in
            alphabetic sequence, and the other assigns numeric values to each letter in some other
            manner traditional in that language. In English, these would correspond to the numbering
            sequences specified by the format tokens <code>a</code> and <code>i</code>. In some
            languages, the first member of each sequence is the same, and so the format token alone
            would be ambiguous. In the absence of the <code>a</code> or <code>t</code> modifier, the
            default is <termref def="implementation-defined">implementation-defined</termref>.</p></def></gitem><gitem><label>Error Conditions</label><def><p>A dynamic error is raised <errorref class="DF" code="1310"/> if the format token is
            invalid, that is, if it violates any mandatory rules (indicated by an emphasized
               <rfc2119>must</rfc2119> or <rfc2119>required</rfc2119> keyword in the above rules).
            For example, the error is raised if the primary format token contains a digit but does
            not match the required regular expression.</p></def></gitem><gitem><label>Notes</label><def><olist role="note"><item><p>Note the careful distinction between conditions that are errors and conditions where
               fallback occurs. The principle is that an error in the syntax of the format picture will
               be reported by all processors, while a construct that is recognized by some
               implementations but not others will never result in an error, but will instead cause a
               fallback representation of the integer to be used.</p></item><item><p>The following notes apply when a <var>decimal-digit-pattern</var> is used:</p><olist><item><p>If <var>grouping-separator-signs</var>
                     appear at regular intervals within the format token, then the sequence is extrapolated to
                     the left, so grouping separators will be used in the formatted number at every
                     multiple of <var>N</var>. For example, if the format token is <code>0'000</code>
                     then the number one million will be formatted as <code>1'000'000</code>, while the
                     number fifteen will be formatted as <code>0'015</code>.</p></item><item><p>The only purpose of <var>optional-digit-signs</var> is to mark the position of
                     <var>grouping-separator-signs</var>. For example, if the format token is
                     <code>#'##0</code> then the number one million will be formatted as
                     <code>1'000'000</code>, while the number fifteen will be formatted as
                     <code>15</code>. A grouping separator is included in the formatted number only
                     if there is a digit to its left, which will only be the case if either (a) the
                     number is large enough to require that digit, or (b) the number of
                     <var>mandatory-digit-signs</var> in the format token requires insignificant
                     leading zeros to be present.</p></item><item><p>Grouping separators are <emph>not</emph> designed for effects such as
                     formatting a US telephone number as <code>(365)123-9876</code>. In general they are not 
                     suitable for such purposes because (a) only single characters are allowed, and (b) they
                     cannot appear at the beginning or end of the number.</p></item><item><p>Numbers will never be truncated. Given the <var>decimal-digit-pattern</var>
                     <code>01</code>, the number three hundred will be output as <code>300</code>,
                     despite the absence of any <var>optional-digit-sign</var>.</p></item></olist></item><item><p>The following notes apply when ordinal numbering is selected using the <code>o</code> modifier.</p><p>In some languages, the form of numbers (especially ordinal numbers) varies depending 
                  on the grammatical context: they may have different genders and may decline with the 
                  noun that they qualify. In such cases the string appearing in parentheses after the 
                  letter <code>c</code> or <code>o</code> may be used to indicate the variation of the 
                  cardinal or ordinal number required.</p><p>The way in which the variation is indicated will depend on the conventions of the language.</p><p>For inflected languages that vary the ending of the word, the approach recommended 
                     in the previous version of this specification was to indicate the required ending, 
                     preceded by a hyphen: for example in German, appropriate values might be 
                     <code>o(-e)</code>, <code>o(-er)</code>, <code>o(-es)</code>, <code>o(-en)</code>. 
                  </p><p>Another approach, which might usefully be adopted by an implementation based on the 
                     open-source ICU localization library <bibref ref="ICU"/>, or any other library making use of the 
                     Unicode Common Locale Data Repository <bibref ref="CLDR"/>, is to allow the value in parentheses 
                     to be the name of a registered numbering rule set for the language in question, 
                     conventionally prefixed with a percent sign: for example, 
                     <code>o(%spellout-ordinal-masculine)</code>, or <code>c(%spellout-cardinal-year)</code>.
                  </p></item></olist></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>format-integer(123, '0000')</code> returns <code>"0123"</code>.</p><p><code>format-integer(123, 'w')</code> might return <code>"one hundred and
                  twenty-three"</code></p><p>Ordinal numbering in Italian: The specification <code>"1;o(-º)"</code> with <code>$lang</code> equal to
                  <code>it</code>, if supported, should produce the sequence:</p><eg xml:space="preserve">1º 2º 3º 4º ...</eg><p>The specification <code>"Ww;o"</code> with <code>$lang</code> equal to
                  <code>it</code>, if supported, should produce the sequence:</p><eg xml:space="preserve">Primo Secondo Terzo Quarto Quinto ...</eg><p>The expression <code>format-integer(21, '1;o', 'en')</code> returns <code>"21st"</code>.</p><p><code>format-integer(14, 'Ww;o(-e)', 'de')</code> might return
                  <code>"Vierzehnte"</code></p><p>The expression <code>format-integer(7, 'a')</code> returns <code>"g"</code>.</p><p>The expression <code>format-integer(57, 'I')</code> returns <code>"LVII"</code>.</p><p>The expression <code>format-integer(1234, '#;##0;')</code> returns <code>"1;234"</code>.</p></def></gitem></glist></div3></div2><div2 id="formatting-numbers"><head>Formatting numbers</head><p>This section defines a function for formatting decimal and floating point numbers.</p><table class="index"><thead><tr><th rowspan="1" colspan="1">Function</th><th rowspan="1" colspan="1">Meaning</th></tr></thead><tbody><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:format-number</code></td><td rowspan="1" colspan="1">Returns a string containing a number formatted according to a given picture string,
            taking account of decimal formats specified in the static context.</td></tr></tbody></table><note><p>This function can be used to format any numeric quantity, including an integer. For integers, however,
		         the <code>fn:format-integer</code> function offers additional possibilities. Note also that the picture
		         strings used by the two functions are not 100% compatible, though they share some options in common.</p></note><div3 id="defining-decimal-format"><head>Defining a decimal format</head><p>Decimal formats are defined in the static context, and the way they are defined is therefore outside the scope
of this specification. XSLT and XQuery both provide custom syntax for creating a decimal format.</p><p>The static context provides a set of decimal formats. One of the decimal formats is unnamed, the others (if any)
   are identified by a QName. There is always an unnamed decimal format available, but its contents are 
   <termref def="implementation-defined"/>.</p><p>Each decimal format provides a set of named properties, described in the following table:</p><table role="no-code-break longlastcol data"><thead><tr><th rowspan="1" colspan="1">Name</th><th rowspan="1" colspan="1">Type</th><th rowspan="1" colspan="1">Usage (non-normative)</th></tr></thead><tbody><tr><td rowspan="1" colspan="1"><code>decimal-separator</code></td><td rowspan="1" colspan="1">A single <termref def="character">character</termref></td><td rowspan="1" colspan="1">Defines the character used to represent the decimal point (typically ".") both in the picture string and in the formatted number.</td></tr><tr><td rowspan="1" colspan="1"><code>grouping-separator</code></td><td rowspan="1" colspan="1">A single <termref def="character">character</termref></td><td rowspan="1" colspan="1">Defines the character used to separate groups of digits (typically ",") both in the picture string and in the formatted number.</td></tr><tr diff="add" at="A"><td rowspan="1" colspan="1"><code>exponent-separator</code></td><td rowspan="1" colspan="1">A single <termref def="character">character</termref></td><td rowspan="1" colspan="1">Defines the character used to separate the mantissa from the exponent
         in scientific notation (typically "e") both in the picture string and in the formatted number.</td></tr><tr><td rowspan="1" colspan="1"><code>infinity</code></td><td rowspan="1" colspan="1">A <termref def="string">string</termref></td><td rowspan="1" colspan="1">Defines the string used to represent the value positive or negative infinity in the formatted number (typically "Infinity")</td></tr><tr><td rowspan="1" colspan="1"><code>minus-sign</code></td><td rowspan="1" colspan="1">A single <termref def="character">character</termref></td><td rowspan="1" colspan="1">Defines the character used as a minus sign in the formatted number if there is no subpicture for formatting negative numbers (typically "-", x2D)</td></tr><tr><td rowspan="1" colspan="1"><code>NaN</code></td><td rowspan="1" colspan="1">A <termref def="string">string</termref></td><td rowspan="1" colspan="1">Defines the string used to represent the value <code>NaN</code> in the formatted number</td></tr><tr><td rowspan="1" colspan="1"><code>percent</code></td><td rowspan="1" colspan="1">A single <termref def="character">character</termref></td><td rowspan="1" colspan="1">Defines the character used as a percent sign (typically "%") both in the picture string and in the formatted number</td></tr><tr><td rowspan="1" colspan="1"><code>per-mille</code></td><td rowspan="1" colspan="1">A single <termref def="character">character</termref></td><td rowspan="1" colspan="1">Defines the character used as a per-mille sign (typically "‰", x2030) both in the picture string and in the formatted number</td></tr><tr><td rowspan="1" colspan="1"><code>zero-digit</code></td><td rowspan="1" colspan="1">A single <termref def="character">character</termref>, which must be a character in Unicode category Nd with decimal digit value 0 (zero)</td><td rowspan="1" colspan="1">Defines the characters used in the picture string to represent a mandatory digit: for example, if the zero-digit is "0" then any of the
         digits "0" to "9" may be used (interchangeably) in the picture string to represent a mandatory digit, and in the formatted number the characters "0" to "9" will
         be used to represent the digits zero to nine.</td></tr><tr><td rowspan="1" colspan="1"><code>digit</code></td><td rowspan="1" colspan="1">A single <termref def="character">character</termref></td><td rowspan="1" colspan="1">Defines the character used in the picture string to represent an optional digit (typically "#")</td></tr><tr><td rowspan="1" colspan="1"><code>pattern-separator</code></td><td rowspan="1" colspan="1">A single <termref def="character">character</termref></td><td rowspan="1" colspan="1">Defines the character used in the picture string to separate the positive and negative subpictures (typically ";")</td></tr></tbody></table><note><p>A phrase such as "The <xtermref spec="XP31" ref="id-static-decimal-format-minus-sign">minus-sign</xtermref> character" is to be read as 
   "the character assigned to the <xtermref spec="XP31" ref="id-static-decimal-format-minus-sign">minus-sign</xtermref>
property in the relevant decimal format within the static context".</p></note><p><termdef id="dt-decimal-digit-family" term="digit family">The <term>decimal digit family</term> of a decimal format 
is the sequence of ten digits with
consecutive Unicode <termref def="codepoint">codepoints</termref> starting with the character that is the value of the 
   <xtermref spec="XP31" ref="id-static-decimal-format-zero-digit">zero-digit</xtermref> property.</termdef></p><p><termdef id="dt-optional-digit-character" term="optional digit character">The <term>optional digit character</term> is
                  the character that is the value of the 
                  <xtermref spec="XP31" ref="id-static-decimal-format-digit">digit</xtermref> property.</termdef></p><p>For any named or unnamed decimal format, the properties
representing characters used in a <termref def="dt-picture-string">picture string</termref>
   must have distinct values. These properties are <xtermref spec="XP31" ref="id-static-decimal-format-decimal-separator">decimal-separator</xtermref> ,
   <xtermref spec="XP31" ref="id-static-decimal-format-grouping-separator">grouping-separator</xtermref>, 
   <xtermref spec="XP31" ref="id-static-decimal-format-exponent-separator">exponent-separator</xtermref>,
   <xtermref spec="XP31" ref="id-static-decimal-format-percent">percent</xtermref>, <xtermref spec="XP31" ref="id-static-decimal-format-per-mille">per-mille</xtermref>,
<xtermref spec="XP31" ref="id-static-decimal-format-digit">digit</xtermref>, and <xtermref spec="XP31" ref="id-static-decimal-format-pattern-separator">pattern-separator</xtermref>.
   Furthermore, none of these properties may be equal to any <termref def="character">character</termref> in the 
<termref def="dt-decimal-digit-family">decimal digit family</termref>.

</p></div3><div3 id="func-format-number"><head>fn:format-number</head><glist><gitem><label>Summary</label><def><p>Returns a string containing a number formatted according to a given picture string,
            taking account of decimal formats specified in the static context.</p></def></gitem><gitem><label>Signatures</label><def><example role="signature"><proto name="format-number" return-type="xs:string" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="value" type="xs:numeric?"/><arg name="picture" type="xs:string"/></proto></example><example role="signature"><proto name="format-number" return-type="xs:string" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="value" type="xs:numeric?"/><arg name="picture" type="xs:string"/><arg name="decimal-format-name" type="xs:string?"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>The two-argument form of this function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p><p>The three-argument form of this function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-dependent">context-dependent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>.  It depends on 
		decimal formats, and namespaces.
	</p></def></gitem><gitem><label>Rules</label><def><p>The effect of the two-argument form of the function is equivalent to calling the
            three-argument form with an empty sequence as the value of the third argument.</p><p>The function formats <code>$value</code> as a string using the <termref def="dt-picture-string">picture string</termref> specified by the
               <code>$picture</code> argument and the decimal-format named by the
               <code>$decimal-format-name</code> argument, or the unnamed decimal-format, if there
            is no <code>$decimal-format-name</code> argument. The syntax of the picture string is
            described in <specref ref="syntax-of-picture-string"/>.</p><p>The <code>$value</code> argument may be of any numeric data type
            (<code>xs:double</code>, <code>xs:float</code>, <code>xs:decimal</code>, or their
            subtypes including <code>xs:integer</code>). Note that if an <code>xs:decimal</code> is
            supplied, it is not automatically promoted to an <code>xs:double</code>, as such
            promotion can involve a loss of precision.</p><p>If the supplied value of the <code>$value</code> argument is an empty sequence, the
            function behaves as if the supplied value were the <code>xs:double</code> value
               <code>NaN</code>.</p><p>The value of <code>$decimal-format-name</code>, if present and non-empty,
               <rfc2119>must</rfc2119> be a string which after removal of leading and trailing
            whitespace is in the form of an <code>EQName</code> as defined in the XPath 3.0
            grammar, that is one of the following:</p><ulist><item><p>A lexical QName, which is expanded using the statically known namespaces. The
                  default namespace is not used (no prefix means no namespace).</p></item><item><p>A <code>URIQualifiedName</code> using the syntax <code>Q{uri}local</code>, where
                  the URI can be zero-length to indicate a name in no namespace.</p></item></ulist><p>The decimal format that is used is the decimal format in the static context whose name
            matches <code>$decimal-format-name</code> if supplied, or the unnamed decimal format in
            the static context otherwise.</p><p>The evaluation of the <code>fn:format-number</code> function takes place in two
            phases, an analysis phase described in <specref ref="analyzing-picture-string"/> and a
            formatting phase described in <specref ref="formatting-the-number"/>.</p><p>The analysis phase takes as its inputs the <termref def="dt-picture-string">picture
               string</termref> and the variables derived from the relevant decimal format in the
            static context, and produces as its output a number of variables with defined values.
            The formatting phase takes as its inputs the number to be formatted and the variables
            produced by the analysis phase, and produces as its output a string containing a
            formatted representation of the number.</p><p>The result of the function is the formatted string representation of the supplied
            number.</p></def></gitem><gitem><label>Error Conditions</label><def><p>A dynamic error is raised <errorref class="DF" code="1280"/> if the name specified as
            the <code>$decimal-format-name</code> argument is neither a valid lexical QName nor a
            valid <code>URIQualifiedName</code>, or if it uses a prefix that is not found in the
            statically known namespaces, or if the static context does not contain a declaration of
            a decimal-format with a matching expanded QName. If the processor is able to detect the
            error statically (for example, when the argument is supplied as a string literal), then
            the processor <rfc2119>may</rfc2119> optionally signal this as a static error.</p></def></gitem><gitem><label>Notes</label><def><p role="note">A string is an ordered sequence of characters, and this specification 
            uses terms such as "left" and "right", "preceding" and "following" in relation to this ordering, 
            irrespective of the position of the characters when visually rendered on some output medium. 
            Both in the picture string and in the result string, digits with higher significance (that is, 
            representing higher powers of ten) always precede digits with lower significance, even when 
            the rendered text flow is from right to left.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The following examples assume a default decimal format in which the chosen digits are
               the ASCII digits 0-9, the decimal separator is ".", the grouping separator is ",",
               the minus-sign is "-", and the percent-sign is "%".</p><p>The expression <code>format-number(12345.6, '#,###.00')</code> returns <code>"12,345.60"</code>.</p><p>The expression <code>format-number(12345678.9, '9,999.99')</code> returns <code>"12,345,678.90"</code>.</p><p>The expression <code>format-number(123.9, '9999')</code> returns <code>"0124"</code>.</p><p>The expression <code>format-number(0.14, '01%')</code> returns <code>"14%"</code>.</p><p>The expression <code>format-number(-6, '000')</code> returns <code>"-006"</code>.</p><p>The following example assumes the existence of a decimal format named 'ch' in which
               the grouping separator is <code>ʹ</code> and the decimal separator is
                  <code>·</code>:</p><p>The expression <code>format-number(1234.5678, '#ʹ##0·00',
                  'ch')</code> returns <code>"1ʹ234·57"</code>.</p><p diff="add" at="A">The following examples assume that the exponent separator is
               in decimal format 'fortran' is 'E':</p><p>The expression <code>format-number(1234.5678, '00.000E0', 'fortran')</code> returns <code>"12.346E2"</code>.</p><p>The expression <code>format-number(0.234, '0.0E0', 'fortran')</code> returns <code>"2.3E-1"</code>.</p><p>The expression <code>format-number(0.234, '#.00E0', 'fortran')</code> returns <code>"0.23E0"</code>.</p><p>The expression <code>format-number(0.234, '.00E0', 'fortran')</code> returns <code>".23E0"</code>.</p></def></gitem></glist></div3><div3 id="syntax-of-picture-string"><head>Syntax of the picture string</head><note><p>This differs from the <code>format-number</code> function previously defined in XSLT 2.0 in that
			   any digit can be used in the picture string to represent a mandatory digit: for example the picture
			   strings '000', '001', and '999' are equivalent. The digits will all be from the same decimal digit family,
			   specifically, the sequence of ten consecutive digits starting with the digit assigned to the <phrase diff="chg" at="D"><var>zero-digit</var> property</phrase>.
			      This change is to align <code>format-number</code> 
			   (which previously used '000') with <code>format-dateTime</code> (which used '001').</p></note><p>
                  <termdef id="dt-picture-string" term="picture string">The formatting of a 
number is controlled by a <term>picture string</term>. The
                     picture string is a sequence of <termref def="character">characters</termref>, in which the characters
                     assigned to the properties <xtermref spec="XP31" ref="id-static-decimal-format-decimal-separator">decimal-separator</xtermref> , 
                     <xtermref spec="XP31" ref="id-static-decimal-format-exponent-separator">exponent-separator</xtermref>, 
                     <xtermref spec="XP31" ref="id-static-decimal-format-grouping-separator">grouping-separator</xtermref>, and
                     <xtermref spec="XP31" ref="id-static-decimal-format-digit">digit</xtermref>, 
                     and <xtermref spec="XP31" ref="id-static-decimal-format-pattern-separator">pattern-separator</xtermref> 
                     and the members of the <termref def="dt-decimal-digit-family">decimal digit family</termref>, are classified as
active characters, and all other characters (including the values of the properties <xtermref spec="XP31" ref="id-static-decimal-format-percent">percent</xtermref> and 
<xtermref spec="XP31" ref="id-static-decimal-format-per-mille">per-mille</xtermref>) are classified as passive characters.</termdef> 

               </p><p>A dynamic error is raised <errorref class="DF" code="1310"/> if the
 <termref def="dt-picture-string">picture string</termref> does not conform to the following rules. 
               Note that in these
rules the words "preceded" and "followed" refer to characters anywhere in the string, they
are not to be read as "immediately preceded" and "immediately followed".</p><ulist><item><p>A picture-string consists either of a sub-picture, or of
        two sub-pictures separated by the <xtermref spec="XP31" ref="id-static-decimal-format-pattern-separator">pattern-separator</xtermref> character. A picture-string
        <rfc2119>must not</rfc2119> contain more than one instance of the <xtermref spec="XP31" ref="id-static-decimal-format-pattern-separator">pattern-separator</xtermref> character. 
                        If the picture-string contains two
        sub-pictures, the first is used for positive <phrase diff="add" at="D">and unsigned zero</phrase> values and the second for negative values.</p></item><item><p>A sub-picture <rfc2119>must not</rfc2119> contain more than one instance of the 
                        <xtermref spec="XP31" ref="id-static-decimal-format-decimal-separator">decimal-separator</xtermref> character.</p></item><item><p>A sub-picture <rfc2119>must not</rfc2119> contain more than one instance of the 
                        <xtermref spec="XP31" ref="id-static-decimal-format-percent">percent</xtermref> or
        <xtermref spec="XP31" ref="id-static-decimal-format-per-mille">per-mille</xtermref> characters, and it <rfc2119>must not</rfc2119> contain one of each.</p></item><item><p><phrase diff="add" at="D">The <var>mantissa part</var> of</phrase> a
                        sub-picture (defined below) <rfc2119>must</rfc2119> contain at least one character that is either 
                        an <termref def="dt-optional-digit-character">optional digit character</termref>
                        or a member of the <termref def="dt-decimal-digit-family">decimal digit family</termref>.</p></item><item><p>A sub-picture <rfc2119>must not</rfc2119> contain a passive character that is preceded by
        an active character and that is followed by another active character.</p></item><item><p>A sub-picture <rfc2119>must not</rfc2119> contain a <xtermref spec="XP31" ref="id-static-decimal-format-grouping-separator">grouping-separator</xtermref> 
                        character that appears adjacent to                        
                         a <xtermref spec="XP31" ref="id-static-decimal-format-decimal-separator">decimal-separator</xtermref>  character, 
                        <phrase diff="add" at="D"> or in the absence of a 
                           <xtermref spec="XP31" ref="id-static-decimal-format-decimal-separator">decimal-separator</xtermref>  character, 
                           at the end of the <var>integer part</var></phrase>.</p></item><item><p diff="add" at="D">A sub-picture <rfc2119>must not</rfc2119> contain two adjacent instances of the <xtermref spec="XP31" ref="id-static-decimal-format-grouping-separator">grouping-separator</xtermref> character.</p></item><item><p>The <var>integer part</var> of a sub-picture (defined below) <rfc2119>must not</rfc2119> contain 
                        a member of the <termref def="dt-decimal-digit-family">decimal digit family</termref> 
					 that is followed by
					 an instance of the <termref def="dt-optional-digit-character">optional digit character</termref>. 
                        The <var>fractional part</var> of a sub-picture (defined below) <rfc2119>must not</rfc2119> contain an instance of the 
                        <termref def="dt-optional-digit-character">optional digit character</termref>
                        that is followed by a member of the <termref def="dt-decimal-digit-family">decimal digit family</termref>.</p></item><item diff="add" at="A"><p>A character that matches the <xtermref spec="XP31" ref="id-static-decimal-format-exponent-separator">exponent-separator</xtermref> property
                  is treated as an <var>exponent-separator-sign</var> if it is both preceded and followed
                  within the sub-picture by an active character. Otherwise, it is treated as a passive character. 
                  A sub-picture <rfc2119>must not</rfc2119> contain more than one character that is treated as an <var>exponent-separator-sign</var>.
                  </p></item><item diff="add" at="A"><p>A sub-picture that contains a <xtermref spec="XP31" ref="id-static-decimal-format-percent">percent</xtermref> or
                     <xtermref spec="XP31" ref="id-static-decimal-format-per-mille">per-mille</xtermref> character <rfc2119>must not</rfc2119> contain a character treated as an
                     <var>exponent-separator-sign</var>.</p></item><item diff="add" at="A"><p>If a sub-picture contains a character treated as an
                     <var>exponent-separator-sign</var> then this <rfc2119>must</rfc2119> be followed by
                     one or more characters that are members of the <termref def="dt-decimal-digit-family">decimal digit family</termref>,
                     and it <rfc2119>must not</rfc2119> be followed by any active character
                     that is not a member of the <termref def="dt-decimal-digit-family">decimal digit family</termref>.</p></item></ulist><p diff="add" at="A">The <var>mantissa part</var> of the sub-picture is defined as the part that appears
               to the left of the <var>exponent-separator-sign</var> if there is one, or the entire
               sub-picture otherwise. The <var>exponent part</var> of the subpicture is defined as
                  the part that appears to the right of the <var>exponent-separator-sign</var>;
                  if there is no <var>exponent-separator-sign</var> then the <var>exponent part</var>
               is absent.</p><p>The <var>integer part</var> of the sub-picture is defined as the part that
                  appears to the left of the <xtermref spec="XP31" ref="id-static-decimal-format-decimal-separator">decimal-separator</xtermref>  character if there is one, or the entire
                  <var diff="chg" at="A">mantissa part</var> otherwise.</p><p>The <var>fractional part</var> of the sub-picture is defined as <phrase diff="chg" at="A">that
                  part of the <var>mantissa part</var></phrase> that
                  appears to the right of the <xtermref spec="XP31" ref="id-static-decimal-format-decimal-separator">decimal-separator</xtermref>  character if there is one, or the part that appears
                  to the right of the rightmost active character otherwise. The fractional part may be zero-length.</p></div3><div3 id="analyzing-picture-string"><head>Analyzing the picture string</head><p>This phase of the algorithm analyzes 
                  the <termref def="dt-picture-string">picture string</termref> and the properties from the selected
decimal format in the static context, and it has the effect
of setting the values of various variables, which are used in the
subsequent formatting phase. These variables are listed below.
Each is shown with its initial setting and its datatype.
					</p><p>Several variables are associated with each sub-picture. If there are
two sub-pictures, then these rules are applied to one sub-picture to obtain the values
that apply to positive <phrase diff="add" at="D">and unsigned zero</phrase> numbers, and to the other to obtain the values that apply
to negative numbers. If there is only one sub-picture, then the values for both cases
are derived from this sub-picture.</p><p>The variables are as follows:</p><ulist><item><p>The <var>integer-part-grouping-positions</var> is a sequence of integers
representing the positions of grouping separators within the integer part of the
sub-picture. For each <xtermref spec="XP31" ref="id-static-decimal-format-grouping-separator">grouping-separator</xtermref> character that appears within the
integer part of the sub-picture, this sequence contains an integer that is equal
to the total number of <termref def="dt-optional-digit-character">optional digit character</termref> and <termref def="dt-decimal-digit-family">decimal digit family</termref>
characters that appear within the integer part of the sub-picture and to the right of the 
<xtermref spec="XP31" ref="id-static-decimal-format-grouping-separator">grouping-separator</xtermref> character.</p><p diff="add" at="E">The grouping is defined to be <term>regular</term> if the following conditions apply:</p><olist><item><p>There is an least one grouping-separator in the integer part of the sub-picture.</p></item><item><p>There is a positive integer <var>G</var> (the grouping size) such that the position of every grouping-separator
                        in the integer part of the sub-picture is a positive integer multiple of <var>G</var>.</p></item><item><p>Every position in the integer part of the sub-picture that is a positive integer multiple of <var>G</var>
                        is occupied by a grouping-separator.</p></item></olist><p>If the grouping is regular, then the <var>integer-part-grouping-positions</var> sequence contains all
integer multiples of <var>G</var> as far as necessary to accommodate the largest 
possible number.</p></item><item><p>The <var>minimum-integer-part-size</var> is an integer indicating the minimum number of digits that will
 appear to the left of the <var>decimal-separator</var> character. It is <phrase diff="chg" at="D">initially</phrase> set to 
 the number of <termref def="dt-decimal-digit-family">decimal digit family</termref> characters found in the integer part of the sub-picture,
                        <phrase diff="add" at="D">but may be adjusted as described below.</phrase> <phrase diff="del" at="D">
 But if the sub-picture contains no <termref def="dt-decimal-digit-family">decimal digit family</termref> character and no 
                        <xtermref spec="XP31" ref="id-static-decimal-format-decimal-separator">decimal-separator</xtermref>  character,
 it is set to one.</phrase></p><note><p>There is no maximum integer part size. All significant digits in the integer part of the
                           number will be displayed, even if this exceeds the number of <termref def="dt-optional-digit-character">optional digit character</termref> and
 <termref def="dt-decimal-digit-family">decimal digit family</termref> characters in the subpicture.</p></note></item><item><p diff="add" at="D">The <var>scaling factor</var> is a non-negative integer used to determine the scaling of the mantissa
                        in exponential notation. It is set to the number of <termref def="dt-decimal-digit-family">decimal digit family</termref> 
                        characters found in the integer part of the sub-picture.</p></item><item><p>The <var>prefix</var> is set to contain all passive characters
in the sub-picture to the left of the leftmost active character.
If the picture string contains only one sub-picture, 
the <var>prefix</var> 
for the negative sub-picture is set by concatenating the <xtermref spec="XP31" ref="id-static-decimal-format-minus-sign">minus-sign</xtermref> 
character and the <var>prefix</var> for the positive sub-picture (if any),
in that order.</p></item><item><p>The <var>fractional-part-grouping-positions</var> is a sequence of integers
representing the positions of grouping separators within the fractional part of the
sub-picture. For each <xtermref spec="XP31" ref="id-static-decimal-format-grouping-separator">grouping-separator</xtermref> character that appears within the
fractional part of the sub-picture, this sequence contains an integer that is equal
to the total number of <termref def="dt-optional-digit-character">optional digit character</termref> and <termref def="dt-decimal-digit-family">decimal digit family</termref> 
characters that appear within the fractional part of the sub-picture and to the left of the 
<xtermref spec="XP31" ref="id-static-decimal-format-grouping-separator">grouping-separator</xtermref> character.</p><note><p>There is no need to extrapolate grouping positions on the fractional side,
                     because the number of digits in the output will never exceed the number of 
                        <termref def="dt-optional-digit-character">optional digit character</termref> and <termref def="dt-decimal-digit-family">decimal digit family</termref> characters
                     in the fractional part of the sub-picture.</p></note></item><item><p>The <var>minimum-fractional-part-size</var> is set to the number of 
<termref def="dt-decimal-digit-family">decimal digit family</termref> characters found in the fractional part of the sub-picture.</p></item><item><p>The <var>maximum-fractional-part-size</var> is set to the total number of 
                        <termref def="dt-optional-digit-character">optional digit character</termref> and 
                        <termref def="dt-decimal-digit-family">decimal digit family</termref> characters found 
                        in the fractional part of the sub-picture.</p></item><item diff="add" at="D"><p>If the effect of the above rules is that <var>minimum-integer-part-size</var> and 
                        <var>maximum-fractional-part-size</var> are both zero, then an adjustment is applied as follows:</p><ulist><item><p>If an exponent separator is present then:</p><ulist><item><p><var>minimum-fractional-part-size</var> is changed to 1 (one).</p></item><item><p><var>maximum-fractional-part-size</var> is changed to 1 (one).</p></item></ulist><note><p>This has the effect that with the picture <code>#.e9</code>, the value <code>0.123</code> is formatted as <code>0.1e0</code></p></note></item><item><p>Otherwise:</p><ulist><item><p><var>minimum-integer-part-size</var> is changed to 1 (one).</p></item></ulist><note><p>This has the effect that with the picture <code>#</code>, the value <code>0.23</code> is formatted
                              as <code>0</code></p></note></item></ulist></item><item diff="add" at="D"><p>If all the following conditions are true:</p><ulist><item><p>An exponent separator is present</p></item><item><p>The <var>minimum-integer-part-size</var> is zero</p></item><item><p>There is at least one <termref def="dt-optional-digit-character">optional digit character</termref> 
                           in the integer part of the sub-picture</p></item></ulist><p>then the <var>minimum-integer-part-size</var> is changed to 1 (one).</p><note><p>This has the effect that with the picture <code>.9e9</code>, the value <code>0.1</code> is formatted
                        as <code>.1e0</code>, while with the picture <code>#.9e9</code>, it is formatted as <code>0.1e0</code></p></note></item><item diff="add" at="D"><p>If (after making the above adjustments) the <var>minimum-integer-part-size</var> and the 
                        <var>minimum-fractional-part-size</var> are both zero, then the <var>minimum-fractional-part-size</var> is set to 1 (one).</p></item><item diff="add" at="A"><p>The <var>minimum-exponent-size</var> is set to the number of 
                        <termref def="dt-decimal-digit-family">decimal digit family</termref> characters found in the exponent part of the sub-picture
                     if present, or zero otherwise.</p><note diff="add" at="D"><p>The rules for the syntax of the picture string ensure that if an exponent
                        separator is present, then the <var>minimum-exponent-size</var> will always be greater than zero.</p></note></item><item><p>The <var>suffix</var> is set to contain all passive characters to the right of the rightmost
active character in the sub-picture.</p></item></ulist><note><p>If there is only one sub-picture, then all variables
for positive numbers and negative numbers will be the same, except for  
<var>prefix</var>: the prefix for negative numbers will 
be preceded by the <xtermref spec="XP31" ref="id-static-decimal-format-minus-sign">minus-sign</xtermref> character.</p></note></div3><div3 id="formatting-the-number"><head>Formatting the number</head><p>This section describes the second phase of processing of the
<code>fn:format-number</code> function. This phase takes as input a number to be formatted
(referred to as the <emph>input number</emph>), and the variables set up by
analyzing the decimal format in the static context and the
<termref def="dt-picture-string">picture string</termref>, as described above.
 The result of this phase is a string, which forms the return value of 
the <code>fn:format-number</code> function.</p><p>The algorithm for this second stage of processing is as follows:</p><olist><item><p>If the input number is NaN (not a number), the result is the 
							 value of the <xtermref spec="XP31" ref="id-static-decimal-format-NaN">pattern separator</xtermref> property (with no
<var>prefix</var> or <var>suffix</var>).</p></item><item><p>In the rules below, the positive sub-picture and its associated variables are used 
							 if the input number is positive, and the negative sub-picture and its associated
                      variables are used if <phrase diff="add" at="D">it is negative. For <code>xs:double</code> and <code>xs:float</code>,
                      negative zero is taken as negative, positive zero as positive. For <code>xs:decimal</code>
                     and <code>xs:integer</code>, the positive sub-picture is used for zero.</phrase></p></item><item><p>The <var>adjusted number</var> is determined as follows:</p><ulist><item><p>If the sub-picture contains a <xtermref spec="XP31" ref="id-static-decimal-format-percent">percent</xtermref> character, 
                           the <var>adjusted number</var> is the input number multiplied by 100.</p></item><item><p>If the sub-picture contains a <xtermref spec="XP31" ref="id-static-decimal-format-per-mille">per-mille</xtermref> character, 
                           the <var>adjusted number</var> is the input number multiplied by 1000.</p></item><item><p diff="add" at="D">Otherwise, the <var>adjusted number</var> is the input number.</p></item></ulist><p diff="add" at="D">If the multiplication causes numeric overflow, no error occurs, and the 
                        <var>adjusted number</var> is positive or negative infinity as appropriate.</p></item><item><p>If the <phrase diff="add" at="D"><var>adjusted number</var></phrase> is positive or negative infinity, the result is the 
                        concatenation of the appropriate <var>prefix</var>, the value of the <xtermref spec="XP31" ref="id-static-decimal-format-infinity">infinity</xtermref> property,
                        and the appropriate <var>suffix</var>.</p></item><item diff="chg" at="D"><p>If the <var>minimum exponent size</var> is non-zero, then the <var>adjusted number</var> is scaled to establish a 
                        <var>mantissa</var> and an integer <var>exponent</var>. The <var>mantissa</var> and <var>exponent</var> are chosen 
                        such that all the following conditions are true:</p><ulist><item><p>The primitive type of the <var>mantissa</var> is the same as the primitive type of the <var>adjusted number</var> (integer, decimal, float, or double).</p></item><item><p>The <var>mantissa</var> multiplied by ten to the power of the exp<var/>onent is equal to the <var>adjusted number</var>.</p></item><item><p>The <var>mantissa</var> is less than 10<sup>N</sup>, and at least 10<sup>N-1</sup>, where <var>N</var> is the <var>scaling factor</var>.</p></item></ulist><p>If the <var>minimum exponent size</var> is zero, then the <var>mantissa</var> is the <var>adjusted number</var> and there is no <var>exponent</var>.</p></item><item><p>The <var diff="chg" at="A">mantissa</var> is converted (if necessary) to
 an <code>xs:decimal</code> value,
using an implementation of <code>xs:decimal</code> that imposes no limits on the
<code>totalDigits</code> or <code>fractionDigits</code> facets. If there are several 
such values that
are numerically equal to the <var diff="chg" at="A">mantissa</var> (bearing in mind that if the
<var diff="chg" at="A">mantissa</var> is an <code>xs:double</code> or <code>xs:float</code>, the comparison will be done by
converting the decimal value back to an <code>xs:double</code> or <code>xs:float</code>), the one that
is chosen <rfc2119>should</rfc2119> be one with the smallest possible number of digits
not counting leading or trailing zeroes (whether significant or insignificant). 
For example, 1.0 is preferred to
0.9999999999, and 100000000 is preferred to 100000001. This value is then
rounded so that it uses no more than <code>maximum-fractional-part-size</code> digits in
its fractional part. The <var>rounded number</var> is defined to be the result of
converting the <var diff="chg" at="A">mantissa</var> to an <code>xs:decimal</code> value, as described above,
and then calling the function <code>fn:round-half-to-even</code> with this converted number
as the first argument and the <code>maximum-fractional-part-size</code> as the second
argument, again with no limits on the <code>totalDigits</code> or <code>fractionDigits</code> in the
result.</p></item><item><p>The absolute value of the <var>rounded number</var> is converted to a string in decimal notation, 
                        using the digits in the <termref def="dt-decimal-digit-family">decimal digit family</termref> to 
                        represent the ten decimal digits, and the <xtermref spec="XP31" ref="id-static-decimal-format-decimal-separator">decimal-separator</xtermref> 
                        character to separate the integer part and the fractional part. This string must always contain a 
                        <xtermref spec="XP31" ref="id-static-decimal-format-decimal-separator">decimal-separator</xtermref>, 
                        and it must contain no leading zeroes and no trailing zeroes. The value zero will at this stage be 
                        represented by a <xtermref spec="XP31" ref="id-static-decimal-format-decimal-separator">decimal-separator</xtermref> 
                        on its own.</p></item><item><p>If the number of digits to the left of the <xtermref spec="XP31" ref="id-static-decimal-format-decimal-separator">decimal-separator</xtermref>  character is less than
<var>minimum-integer-part-size</var>, leading <xtermref spec="XP31" ref="id-static-decimal-format-zero-digit">zero digit</xtermref> 
characters are added to pad out to that size.</p></item><item><p>If the number of digits to the right of the <xtermref spec="XP31" ref="id-static-decimal-format-decimal-separator">decimal-separator</xtermref>  character is less than
<var>minimum-fractional-part-size</var>, trailing <xtermref spec="XP31" ref="id-static-decimal-format-zero-digit">zero digit</xtermref> 
characters are added to pad out to that size.</p></item><item><p>For each integer <var>N</var> in the <var>integer-part-grouping-positions</var> list,  
a <xtermref spec="XP31" ref="id-static-decimal-format-grouping-separator">grouping-separator</xtermref> character is inserted into the string immediately
after that digit that appears in the integer part of the number and has <var>N</var> digits
between it and the <xtermref spec="XP31" ref="id-static-decimal-format-decimal-separator">decimal-separator</xtermref>  character, if there is such a digit.</p></item><item><p>For each integer <var>N</var> in the <var>fractional-part-grouping-positions</var> list,  
a <xtermref spec="XP31" ref="id-static-decimal-format-grouping-separator">grouping-separator</xtermref> character is inserted into the string immediately
before that digit that appears in the fractional part of the number and has <var>N</var> digits
between it and the <xtermref spec="XP31" ref="id-static-decimal-format-decimal-separator">decimal-separator</xtermref>  character, if there is such a digit.</p></item><item><p>If there is no <xtermref spec="XP31" ref="id-static-decimal-format-decimal-separator">decimal-separator</xtermref>  character in the sub-picture, 
or if there are no digits to the right of the 
<var>decimal-separator</var> character in the string, then the
<var>decimal-separator</var> character is removed from the string (it will be the rightmost 
character in the string).</p></item><item diff="add" at="A"><p>If an <var>exponent</var> exists, then the string
                  produced from the <var>mantissa</var> as described above is extended with
                     the following, in order:
                  (a) the <xtermref spec="XP31" ref="id-static-decimal-format-exponent-separator">exponent-separator</xtermref> character; (b) if the <var>exponent</var> is negative,
                  the <xtermref spec="XP31" ref="id-static-decimal-format-minus-sign">minus-sign</xtermref> character; (c) the value of the <var>exponent</var> represented
                  as a decimal integer, extended if necessary with leading zeroes to make it up to
                  the <var>minimum exponent size</var>, using digits taken from the
                  <termref def="dt-decimal-digit-family">decimal digit family</termref>.</p></item><item><p>The result of the function is the concatenation of the appropriate <var>prefix</var>, the 
string conversion of the number as obtained above, and the appropriate <var>suffix</var>.</p></item></olist></div3></div2><div2 id="trigonometry"><head>Trigonometric and exponential functions</head><p>The functions in this section perform trigonometric and other mathematical calculations on <code>xs:double</code> values. They
			are provided primarily for use in applications performing geometrical computation, for example when generating 
			SVG graphics.</p><p>Functions are provided to support the six most commonly used trigonometric calculations: sine, cosine and tangent, 
			and their inverses arc sine, arc cosine, and arc tangent. Other functions such as secant, cosecant, and cotangent are
			not provided because they are easily computed in terms of these six.</p><p>The functions in this section (with the exception of <code>math:pi</code>) 
		      are specified by reference to <bibref ref="ieee754-2008"/>, where
		   they appear as <emph>Recommended operations</emph> in section 9. IEEE defines
		   these functions for a variety of floating point formats; this specification
		   defines them only for <code>xs:double</code> values. The IEEE specification
		   applies with the following caveats:</p><olist><item><p>IEEE states that the preferred quantum is language-defined. In this
		       specification, it is <termref def="implementation-defined"/>.</p></item><item><p>IEEE states that certain functions should raise the inexact exception if the
		          result is inexact. 
		          In this specification, this exception if it occurs does not
		          result in an error. Any diagnostic information is outside the scope of this
		          specification.</p></item><item><p>IEEE defines various rounding algorithms for inexact results, and states
		          that the choice of rounding direction, and the mechanisms for influencing this choice,
		          are language-defined. In this specification, the rounding direction and any mechanisms for
		          influencing it are <termref def="implementation-defined"/>.</p></item><item><p>Certain operations (such as taking the square root of a negative number)
		          are defined in IEEE to signal the invalid operation exception and return a
		          quiet NaN. In this specification, such operations return <code>NaN</code>
		          and do not raise an error. The same policy applies to operations (such as taking
		          the logarithm of zero) that raise a divide-by-zero exception. Any diagnostic 
		          information is outside the scope of this specification. </p></item><item><p>Operations whose mathematical result is greater than the largest finite <code>xs:double</code>
		          value are defined in IEEE to signal the overflow exception; operations whose mathematical
		          result is closer to zero than the smallest non-zero <code>xs:double</code> value are similarly
		       defined in IEEE to signal the underflow exception. The treatment of these exceptions in
		       this specification is defined in <specref ref="op.numeric"/>.</p></item></olist><table class="index"><thead><tr><th rowspan="1" colspan="1">Function</th><th rowspan="1" colspan="1">Meaning</th></tr></thead><tbody><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">math:pi</code></td><td rowspan="1" colspan="1">Returns an approximation to the mathematical constant <var>π</var>.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">math:exp</code></td><td rowspan="1" colspan="1">Returns the value of <var>e</var><sup><var>x</var></sup>.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">math:exp10</code></td><td rowspan="1" colspan="1">Returns the value of <code>10</code><sup><var>x</var></sup>.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">math:log</code></td><td rowspan="1" colspan="1">Returns the natural logarithm of the argument.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">math:log10</code></td><td rowspan="1" colspan="1">Returns the base-ten logarithm of the argument.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">math:pow</code></td><td rowspan="1" colspan="1">Returns the result of raising the first argument to the power of the second.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">math:sqrt</code></td><td rowspan="1" colspan="1">Returns the non-negative square root of the argument.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">math:sin</code></td><td rowspan="1" colspan="1">Returns the sine of the argument. The argument is an angle in radians.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">math:cos</code></td><td rowspan="1" colspan="1">Returns the cosine of the argument. The argument is an angle in radians.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">math:tan</code></td><td rowspan="1" colspan="1">Returns the tangent of the argument. The argument is an angle in radians.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">math:asin</code></td><td rowspan="1" colspan="1">Returns the arc sine of the argument.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">math:acos</code></td><td rowspan="1" colspan="1">Returns the arc cosine of the argument.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">math:atan</code></td><td rowspan="1" colspan="1">Returns the arc tangent of the argument.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">math:atan2</code></td><td rowspan="1" colspan="1">Returns the angle in radians subtended at the origin by the point on a plane with
            coordinates (x, y) and the positive x-axis.</td></tr></tbody></table><p/><div3 id="func-math-pi"><head>math:pi</head><glist><gitem><label>Summary</label><def><p>Returns an approximation to the mathematical constant <var>π</var>.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="pi" return-type="xs:double" isOp="no" prefix="math" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"/></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>This function returns the <code>xs:double</code> value whose lexical representation is
            3.141592653589793e0</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>2*math:pi()</code> returns <code>6.283185307179586e0</code>.</p><p>The expression <code>60 * (math:pi() div 180)</code> converts an angle of 60 degrees
               to radians. </p></def></gitem></glist></div3><div3 id="func-math-exp"><head>math:exp</head><glist><gitem><label>Summary</label><def><p>Returns the value of <var>e</var><sup><var>x</var></sup>.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="exp" return-type="xs:double?" isOp="no" prefix="math" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg" type="xs:double?"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>If <code>$arg</code> is the empty sequence, the function returns the empty sequence.</p><p>Otherwise the result is the mathematical constant <var>e</var> raised to the power of
               <code>$arg</code>, as defined in the <bibref ref="ieee754-2008"/> specification of
            the <code>exp</code> function applied to 64-bit binary floating point values.</p></def></gitem><gitem><label>Notes</label><def><p role="note">The treatment of overflow and underflow is defined in <specref ref="op.numeric"/>.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>math:exp(())</code> returns <code>()</code>.</p><p>The expression <code>math:exp(0)</code> returns <code>1.0e0</code>.</p><p>The expression <code>math:exp(1)</code> returns <code>2.7182818284590455e0</code> (approximately).</p><p>The expression <code>math:exp(2)</code> returns <code>7.38905609893065e0</code>.</p><p>The expression <code>math:exp(-1)</code> returns <code>0.36787944117144233e0</code>.</p><p>The expression <code>math:exp(math:pi())</code> returns <code>23.140692632779267e0</code>.</p><p>The expression <code>math:exp(xs:double('NaN'))</code> returns <code>xs:double('NaN')</code>.</p><p>The expression <code>math:exp(xs:double('INF'))</code> returns <code>xs:double('INF')</code>.</p><p>The expression <code>math:exp(xs:double('-INF'))</code> returns <code>0.0e0</code>.</p></def></gitem></glist></div3><div3 id="func-math-exp10"><head>math:exp10</head><glist><gitem><label>Summary</label><def><p>Returns the value of <code>10</code><sup><var>x</var></sup>.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="exp10" return-type="xs:double?" isOp="no" prefix="math" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg" type="xs:double?"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>If <code>$arg</code> is the empty sequence, the function returns the empty sequence.</p><p>Otherwise the result is ten raised to the power of <code>$arg</code>, as defined in the
               <bibref ref="ieee754-2008"/> specification of the <code>exp10</code> function applied
            to 64-bit binary floating point values.</p></def></gitem><gitem><label>Notes</label><def><p role="note">The treatment of overflow and underflow is defined in <specref ref="op.numeric"/>.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>math:exp10(())</code> returns <code>()</code>.</p><p>The expression <code>math:exp10(0)</code> returns <code>1.0e0</code>.</p><p>The expression <code>math:exp10(1)</code> returns <code>1.0e1</code>.</p><p>The expression <code>math:exp10(0.5)</code> returns <code>3.1622776601683795e0</code>.</p><p>The expression <code>math:exp10(-1)</code> returns <code>1.0e-1</code>.</p><p>The expression <code>math:exp10(xs:double('NaN'))</code> returns <code>xs:double('NaN')</code>.</p><p>The expression <code>math:exp10(xs:double('INF'))</code> returns <code>xs:double('INF')</code>.</p><p>The expression <code>math:exp10(xs:double('-INF'))</code> returns <code>0.0e0</code>.</p></def></gitem></glist></div3><div3 id="func-math-log"><head>math:log</head><glist><gitem><label>Summary</label><def><p>Returns the natural logarithm of the argument.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="log" return-type="xs:double?" isOp="no" prefix="math" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg" type="xs:double?"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>If <code>$arg</code> is the empty sequence, the function returns the empty sequence.</p><p>Otherwise the result is the natural logarithm of <code>$arg</code>, as defined in the
               <bibref ref="ieee754-2008"/> specification of the <code>log</code> function applied
            to 64-bit binary floating point values.</p></def></gitem><gitem><label>Notes</label><def><p role="note">The treatment of <code>divideByZero</code> and <code>invalidOperation</code> exceptions
            is defined in <specref ref="op.numeric"/>. <phrase diff="chg" at="D">The effect is that if the argument is 
            zero, the result is <code>-INF</code>, and if it is negative, the result is <code>NaN</code></phrase>.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>math:log(())</code> returns <code>()</code>.</p><p>The expression <code>math:log(0)</code> returns <code>xs:double('-INF')</code>.</p><p>The expression <code>math:log(math:exp(1))</code> returns <code>1.0e0</code>.</p><p>The expression <code>math:log(1.0e-3)</code> returns <code>-6.907755278982137e0</code>.</p><p>The expression <code>math:log(2)</code> returns <code>0.6931471805599453e0</code>.</p><p>The expression <code>math:log(-1)</code> returns <code>xs:double('NaN')</code>.</p><p>The expression <code>math:log(xs:double('NaN'))</code> returns <code>xs:double('NaN')</code>.</p><p>The expression <code>math:log(xs:double('INF'))</code> returns <code>xs:double('INF')</code>.</p><p>The expression <code>math:log(xs:double('-INF'))</code> returns <code>xs:double('NaN')</code>.</p></def></gitem></glist></div3><div3 id="func-math-log10"><head>math:log10</head><glist><gitem><label>Summary</label><def><p>Returns the base-ten logarithm of the argument.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="log10" return-type="xs:double?" isOp="no" prefix="math" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg" type="xs:double?"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>If <code>$arg</code> is the empty sequence, the function returns the empty sequence.</p><p>Otherwise the result is the base-10 logarithm of <code>$arg</code>, as defined in the
               <bibref ref="ieee754-2008"/> specification of the <code>log10</code> function applied
            to 64-bit binary floating point values.</p></def></gitem><gitem><label>Notes</label><def><p role="note">The treatment of <code>divideByZero</code> and <code>invalidOperation</code> exceptions
            is defined in <specref ref="op.numeric"/>. <phrase diff="chg" at="D">The effect is that if the argument is 
               zero, the result is <code>-INF</code>, and if it is negative, the result is <code>NaN</code></phrase>.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>math:log10(())</code> returns <code>()</code>.</p><p>The expression <code>math:log10(0)</code> returns <code>xs:double('-INF')</code>.</p><p>The expression <code>math:log10(1.0e3)</code> returns <code>3.0e0</code>.</p><p>The expression <code>math:log10(1.0e-3)</code> returns <code>-3.0e0</code>.</p><p>The expression <code>math:log10(2)</code> returns <code>0.3010299956639812e0</code>.</p><p>The expression <code>math:log10(-1)</code> returns <code>xs:double('NaN')</code>.</p><p>The expression <code>math:log10(xs:double('NaN'))</code> returns <code>xs:double('NaN')</code>.</p><p>The expression <code>math:log10(xs:double('INF'))</code> returns <code>xs:double('INF')</code>.</p><p>The expression <code>math:log10(xs:double('-INF'))</code> returns <code>xs:double('NaN')</code>.</p></def></gitem></glist></div3><div3 id="func-math-pow"><head>math:pow</head><glist><gitem><label>Summary</label><def><p>Returns the result of raising the first argument to the power of the second.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="pow" return-type="xs:double?" isOp="no" prefix="math" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="x" type="xs:double?"/><arg name="y" type="xs:numeric"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>If <code>$x</code> is the empty sequence, the function returns the empty sequence.</p><p>If <code>$y</code> is an instance of <code>xs:integer</code>, the result is
               <code>$x</code> raised to the power of <code>$y</code> as defined in the <bibref ref="ieee754-2008"/> specification of the <code>pown</code> function applied to a
            64-bit binary floating point value and an integer.</p><p>Otherwise <code>$y</code> is converted to an <code>xs:double</code> by numeric
            promotion, and the result is the value of <code>$x</code> raised to the power of
               <code>$y</code> as defined in the <bibref ref="ieee754-2008"/> specification of the
               <code>pow</code> function applied to two 64-bit binary floating point values.</p></def></gitem><gitem><label>Notes</label><def><p role="note">The treatment of the <code>divideByZero</code> and <code>invalidOperation</code>
            exceptions is defined in <specref ref="op.numeric"/>. Some of the consequences are
            illustrated in the examples below.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>math:pow((), 93.7)</code> returns <code>()</code>.</p><p>The expression <code>math:pow(2, 3)</code> returns <code>8.0e0</code>.</p><p>The expression <code>math:pow(-2, 3)</code> returns <code>-8.0e0</code>.</p><p>The expression <code>math:pow(2, -3)</code> returns <code>0.125e0</code>.</p><p>The expression <code>math:pow(-2, -3)</code> returns <code>-0.125e0</code>.</p><p>The expression <code>math:pow(2, 0)</code> returns <code>1.0e0</code>.</p><p>The expression <code>math:pow(0, 0)</code> returns <code>1.0e0</code>.</p><p>The expression <code>math:pow(xs:double('INF'), 0)</code> returns <code>1.0e0</code>.</p><p>The expression <code>math:pow(xs:double('NaN'), 0)</code> returns <code>1.0e0</code>.</p><p>The expression <code>math:pow(-math:pi(), 0)</code> returns <code>1.0e0</code>.</p><p>The expression <code>math:pow(0e0, 3)</code> returns <code>0.0e0</code>.</p><p>The expression <code>math:pow(0e0, 4)</code> returns <code>0.0e0</code>.</p><p>The expression <code>math:pow(-0e0, 3)</code> returns <code>-0.0e0</code>.</p><p>The expression <code>math:pow(0, 4)</code> returns <code>0.0e0</code>.</p><p>The expression <code>math:pow(0e0, -3)</code> returns <code>xs:double('INF')</code>.</p><p>The expression <code>math:pow(0e0, -4)</code> returns <code>xs:double('INF')</code>.</p><p>The expression <code>math:pow(-0e0, -3)</code> returns <code>xs:double('-INF')</code>.</p><p>The expression <code>math:pow(0, -4)</code> returns <code>xs:double('INF')</code>.</p><p>The expression <code>math:pow(16, 0.5e0)</code> returns <code>4.0e0</code>.</p><p>The expression <code>math:pow(16, 0.25e0)</code> returns <code>2.0e0</code>.</p><p>The expression <code>math:pow(0e0, -3.0e0)</code> returns <code>xs:double('INF')</code>.</p><p>The expression <code>math:pow(-0e0, -3.0e0)</code> returns <code>xs:double('-INF')</code>. <emph>(Odd-valued whole numbers are treated specially).</emph></p><p>The expression <code>math:pow(0e0, -3.1e0)</code> returns <code>xs:double('INF')</code>.</p><p>The expression <code>math:pow(-0e0, -3.1e0)</code> returns <code>xs:double('INF')</code>.</p><p>The expression <code>math:pow(0e0, 3.0e0)</code> returns <code>0.0e0</code>.</p><p>The expression <code>math:pow(-0e0, 3.0e0)</code> returns <code>-0.0e0</code>. <emph>(Odd-valued whole numbers are treated specially).</emph></p><p>The expression <code>math:pow(0e0, 3.1e0)</code> returns <code>0.0e0</code>.</p><p>The expression <code>math:pow(-0e0, 3.1e0)</code> returns <code>0.0e0</code>.</p><p>The expression <code>math:pow(-1, xs:double('INF'))</code> returns <code>1.0e0</code>.</p><p>The expression <code>math:pow(-1, xs:double('-INF'))</code> returns <code>1.0e0</code>.</p><p>The expression <code>math:pow(1, xs:double('INF'))</code> returns <code>1.0e0</code>.</p><p>The expression <code>math:pow(1, xs:double('-INF'))</code> returns <code>1.0e0</code>.</p><p>The expression <code>math:pow(1, xs:double('NaN'))</code> returns <code>1.0e0</code>.</p><p>The expression <code>math:pow(-2.5e0, 2.0e0)</code> returns <code>6.25e0</code>.</p><p>The expression <code>math:pow(-2.5e0, 2.00000001e0)</code> returns <code>xs:double('NaN')</code>.</p></def></gitem></glist></div3><div3 id="func-math-sqrt"><head>math:sqrt</head><glist><gitem><label>Summary</label><def><p>Returns the non-negative square root of the argument.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="sqrt" return-type="xs:double?" isOp="no" prefix="math" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg" type="xs:double?"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>If <code>$arg</code> is the empty sequence, the function returns the empty sequence.</p><p>Otherwise the result is the mathematical non-negative square root of <code>$arg</code>
            as defined in the <bibref ref="ieee754-2008"/> specification of the
               <code>squareRoot</code> function applied to 64-bit binary floating point values.</p></def></gitem><gitem><label>Notes</label><def><p role="note">The treatment of the <code>invalidOperation</code> exception is defined in <specref ref="op.numeric"/>. The effect is that if the argument is less than zero, the result
            is <code>NaN</code>.</p><p role="note">If <code>$arg</code> is positive or negative zero, positive infinity, or
               <code>NaN</code>, then the result is <code>$arg</code>. (Negative zero is the only
            case where the result can have negative sign)</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>math:sqrt(())</code> returns <code>()</code>.</p><p>The expression <code>math:sqrt(0.0e0)</code> returns <code>0.0e0</code>.</p><p>The expression <code>math:sqrt(-0.0e0)</code> returns <code>-0.0e0</code>.</p><p>The expression <code>math:sqrt(1.0e6)</code> returns <code>1.0e3</code>.</p><p>The expression <code>math:sqrt(2.0e0)</code> returns <code>1.4142135623730951e0</code>.</p><p>The expression <code>math:sqrt(-2.0e0)</code> returns <code>xs:double('NaN')</code>.</p><p>The expression <code>math:sqrt(xs:double('NaN'))</code> returns <code>xs:double('NaN')</code>.</p><p>The expression <code>math:sqrt(xs:double('INF'))</code> returns <code>xs:double('INF')</code>.</p><p>The expression <code>math:sqrt(xs:double('-INF'))</code> returns <code>xs:double('NaN')</code>.</p></def></gitem></glist></div3><div3 id="func-math-sin"><head>math:sin</head><glist><gitem><label>Summary</label><def><p>Returns the sine of the argument. The argument is an angle in radians.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="sin" return-type="xs:double?" isOp="no" prefix="math" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="θ" type="xs:double?"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>If <code>$</code><var>θ</var> is the empty sequence, the function returns the empty
            sequence.</p><p>Otherwise the result is the sine of <code>$</code><var>θ</var> (which is treated as an angle in
            radians) as defined in the <bibref ref="ieee754-2008"/> specification of the
               <code>sin</code> function applied to 64-bit binary floating point values.</p></def></gitem><gitem><label>Notes</label><def><p role="note">The treatment of the <code>invalidOperation</code> and <code>underflow</code> exceptions
            is defined in <specref ref="op.numeric"/>. </p><p role="note">If <code>$</code><var>θ</var> is positive or negative zero, the result is
               <code>$</code><var>θ</var>.</p><p role="note">If <code>$</code><var>θ</var> is positive or negative infinity, or <code>NaN</code>,
            then the result is <code>NaN</code>.</p><p role="note">Otherwise the result is always in the range -1.0e0 to +1.0e0</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>math:sin(())</code> returns <code>()</code>.</p><p>The expression <code>math:sin(0)</code> returns <code>0.0e0</code>.</p><p>The expression <code>math:sin(-0.0e0)</code> returns <code>-0.0e0</code>.</p><p>The expression <code>math:sin(math:pi() div 2)</code> returns <code>1.0e0</code> (approximately).</p><p>The expression <code>math:sin(-math:pi() div 2)</code> returns <code>-1.0e0</code> (approximately).</p><p>The expression <code>math:sin(math:pi())</code> returns <code>0.0e0</code> (approximately).</p><p>The expression <code>math:sin(xs:double('NaN'))</code> returns <code>xs:double('NaN')</code>.</p><p>The expression <code>math:sin(xs:double('INF'))</code> returns <code>xs:double('NaN')</code>.</p><p>The expression <code>math:sin(xs:double('-INF'))</code> returns <code>xs:double('NaN')</code>.</p></def></gitem></glist></div3><div3 id="func-math-cos"><head>math:cos</head><glist><gitem><label>Summary</label><def><p>Returns the cosine of the argument. The argument is an angle in radians.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="cos" return-type="xs:double?" isOp="no" prefix="math" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="θ" type="xs:double?"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>If <code>$</code><var>θ</var> is the empty sequence, the function returns the empty
            sequence.</p><p>If <code>$</code><var>θ</var> is positive or negative infinity, or <code>NaN</code>,
            then the result is <code>NaN</code>.</p><p>Otherwise the result is the cosine of <code>$</code><var>θ</var> (which is treated as an angle in
            radians) as defined in the <bibref ref="ieee754-2008"/> specification of the
               <code>cos</code> function applied to 64-bit binary floating point values.</p></def></gitem><gitem><label>Notes</label><def><p role="note">The treatment of the <code>invalidOperation</code> exception is defined in <specref ref="op.numeric"/>. </p><p role="note">If <code>$</code><var>θ</var> is positive or negative zero, the result is
               <code>$</code><var>θ</var>.</p><p role="note">If <code>$</code><var>θ</var> is positive or negative infinity, or <code>NaN</code>,
            then the result is <code>NaN</code>.</p><p role="note">Otherwise the result is always in the range -1.0e0 to +1.0e0</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>math:cos(())</code> returns <code>()</code>.</p><p>The expression <code>math:cos(0)</code> returns <code>1.0e0</code>.</p><p>The expression <code>math:cos(-0.0e0)</code> returns <code>1.0e0</code>.</p><p>The expression <code>math:cos(math:pi() div 2)</code> returns <code>0.0e0</code> (approximately).</p><p>The expression <code>math:cos(-math:pi() div 2)</code> returns <code>0.0e0</code> (approximately).</p><p>The expression <code>math:cos(math:pi())</code> returns <code>-1.0e0</code> (approximately).</p><p>The expression <code>math:cos(xs:double('NaN'))</code> returns <code>xs:double('NaN')</code>.</p><p>The expression <code>math:cos(xs:double('INF'))</code> returns <code>xs:double('NaN')</code>.</p><p>The expression <code>math:cos(xs:double('-INF'))</code> returns <code>xs:double('NaN')</code>.</p></def></gitem></glist></div3><div3 id="func-math-tan"><head>math:tan</head><glist><gitem><label>Summary</label><def><p>Returns the tangent of the argument. The argument is an angle in radians.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="tan" return-type="xs:double?" isOp="no" prefix="math" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="θ" type="xs:double?"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>If <code>$</code><var>θ</var> is the empty sequence, the function returns the empty
            sequence.</p><p>Otherwise the result is the tangent of <code>$</code><var>θ</var> (which is treated as an angle
            in radians) as defined in the <bibref ref="ieee754-2008"/> specification of the
               <code>tan</code> function applied to 64-bit binary floating point values.</p></def></gitem><gitem><label>Notes</label><def><p role="note">The treatment of the <code>invalidOperation</code> and <code>underflow</code> exceptions
            is defined in <specref ref="op.numeric"/>. </p><p role="note">If <code>$</code><var>θ</var> is positive or negative infinity, or <code>NaN</code>,
            then the result is <code>NaN</code>.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>math:tan(())</code> returns <code>()</code>.</p><p>The expression <code>math:tan(0)</code> returns <code>0.0e0</code>.</p><p>The expression <code>math:tan(-0.0e0)</code> returns <code>-0.0e0</code>.</p><p>The expression <code>math:tan(math:pi() div 4)</code> returns <code>1.0e0</code> (approximately).</p><p>The expression <code>math:tan(-math:pi() div 4)</code> returns <code>-1.0e0</code> (approximately).</p><p>The expression <code>1 div math:tan(math:pi() div 2)</code> returns <code>0.0e0</code> (approximately). <emph>(Mathematically, <emph>tan(π/2)</emph> is positive infinity. But because <code>math:pi() div 2</code>
                  returns an approximation, the result of <code>math:tan(math:pi() div 2)</code> will be a large
                  but finite number.)</emph></p><p>The expression <code>1 div math:tan(-math:pi() div 2)</code> returns <code>-0.0e0</code> (approximately). <emph>(Mathematically, <emph>tan(-π/2)</emph> is negative infinity. But because <code>-math:pi() div 2</code>
                  returns an approximation, the result of <code>math:tan(-math:pi() div 2)</code> will be a large
                  but finite negative number.)</emph></p><p>The expression <code>math:tan(math:pi())</code> returns <code>0.0e0</code> (approximately).</p><p>The expression <code>math:tan(xs:double('NaN'))</code> returns <code>xs:double('NaN')</code>.</p><p>The expression <code>math:tan(xs:double('INF'))</code> returns <code>xs:double('NaN')</code>.</p><p>The expression <code>math:tan(xs:double('-INF'))</code> returns <code>xs:double('NaN')</code>.</p></def></gitem></glist></div3><div3 id="func-math-asin"><head>math:asin</head><glist><gitem><label>Summary</label><def><p>Returns the arc sine of the argument.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="asin" return-type="xs:double?" isOp="no" prefix="math" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg" type="xs:double?"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>If <code>$arg</code> is the empty sequence, the function returns the empty sequence.</p><p>Otherwise the result is the arc sine of <code>$arg</code> as defined in the <bibref ref="ieee754-2008"/> specification of the
            <code>asin</code> function applied to 64-bit binary floating point values. 
            The result is in the range -<var>π</var>/2 to +<var>π</var>/2 radians. </p></def></gitem><gitem><label>Notes</label><def><p role="note">The treatment of the <code>invalidOperation</code> and <code>underflow</code> exceptions
            is defined in <specref ref="op.numeric"/>. </p><p role="note">If <code>$arg</code> is positive or negative zero, the result is <code>$arg</code>.</p><p role="note">If <code>$arg</code> is <code>NaN</code>, or if its absolute value is greater than one,
            then the result is <code>NaN</code>.</p><p role="note">In other cases the result is an <code>xs:double</code> value representing an angle
               <var>θ</var> in radians in the range -<var>π</var><code>/2 &lt;=
               </code><var>θ</var><code> &lt;= +</code><var>π</var><code>/2</code>. </p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>math:asin(())</code> returns <code>()</code>.</p><p>The expression <code>math:asin(0)</code> returns <code>0.0e0</code>.</p><p>The expression <code>math:asin(-0.0e0)</code> returns <code>-0.0e0</code>.</p><p>The expression <code>math:asin(1.0e0)</code> returns <code>1.5707963267948966e0</code> (approximately).</p><p>The expression <code>math:asin(-1.0e0)</code> returns <code>-1.5707963267948966e0</code> (approximately).</p><p>The expression <code>math:asin(2.0e0)</code> returns <code>xs:double('NaN')</code>.</p><p>The expression <code>math:asin(xs:double('NaN'))</code> returns <code>xs:double('NaN')</code>.</p><p>The expression <code>math:asin(xs:double('INF'))</code> returns <code>xs:double('NaN')</code>.</p><p>The expression <code>math:asin(xs:double('-INF'))</code> returns <code>xs:double('NaN')</code>.</p></def></gitem></glist></div3><div3 id="func-math-acos"><head>math:acos</head><glist><gitem><label>Summary</label><def><p>Returns the arc cosine of the argument.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="acos" return-type="xs:double?" isOp="no" prefix="math" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg" type="xs:double?"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>If <code>$arg</code> is the empty sequence, the function returns the empty sequence.</p><p>Otherwise the result is the arc cosine of <code>$arg</code>, as defined in the <bibref ref="ieee754-2008"/> specification of the
               <code>acos</code> function applied to 64-bit binary floating point values.
            The result is in the range zero to +<var>π</var> radians.</p></def></gitem><gitem><label>Notes</label><def><p role="note">The treatment of the <code>invalidOperation</code> exception is defined in <specref ref="op.numeric"/>. </p><p role="note">If <code>$arg</code> is <code>NaN</code>, or if its absolute value is greater than one,
            then the result is <code>NaN</code>.</p><p role="note">In other cases the result is an <code>xs:double</code> value representing an angle
               <var>θ</var> in radians in the range <code>0 &lt;= </code><var>θ</var><code> &lt;=
               +</code><var>π</var>. </p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>math:acos(())</code> returns <code>()</code>.</p><p>The expression <code>math:acos(0)</code> returns <code>1.5707963267948966e0</code> (approximately).</p><p>The expression <code>math:acos(-0.0e0)</code> returns <code>1.5707963267948966e0</code> (approximately).</p><p>The expression <code>math:acos(1.0e0)</code> returns <code>0.0e0</code>.</p><p>The expression <code>math:acos(-1.0e0)</code> returns <code>3.141592653589793e0</code> (approximately).</p><p>The expression <code>math:acos(2.0e0)</code> returns <code>xs:double('NaN')</code>.</p><p>The expression <code>math:acos(xs:double('NaN'))</code> returns <code>xs:double('NaN')</code>.</p><p>The expression <code>math:acos(xs:double('INF'))</code> returns <code>xs:double('NaN')</code>.</p><p>The expression <code>math:acos(xs:double('-INF'))</code> returns <code>xs:double('NaN')</code>.</p></def></gitem></glist></div3><div3 id="func-math-atan"><head>math:atan</head><glist><gitem><label>Summary</label><def><p>Returns the arc tangent of the argument.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="atan" return-type="xs:double?" isOp="no" prefix="math" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg" type="xs:double?"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>If <code>$arg</code> is the empty sequence, the function returns the empty sequence.</p><p>Otherwise the result is the arc tangent of <code>$arg</code>, as defined 
            in the <bibref ref="ieee754-2008"/> specification of the
               <code>atan</code> function applied to 64-bit binary floating point values.
            The result is in the range -<var>π</var>/2
            to +<var>π</var>/2 radians.</p></def></gitem><gitem><label>Notes</label><def><p role="note">The treatment of the <code>underflow</code> exception is defined in <specref ref="op.numeric"/>. </p><p role="note">If <code>$arg</code> is positive or negative zero, the result is <code>$arg</code>.</p><p role="note">If <code>$arg</code> is <code>NaN</code> then the result is <code>NaN</code>.</p><p role="note">In other cases the result is an <code>xs:double</code> value representing an angle
               <var>θ</var> in radians in the range -<var>π</var><code>/2 &lt;=
               </code><var>θ</var><code> &lt;= +</code><var>π</var><code>/2</code>. </p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>math:atan(())</code> returns <code>()</code>.</p><p>The expression <code>math:atan(0)</code> returns <code>0.0e0</code>.</p><p>The expression <code>math:atan(-0.0e0)</code> returns <code>-0.0e0</code>.</p><p>The expression <code>math:atan(1.0e0)</code> returns <code>0.7853981633974483e0</code> (approximately).</p><p>The expression <code>math:atan(-1.0e0)</code> returns <code>-0.7853981633974483e0</code> (approximately).</p><p>The expression <code>math:atan(xs:double('NaN'))</code> returns <code>xs:double('NaN')</code>.</p><p>The expression <code>math:atan(xs:double('INF'))</code> returns <code>1.5707963267948966e0</code> (approximately).</p><p>The expression <code>math:atan(xs:double('-INF'))</code> returns <code>-1.5707963267948966e0</code> (approximately).</p></def></gitem></glist></div3><div3 id="func-math-atan2"><head>math:atan2</head><glist><gitem><label>Summary</label><def><p>Returns the angle in radians subtended at the origin by the point on a plane with
            coordinates (x, y) and the positive x-axis.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="atan2" return-type="xs:double" isOp="no" prefix="math" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="y" type="xs:double"/><arg name="x" type="xs:double"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>The result is the value of <code>atan2(y, x)</code> as defined in the <bibref ref="ieee754-2008"/> specification of the <code>atan2</code> function applied to
            64-bit binary floating point values. The result is in the range -<var>π</var>
            to +<var>π</var> radians.</p></def></gitem><gitem><label>Notes</label><def><p role="note">The treatment of the <code>underflow</code> exception is defined in <specref ref="op.numeric"/>. </p><p role="note">If either argument is <code>NaN</code> then the result is <code>NaN</code>.</p><p role="note">If <code>$y</code> is positive and <code>$x</code> is positive and finite, then (subject
            to rules for overflow, underflow and approximation) the value of <code>atan2($y,
               $x)</code> is <code>atan($y div $x)</code>.</p><p role="note">If <code>$y</code> is positive and <code>$x</code> is negative and finite, then (subject
            to the same caveats) the value of <code>atan2($y, $x)</code> is <var>π</var>
            <code>- atan($y div $x)</code>.</p><p role="note">Some results for special values of the arguments are shown in the examples below.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>math:atan2(+0.0e0, 0.0e0)</code> returns <code>0.0e0</code>.</p><p>The expression <code>math:atan2(-0.0e0, 0.0e0)</code> returns <code>-0.0e0</code>.</p><p>The expression <code>math:atan2(+0.0e0, -0.0e0)</code> returns <code>3.141592653589793e0</code>.</p><p>The expression <code>math:atan2(-0.0e0, -0.0e0)</code> returns <code>-3.141592653589793e0</code>.</p><p>The expression <code>math:atan2(-1, 0.0e0)</code> returns <code>-1.5707963267948966e0</code>.</p><p>The expression <code>math:atan2(+1, 0.0e0)</code> returns <code>1.5707963267948966e0</code>.</p><p>The expression <code>math:atan2(-0.0e0, -1)</code> returns <code>-3.141592653589793e0</code>.</p><p>The expression <code>math:atan2(+0.0e0, -1)</code> returns <code>3.141592653589793e0</code>.</p><p>The expression <code>math:atan2(-0.0e0, +1)</code> returns <code>-0.0e0</code>.</p><p>The expression <code>math:atan2(+0.0e0, +1)</code> returns <code>+0.0e0</code>.</p></def></gitem></glist></div3></div2><div2 id="random-numbers" diff="add" at="B"><head>Random Numbers</head><table class="index"><thead><tr><th rowspan="1" colspan="1">Function</th><th rowspan="1" colspan="1">Meaning</th></tr></thead><tbody><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:random-number-generator</code></td><td rowspan="1" colspan="1">Returns a random number generator, which can be used to generate sequences of random numbers.</td></tr></tbody></table><div3 id="func-random-number-generator"><head>fn:random-number-generator</head><glist><gitem><label>Summary</label><def><p>Returns a random number generator, which can be used to generate sequences of random numbers.</p></def></gitem><gitem><label>Signatures</label><def><example role="signature"><proto name="random-number-generator" return-type="map(xs:string, item())" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"/></example><example role="signature"><proto name="random-number-generator" return-type="map(xs:string, item())" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="seed" type="xs:anyAtomicType?"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>, <termref def="dt-focus-independent">focus-independent</termref>,  and <termref def="dt-higher-order">higher-order</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>The function returns a random number generator. A random number generator is represented as a map containing three entries. 
            The keys of each entry are strings:</p><olist><item><p>The entry with key <code>"number"</code> holds a random number; it is an <code>xs:double</code> greater than or equal
               to zero (0.0e0), and less than one (1.0e0).</p></item><item><p>The entry with key <code>"next"</code> is a zero-arity function that can be called to return another random number
            generator.</p><p diff="add" at="D">The properties of this function are as follows:</p><ulist diff="add" at="D"><item><p>name: absent</p></item><item><p>parameter names: ()</p></item><item><p>signature: <code>() =&gt; map(xs:string, item())</code></p></item><item><p>non-local variable bindings: none</p></item><item><p>implementation: implementation-dependent</p></item></ulist></item><item><p>The entry with key <code>"permute"</code> is a function with arity 1 (one), which takes an arbitrary sequence
            as its argument, and returns a random permutation of that sequence.</p><p diff="add" at="D">The properties of this function are as follows:</p><ulist diff="add" at="D"><item><p>name: absent</p></item><item><p>parameter names: ("arg")</p></item><item><p>signature: <code>(item()*) =&gt; item()*</code></p></item><item><p>non-local variable bindings: none</p></item><item><p>implementation: implementation-dependent</p></item></ulist></item></olist><p>Calling the <code>fn:random-number-generator</code> function with no arguments is equivalent to calling the single-argument
         form of the function with an implementation-dependent seed.</p><p diff="add" at="E">Calling the <code>fn:random-number-generator</code> function with an empty sequence as the value of <code>$seed</code> 
            is equivalent to calling the single-argument form of the function with an implementation-dependent seed.</p><p>If a <code>$seed</code> is supplied, it may be an atomic value of any type.</p><p>Both forms of the function are <termref def="dt-deterministic"/>: calling the function twice with the same arguments, within a single
         <termref def="execution-scope">execution scope</termref>, produces the same results.</p><p>The value of the <code>number</code> entry <rfc2119>should</rfc2119> be such that all eligible <code>xs:double</code>
         values are equally likely to be chosen.</p><p>The function returned in the <code>permute</code> entry <rfc2119>should</rfc2119> be such that all permutations 
            of the supplied sequence are equally likely to be chosen.</p><p>The map returned by the <code>fn:random-number-generator</code> function <rfc2119>may</rfc2119> contain additional entries beyond
            those specified here, but it <rfc2119>must</rfc2119> match the type <code>map(xs:string, item())</code>. The meaning of any additional entries
         is <termref def="implementation-defined">implementation-defined</termref>. To avoid conflict with any future version of this specification, the keys of any
         such entries <rfc2119>should</rfc2119> start with an underscore character.</p></def></gitem><gitem><label>Notes</label><def><p role="note">It is not meaningful to ask whether the functions returned in the <code>next</code> and <code>permute</code>
            functions resulting from two separate calls with the same seed are "the same function", but the functions must be equivalent in the sense
            that calling them produces the same sequence of random numbers.</p><p role="note">The repeatability of the results of function calls in different execution scopes is outside the scope of this
            specification. It is <rfc2119>recommended</rfc2119> that when the same seed is provided explicitly, the same random number sequence
            should be delivered even in different execution scopes; while if no seed is provided, the processor should choose a seed
            that is likely to be different from one execution scope to another. (The same effect can be achieved explicitly by using
         <code>fn:current-dateTime()</code> as a seed.)</p><p role="note">The specification does not place strong conformance requirements on the actual randomness of the result; this is left to 
            the implementation. It is desirable, for example, when generating a sequence
         of random numbers that the sequence should not get into a repeating loop; but the specification does not attempt to dictate this.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The following example returns a random permutation of the integers in the range 1 to 100: 
               <code>fn:random-number-generator()?permute(1 to 100)</code>
            </p><p>The following example returns a 10% sample of the items in an input sequence <code>$seq</code>, chosen at random: 
                  <code>fn:random-number-generator()?permute($seq)[position() = 1 to (count($seq) idiv 10)]</code>
            </p><p>The following code defines a function that can be called to produce a random sequence of <code>xs:double</code>
            values in the range zero to one, of specified length:</p><eg xml:space="preserve">
declare %public function r:random-sequence($length as xs:integer) as xs:double* {
  r:random-sequence($length, fn:random-number-generator())
};

declare %private function r:random-sequence($length as xs:integer, 
                                            $G as map(xs:string, item())) {
  if ($length eq 0)
  then ()
  else ($G?number, r:random-sequence($length - 1, $G?next()))
};

r:random-sequence(200);
            </eg></def></gitem></glist></div3></div2></div1><div1 id="string-functions"><head>Functions on strings</head><p>This section specifies functions and operators on the <bibref ref="xmlschema-2"/>
                <code>xs:string</code> datatype and the datatypes derived from it.</p><div2 id="string-types"><head>String types</head><p>The operators described in this section are defined on the following types. Each
                    type whose name is indented is derived from the type whose name appears nearest
                    above with one less level of indentation.</p><table border="0" summary="Type summary" role="hierarchy"><tbody><tr><td rowspan="1" colspan="1">xs:string</td></tr><tr><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1">xs:normalizedString</td></tr><tr><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1">xs:token</td></tr><tr><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1">xs:language</td></tr><tr><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1">xs:NMTOKEN</td></tr><tr><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1">xs:Name</td></tr><tr><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1">xs:NCName</td></tr><tr><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1">xs:ID</td></tr><tr><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1">xs:IDREF</td></tr><tr><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1">xs:ENTITY</td></tr></tbody></table><p>They also apply to user-defined types derived by restriction from the above types. </p></div2><div2 id="func-assemble-disassemble-string"><head>Functions to assemble and disassemble strings</head><table class="index"><thead><tr><th rowspan="1" colspan="1">Function</th><th rowspan="1" colspan="1">Meaning</th></tr></thead><tbody><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:codepoints-to-string</code></td><td rowspan="1" colspan="1">Returns an <code>xs:string</code> whose characters have supplied <termref def="codepoint">codepoints</termref>.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:string-to-codepoints</code></td><td rowspan="1" colspan="1">Returns the sequence of <termref def="codepoint">codepoints</termref> that constitute an
               <code>xs:string</code> value. </td></tr></tbody></table><div3 id="func-codepoints-to-string"><head>fn:codepoints-to-string</head><glist><gitem><label>Summary</label><def><p diff="chg" at="C">Returns an <code>xs:string</code> whose characters have supplied <termref def="codepoint">codepoints</termref>.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="codepoints-to-string" return-type="xs:string" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg" type="xs:integer*"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>The function returns the string made up from the <termref def="character">characters</termref> whose Unicode <termref def="codepoint">codepoints</termref> are
            supplied in <code>$arg</code>. This will be the zero-length string if <code>$arg</code>
            is the empty sequence. </p></def></gitem><gitem><label>Error Conditions</label><def><p>A dynamic error is raised <errorref class="CH" code="0001"/> if any of the codepoints in
               <code>$arg</code> is not a permitted XML character.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>fn:codepoints-to-string((66, 65, 67, 72))</code> returns <code>"BACH"</code>.</p><p>The expression <code>fn:codepoints-to-string((2309, 2358, 2378, 2325))</code> returns <code>"अशॊक"</code>.</p><p>The expression <code>fn:codepoints-to-string(())</code> returns <code>""</code>.</p><p>The expression <code>fn:codepoints-to-string(0)</code> raises error <code>FOCH0001</code>.</p></def></gitem></glist></div3><div3 id="func-string-to-codepoints"><head>fn:string-to-codepoints</head><glist><gitem><label>Summary</label><def><p>Returns the sequence of <termref def="codepoint">codepoints</termref> that constitute an
               <code>xs:string</code> value. </p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="string-to-codepoints" return-type="xs:integer*" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg" type="xs:string?"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>The function returns a sequence of integers, each integer being the Unicode <termref def="codepoint">codepoint</termref> of the corresponding <termref def="character">character</termref> in <code>$arg</code>.</p><p>If <code>$arg</code> is a zero-length string or the empty sequence, the function returns
            the empty sequence.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>fn:string-to-codepoints("Thérèse")</code> returns <code>(84, 104, 233, 114, 232, 115, 101)</code>.</p></def></gitem></glist></div3></div2><div2 id="string-compare"><head>Comparison of strings</head><table class="index"><thead><tr><th rowspan="1" colspan="1">Function</th><th rowspan="1" colspan="1">Meaning</th></tr></thead><tbody><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:compare</code></td><td rowspan="1" colspan="1">Returns -1, 0, or 1, depending on whether <code>$comparand1</code> collates before,
            equal to, or after <code>$comparand2</code> according to the rules of a selected
            collation.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:codepoint-equal</code></td><td rowspan="1" colspan="1">Returns true if two strings are equal, considered codepoint-by-codepoint.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:collation-key</code></td><td rowspan="1" colspan="1">Given a string value and a collation, generates an internal value called a collation key, with the property that
            the matching and ordering of collation keys reflects the matching and ordering of strings under the specified collation.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:contains-token</code></td><td rowspan="1" colspan="1">Determines whether or not any of the supplied strings, when tokenized at whitespace boundaries, contains the supplied token,
            under the rules of the supplied collation.</td></tr></tbody></table><div3 id="collations"><head>Collations</head><p> A collation is a specification of the manner in which <termref def="string">strings</termref> are
                        compared and, by extension, ordered. When values whose type is
                        <code>xs:string</code> or a type derived from <code>xs:string</code> are
                        compared (or, equivalently, sorted), the comparisons are inherently
                        performed according to some collation (even if that collation is defined
                        entirely on codepoint values). The <bibref ref="charmod"/> 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. </p><p>Collations can indicate that two different codepoints are, in fact, equal
                        for comparison purposes (e.g., "v" and "w" are considered equivalent in
                        some Swedish collations). Strings can be compared codepoint-by-codepoint or in a
                        linguistically appropriate manner, as defined by the collation. </p><p>Some collations, especially those based on the 
                  Unicode Collation Algorithm (see <bibref ref="UNICODE-TR10"/>) can be "tailored" for various purposes. This
                        document does not discuss such tailoring, nor does it provide a mechanism to
                        perform tailoring. Instead, it assumes that the collation argument to the
                        various functions below is a tailored and named collation.</p><p>The <termref def="dt-codepoint-collation">Unicode codepoint collation</termref> is a collation
                  available in every implementation, which sorts based on codepoint values. For further details
                  see <specref ref="codepoint-collation"/>.</p><p diff="del" at="A">In the ideal case, a collation should treat two strings as equal if the two strings are identical after Unicode normalization.  Thus, the <bibref ref="charmod-normalization"/> recommends that all strings be subjected to early Unicode normalization and some collations will raise runtime errors if they encounter strings that are not properly normalized.  However, 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 interoperability of 
                        operations on XML documents in general, there may be collations that operate
                        on unnormalized strings and other collations that
                        implicitly normalize strings before comparing them. Applications may choose the kind of collation best suited for their needs.  Note that collations based
                        on the Unicode collation algorithm implicitly normalize strings before comparison and produce equivalent results regardless of
                        a string's normalization.</p><p diff="add" at="A">Collations may or may not perform Unicode normalization on strings before comparing them.</p><p>This specification assumes that collations are named and that the collation
                        name may be provided as an argument to string functions. Functions that
                        allow specification of a collation do so with an argument whose type is
                        <code>xs:string</code> but whose lexical form must conform to an
                        <code>xs:anyURI</code>. If the collation is specified using a relative URI reference, 
                  it is resolved relative to the value of the
                     static base URI property from the static context. 
                  This specification also defines the manner in which a
                        default collation is determined if the collation argument is not specified
                        in calls of functions that use a collation but allow it to be omitted. </p><p>This specification does not define whether or not the collation URI is
					dereferenced. The collation URI may be an abstract identifier, or it may
					refer to an actual resource describing the collation. If it refers to a
					resource, this specification does not define the nature of that resource.
					One possible candidate is that the resource is a locale description
					expressed using the Locale Data Markup Language: see <bibref ref="UNICODE-TR35"/>.
					</p><p>Functions such as <code>fn:compare</code> and <code>fn:max</code> that
                        compare <code>xs:string</code> values use a single collation URI to identify
                        all aspects of the collation rules. This means that any parameters such as
                        the strength of the collation must be specified as part of the collation
                        URI. For example, suppose there is a collation 
                            <code>http://www.example.com/collations/French</code>
                         that refers to a French collation that compares on the basis of
                        base characters. Collations that use the same basic rules, but with higher
                        strengths, for example, base characters and accents, or base characters,
                        accents and case, would need to be given different names, say 
                            <code>http://www.example.com/collations/French1</code>
                         and 
                            <code>http://www.example.com/collations/French2</code>. 
                  Note that some specifications use the term collation to refer to
                        an algorithm that can be parameterized, but in this specification, each
                        possible parameterization is considered to be a distinct collation.</p><p>The XQuery/XPath static context includes a provision for a default collation
                        that can be used for string comparisons and ordering operations. See the
                        description of the static context in <xspecref spec="XP31" ref="static_context"/>. 
						If the default collation is not specified by the
                        user or the system, the default collation is the <termref def="dt-codepoint-collation">Unicode codepoint collation</termref>.</p><note><p>XML allows elements to specify the <code>xml:lang</code> attribute to
                     indicate the language associated with the content of such an element.
                     This specification does not use <code>xml:lang</code> to identify the
                     default collation because using
                     <code>xml:lang</code> does not produce desired effects when the two
                     strings to be compared have different <code>xml:lang</code> values or
                     when a string is multilingual. </p></note></div3><div3 id="codepoint-collation"><head>The Unicode Codepoint Collation</head><p><termdef id="dt-codepoint-collation" term="Unicode codepoint collation">The collation URI
                  <code>http://www.w3.org/2005/xpath-functions/collation/codepoint</code> identifies
               a collation which must be recognized by every implementation: it is referred to as
               the <term>Unicode codepoint collation</term> (not to be confused with the Unicode collation algorithm).</termdef></p><p>The Unicode codepoint collation does not perform any normalization on the
               supplied strings.</p><p>The collation is defined as follows. Each of the two strings is
               converted to a sequence of integers using the <code>fn:string-to-codepoints</code>
               function. These two sequences <code>$A</code> and <code>$B</code> are then compared as follows: </p><ulist><item><p>If both sequences are empty, the strings are equal.</p></item><item><p>If one sequence is empty and the other is not, then the string
                     corresponding to the empty sequence is less than the other string.</p></item><item><p>If the first integer in <code>$A</code> is less than the first integer in <code>$B</code>, then
                     the string corresponding to <code>$A</code> is less than the string corresponding to
                     <code>$B</code>.
                  </p></item><item><p>If the first integer in <code>$A</code> is greater than the first integer in <code>$B</code>, then
                     the string corresponding to <code>$A</code> is greater than the string corresponding to
                     <code>$B</code>.</p></item><item><p>Otherwise (the first pair of integers are equal), the result is obtained
                    by applying the same rules recursively to <code>fn:tail($A)</code> and
                    <code>fn:tail($B)</code></p></item></ulist><note><p>While the Unicode codepoint collation does not produce results suitable for quality publishing of
               printed indexes or directories, it is adequate for many purposes where a restricted alphabet
               is used, such as sorting of vehicle registrations.</p></note></div3><div3 id="uca-collations" diff="add" at="A"><head>The Unicode Collation Algorithm</head><p>This specification defines a family of collation URIs representing tailorings of the Unicode Collation
                  Algorithm (UCA) as defined in <bibref ref="UNICODE-TR10"/>. The parameters used for tailoring the UCA
                  are based on the parameters defined in the Locale Data Markup Language (LDML), defined in <bibref ref="UNICODE-TR35"/>.</p><p>This family of URIs use the scheme and path <code>http://www.w3.org/2013/collation/UCA</code>
                  followed by an optional query part. The query part, if present, consists of a question mark followed
                  by a sequence of zero or more semicolon-separated parameters. Each parameter is a keyword-value pair, the
                  keyword and value being separated by an equals sign.</p><p>All implementations must recognize URIs in this family in the <code>collation</code> argument of functions that
                  take a collation argument.</p><p>If the <code>fallback</code> parameter is
                  present with the value <code>no</code>, then the implementation <rfc2119>must</rfc2119> either use a collation that conforms with
                  the rules in the Unicode specifications for the requested tailoring, or fail with a static or dynamic error indicating that it
                  does not provide the collation (the error code should be the same as if the collation URI were not recognized). 
                  If the <code>fallback</code> parameter
                  is omitted or takes the value <code>yes</code>, and if the collation URI is well-formed according to the rules in this section,
                  then the implementation <rfc2119>must</rfc2119> accept the collation URI, and <rfc2119>should</rfc2119> use the available
                  collation that most closely reflects the user's intentions. For example, if the collation URI requested is
                  <code>http://www.w3.org/2013/collation/UCA?lang=se;fallback=yes</code> and the implementation does not include a fully
                  conformant version of the UCA tailored for Swedish, then it <rfc2119>may</rfc2119> choose to use a Swedish collation that is known to differ
                  from the UCA definition, or one whose conformance has not been established. It might even, as a last resort, fall back to using
                  codepoint collation.</p><p>If two query parameters use the same keyword then the last one wins. If a query parameter uses a keyword or value which is not
                  defined in this specification then the meaning is <termref def="implementation-defined"/>. If the implementation recognizes
                  the meaning of the keyword and value then it <rfc2119>should</rfc2119> interpret it accordingly; if it does not recognize
                  the keyword or value then if the <code>fallback</code> parameter is present with the value <code>no</code> it should reject
                  the collation as unsupported, otherwise it should ignore the unrecognized parameter.</p><p>The following query parameters are defined. If any parameter is absent, the default is <termref def="implementation-defined"/>
                  except where otherwise stated.
                  The meaning given for each parameter is non-normative; the normative specification is found in <bibref ref="UNICODE-TR35"/>.</p><table role="longlastcol data"><thead><tr><th rowspan="1" colspan="1">Keyword</th><th rowspan="1" colspan="1">Values</th><th rowspan="1" colspan="1">Meaning</th></tr></thead><tbody><tr><td rowspan="1" colspan="1">fallback</td><td rowspan="1" colspan="1">yes | no (default yes)</td><td rowspan="1" colspan="1">Determines whether the processor uses a fallback collation if a conformant collation is not available.</td></tr><tr><td rowspan="1" colspan="1">lang</td><td rowspan="1" colspan="1">language code: <phrase diff="chg" at="D">a string in the lexical space of <code>xs:language</code></phrase>.</td><td rowspan="1" colspan="1">The language whose collation conventions are to be used.</td></tr><tr><td rowspan="1" colspan="1">version</td><td rowspan="1" colspan="1">string</td><td rowspan="1" colspan="1">The version number of the UCA to be used.</td></tr><tr><td rowspan="1" colspan="1">strength (default tertiary)</td><td rowspan="1" colspan="1">primary | secondary | tertiary | quaternary | identical, or 
                        1|2|3|4|5 as synonyms</td><td rowspan="1" colspan="1">The collation strength as defined in UCA. Primary 
                           strength takes only the base form of the character into account (so A=a=Ä=ä); secondary strength ignores case but considers accents
                           and diacritics as significant (so A=a and Ä=ä but ä≠a); tertiary considers case as significant (A≠a≠Ä≠ä); quaternary considers 
                           spaces and punctuation that would otherwise be ignored (for example <code>data-base</code>=<code>database</code>).</td></tr><tr diff="add" at="E"><td rowspan="1" colspan="1">maxVariable</td><td rowspan="1" colspan="1">space | punct | symbol | currency (default punct)</td><td rowspan="1" colspan="1">
                        Indicates that all characters in the specified group and earlier groups are treated as "noise" characters 
                        to be handled as defined by the <code>alternate</code> parameter. For example, <code>maxVariable=punct</code> indicates 
                        that characters classified as whitespace or punctuation get this treatment.</td></tr><tr diff="chg" at="E"><td rowspan="1" colspan="1">alternate</td><td rowspan="1" colspan="1">non-ignorable | shifted | blanked (default non-ignorable)</td><td rowspan="1" colspan="1">Controls the handling of characters such as spaces and hyphens;
                     specifically, the "noise" characters in the groups selected by the <code>maxVariable</code> parameter. The value <code>non-ignorable</code>
                     indicates that such characters are treated as distinct at the primary level (so <code>data base</code> sorts before <code>datatype</code>);
                     <code>shifted</code> indicates that they are used to differentiate two strings only at the <code>quaternary</code> level,
                     and <code>blanked</code> indicates that they are taken into account only at the <code>identical</code> level.</td></tr><tr><td rowspan="1" colspan="1">backwards</td><td rowspan="1" colspan="1">yes | no (default no)</td><td rowspan="1" colspan="1">The value <code>backwards=yes</code> indicates that the last accent in the 
                           <phrase diff="chg" at="E">string</phrase> is the most significant.</td></tr><tr><td rowspan="1" colspan="1">normalization</td><td rowspan="1" colspan="1">yes | no (default no)</td><td rowspan="1" colspan="1">Indicates whether <phrase diff="chg" at="E">strings</phrase> 
                           are converted to normalization form D.</td></tr><tr><td rowspan="1" colspan="1">caseLevel</td><td rowspan="1" colspan="1">yes | no (default no)</td><td rowspan="1" colspan="1">When used with primary strength, setting <code>caseLevel=yes</code> has the effect of ignoring accents
                        while taking account of case.</td></tr><tr><td rowspan="1" colspan="1">caseFirst</td><td rowspan="1" colspan="1">upper | lower</td><td rowspan="1" colspan="1">Indicates whether upper-case precedes lower-case or vice versa.</td></tr><tr diff="del" at="C"><td rowspan="1" colspan="1">hiraganaQuaternary</td><td rowspan="1" colspan="1">yes | no</td><td rowspan="1" colspan="1">Controls special treatment of Hiragana codepoints when strength is quaternary or greater.</td></tr><tr><td rowspan="1" colspan="1">numeric</td><td rowspan="1" colspan="1">yes | no (default no)</td><td rowspan="1" colspan="1">When <code>numeric=yes</code> is specified, a sequence of consecutive digits is interpreted as a number,
                        for example <code>chap2</code> sorts before <code>chap12</code>.</td></tr><tr><td rowspan="1" colspan="1">reorder</td><td rowspan="1" colspan="1">a comma-separated sequence of reorder codes, where a reorder code is one of <code>space</code>, <code>punct</code>,
                        <code>symbol</code>, <code>currency</code>, <code>digit</code>, or a four-letter script code defined in <bibref ref="ISO15924_register"/>, the register
                        of scripts maintained by the Unicode Consortium in its capacity as registration authority for <bibref ref="ISO15924"/>.</td><td rowspan="1" colspan="1">Determines the relative ordering of text in different scripts; for example the value <code>digit,Grek,Latn</code> indicates
                           that digits precede Greek letters, which precede Latin letters.</td></tr></tbody></table><note><p>This list excludes parameters that are inconvenient to express in a URI, or that are applicable only to substring matching.</p></note></div3><div3 id="html-ascii-case-insensitive-collation" diff="add" at="B"><head>The HTML ASCII Case-Insensitive Collation</head><p>The collation URI <code>http://www.w3.org/2005/xpath-functions/collation/html-ascii-case-insensitive</code> must be recognized
                  by every implementation. It is used
               to refer to the HTML ASCII case-insensitive collation as defined in <bibref ref="html5"/> (section 2.5, <emph>Case sensitivity and
               string comparison</emph>). It is used, for example, when matching HTML <code>class</code> attribute values.</p><note><p>The definition of the collation is paraphrased here for convenience:</p><p>Comparing two strings in an ASCII case-insensitive manner means comparing them exactly, 
                     codepoint for codepoint, except that the characters in the range x41 to x5A (A-Z) 
                     and the corresponding characters in the range x61 to x7A (a-z) are considered to also match.</p></note><p>HTML5 defines the semantics of equality matching using this collation; it does not define rules for ordering. If the collation
               is used for ordering, the results are <termref def="implementation-defined"/>. The collation supports collation units and can therefore
               be used with functions such as <code>fn:contains</code>; each Unicode codepoint is a single collation unit.</p></div3><div3 id="choosing-a-collation"><head>Choosing a collation</head><p>Many functions have two signatures, where one signature includes a <code>$collation</code>
			   argument and the other omits this argument.</p><p>The collation to use for these functions is determined by the following rules:</p><olist><item><p>If the function specifies an explicit collation, CollationA (e.g., if
                                the optional collation argument is specified in a call of the
                                <code>fn:compare</code> function), then:</p><ulist><item><p>If CollationA is supported by the implementation, then
                                        CollationA is used. </p></item><item><p>Otherwise, a dynamic error is raised <errorref class="CH" code="0002"/>. </p></item></ulist></item><item><p>If no collation is explicitly specified for the function and the
                                default collation in the XQuery/XPath static context is CollationB, then:</p><ulist><item><p>If CollationB is supported by the implementation, then
                                        CollationB is used. </p></item><item><p>Otherwise, a dynamic error is raised <errorref class="CH" code="0002"/>. </p></item></ulist></item></olist><note><p>Because the set of collations that are supported is <termref def="implementation-defined">implementation-defined</termref>,
			   an implementation has the option to support all collation URIs, in which case it will never raise this error.</p></note><p diff="add" at="B">If the value of the collation argument is a relative URI reference, it is resolved against the base-URI from the
			      static context. If it is a relative URI reference and cannot be resolved, perhaps because the base-URI property in the static context
			      is absent, a dynamic error is raised <errorref class="CH" code="0002"/>.</p><note diff="add" at="D"><p>There is no explicit requirement that the string used as a collation URI be a valid URI.
			   Implementations will in many cases reject such strings on the grounds that do not identify a supported collation; they
			   may also cause an error if they cannot be resolved against the static base URI.</p></note></div3><div3 id="func-compare"><head>fn:compare</head><glist><gitem><label>Summary</label><def><p>Returns -1, 0, or 1, depending on whether <code>$comparand1</code> collates before,
            equal to, or after <code>$comparand2</code> according to the rules of a selected
            collation.</p></def></gitem><gitem><label>Signatures</label><def><example role="signature"><proto name="compare" return-type="xs:integer?" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="comparand1" type="xs:string?"/><arg name="comparand2" type="xs:string?"/></proto></example><example role="signature"><proto name="compare" return-type="xs:integer?" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="comparand1" type="xs:string?"/><arg name="comparand2" type="xs:string?"/><arg name="collation" type="xs:string"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>The two-argument form of this function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-dependent">context-dependent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>.  It depends on 
		collations.
	</p><p>The three-argument form of this function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-dependent">context-dependent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>.  It depends on 
		collations, and static base URI.
	</p></def></gitem><gitem><label>Rules</label><def><p>Returns -1, 0, or 1, depending on whether the value of the <code>$comparand1</code> is
            respectively less than, equal to, or greater than the value of <code>$comparand2</code>,
            according to the rules of the collation that is used. </p><p>The collation used by this function is determined according to the rules in <specref ref="choosing-a-collation"/>. </p><p>If either <code>$comparand1</code> or <code>$comparand2</code> is the empty sequence,
            the function returns the empty sequence.</p><p>This function, called with the first signature, defines the semantics of the "eq", "ne",
            "gt", "lt", "le" and "ge" operators on <code>xs:string</code> values.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>fn:compare('abc', 'abc')</code> returns <code>0</code>.</p><p>The expression <code>fn:compare('Strasse', 'Straße')</code> returns <code>0</code>. <emph>(Assuming the default collation includes provisions that equate
                     <quote>ss</quote> and the (German) character <quote>ß</quote>
                     (<quote>sharp-s</quote>). Otherwise, the returned value depends on the
                  semantics of the default collation.)</emph></p><p>The expression <code>fn:compare('Strasse', 'Straße',
                  'http://www.w3.org/2013/collation/UCA?lang=de;strength=primary')</code> returns <code>0</code>. <emph>(The specified collation equates
                     <quote>ss</quote> and the (German) character <quote>ß</quote>
                     (<quote>sharp-s</quote>).)</emph></p><p>The expression <code>fn:compare('Strassen', 'Straße')</code> returns <code>1</code>. <emph>(Assuming the default collation includes provisions that treat
                  differences between <quote>ss</quote> and the (German) character <quote>ß</quote>
                     (<quote>sharp-s</quote>) with less strength than the differences between the
                  base characters, such as the final <quote>n</quote>. ).</emph></p></def></gitem></glist></div3><div3 id="func-codepoint-equal"><head>fn:codepoint-equal</head><glist><gitem><label>Summary</label><def><p>Returns true if two strings are equal, considered codepoint-by-codepoint.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="codepoint-equal" return-type="xs:boolean?" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="comparand1" type="xs:string?"/><arg name="comparand2" type="xs:string?"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>If either argument is the empty sequence, the function returns the empty sequence. </p><p>Otherwise, the function returns <code>true</code> or <code>false</code> depending on
            whether the value of <code>$comparand1</code> is equal to the value of
               <code>$comparand2</code>, according to the Unicode codepoint collation
               (<code>http://www.w3.org/2005/xpath-functions/collation/codepoint</code>).</p></def></gitem><gitem><label>Notes</label><def><p role="note">This function allows <code>xs:anyURI</code> values to be compared without having to
            specify the Unicode codepoint collation.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>fn:codepoint-equal("abcd", "abcd")</code> returns <code>true()</code>.</p><p>The expression <code>fn:codepoint-equal("abcd", "abcd ")</code> returns <code>false()</code>.</p><p>The expression <code>fn:codepoint-equal("", "")</code> returns <code>true()</code>.</p><p>The expression <code>fn:codepoint-equal("", ())</code> returns <code>()</code>.</p><p>The expression <code>fn:codepoint-equal((), ())</code> returns <code>()</code>.</p></def></gitem></glist></div3><div3 id="func-collation-key" diff="add" at="A"><head>fn:collation-key</head><glist><gitem><label>Summary</label><def><p diff="chg" at="B-bug25446">Given a string value and a collation, generates an internal value called a collation key, with the property that
            the matching and ordering of collation keys reflects the matching and ordering of strings under the specified collation.</p></def></gitem><gitem><label>Signatures</label><def><example role="signature"><proto name="collation-key" return-type="xs:base64Binary" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="key" type="xs:string"/></proto></example><example role="signature"><proto name="collation-key" return-type="xs:base64Binary" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="key" type="xs:string"/><arg name="collation" type="xs:string"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-dependent">context-dependent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>.  It depends on 
		collations.
	</p></def></gitem><gitem><label>Rules</label><def><p>Calling the one-argument version of this function is equivalent to calling the
            two-argument version supplying the default collation as the second argument.</p><p>The function returns an <phrase diff="add" at="B-bug25446"><termref def="implementation-dependent">implementation-dependent</termref></phrase> 
            value with the property that,
            for any two strings <code>$K1</code> and <code>$K2</code>:</p><ulist><item><p><code>collation-key($K1, $C) eq collation-key($K2, $C)</code> if and only if
                  <code>compare($K1, $K2, $C) eq 0</code></p></item><item diff="add" at="B-bug25446"><p><code>collation-key($K1, $C) lt collation-key($K2, $C)</code> if and only if
                  <code>compare($K1, $K2, $C) lt 0</code></p></item></ulist><p diff="add" at="E">The collation used by this function is determined according to the rules in <specref ref="choosing-a-collation"/>. Collation keys are defined as <code>xs:base64Binary</code> values
            to ensure unambiguous and context-free comparison semantics.</p><p>An implementation is free to generate a collation key in any convenient way provided
            that it always generates the same collation key for two strings that are equal under the
            collation, and different collation keys for strings that are not equal. This holds only
            within a single <termref ref="execution-scope">execution scope</termref>;
            an implementation is under no obligation to generate the same collation keys during a
            subsequent unrelated query or transformation.</p><p>It is possible to define collations that do not have the ability to generate collation
            keys. Supplying such a collation will cause the function to fail. The ability to
            generate collation keys is an <termref def="implementation-defined">implementation-defined</termref> property of the
            collation.</p></def></gitem><gitem><label>Error Conditions</label><def><p>An error is raised <errorref class="CH" code="0004"/> if the specified
            collation does not support the generation of collation keys. </p></def></gitem><gitem><label>Notes</label><def><p role="note">The function is provided primarily for use with maps. If a map is required where
            codepoint equality is inappropriate for comparing keys, then a common technique is to
            normalize the key so that equality matching becomes feasible. There are many ways
            keys can be normalized, for example by use of functions such as
               <code>fn:upper-case</code>, <code>fn:lower-case</code>,
               <code>fn:normalize-space</code>, or <code>fn:normalize-unicode</code>, but this
            function provides a way of normalizing them according to the rules of a specified
            collation. For example, if the collation ignores accents, then the function will
            generate the same collation key for two input strings that differ only in their use of
            accents.</p><p role="note">The result of the function is defined to be an <code>xs:base64Binary</code> value. Binary values
         are chosen because they have unambiguous and context-free comparison semantics, because the value space
         is unbounded, and because the ordering rules are such that between any two values in the ordered value space, an
         arbitrary number of further values can be interpolated. The choice between <code>xs:base64Binary</code>
            and <code>xs:hexBinary</code> is arbitrary; the only operation that behaves differently between the two binary
            data types is conversion to/from a string, and this operation is not one that is normally required for
            effective use of collation keys.
         </p><p role="note">For collations based on the Unicode Collation Algorithm, an algorithm for computing
            collation keys is provided in <bibref ref="UNICODE-TR10"/>. Implementations are
               <rfc2119>not required</rfc2119> to use this algorithm.</p><p role="note">This specification does not mandate that collation keys should retain ordering. This is
            partly because the primary use case is for maps, where only equality comparisons are
            required, and partly to allow the use of binary data types (which are currently
            unordered types) for the result. The specification may be revised in a future release to
            specify that ordering is preserved.</p><p role="note">The fact that collation keys are ordered can be exploited in XQuery, whose <code>order by</code>
         clause does not allow the collation to be selected dynamically. This restriction can be circumvented
         by rewriting the clause <code>order by $e/@key collation "URI"</code> as <code>order by fn:collation-key($e/@key, $collation)</code>,
         where <code>$collation</code> allows the collation to be chosen dynamically.</p><p role="note">Note that <code>xs:base64Binary</code> becomes an ordered type
         in XPath 3.1, making binary collation keys possible.</p></def></gitem><gitem><label>Examples</label><def role="example"><eg xml:space="preserve">let $C := 'http://www.w3.org/2013/collation/UCA?strength=primary'</eg><p>The expression <code>map:merge((map{collation-key("A", $C):1}, map{collation-key("a",
                  $C):2}), map{"duplicates":"use-last"})(collation-key("A", $C))</code> returns <code>2</code>. <emph>(Given that the keys of the two entries are equal under the rules of
                  the chosen collation, only one of the entries can appear in the result; the one
                  that is chosen is the one from the last map in the input sequence.)</emph></p><p>The expression <code>let $M := map{collation-key("A", $C):1, collation-key("B", $C):2}
                  return $M(collation-key("a", $C))</code> returns <code>1</code>. <emph>(The strings "A" and "a" have the same collation key under this
                  collation.)</emph></p><p>As the above examples illustrate, it is important that when the
                  <code>collation-key</code> function is used to add entries to a map, then it must
               also be used when retrieving entries from the map. This process can be made less
               error-prone by encapsulating the map within a function: <code>function($k)
                  {$M(collation-key($k, $collation)}</code>.</p></def></gitem></glist></div3><div3 id="func-contains-token" diff="add" at="B"><head>fn:contains-token</head><glist><gitem><label>Summary</label><def><p>Determines whether or not any of the supplied strings, when tokenized at whitespace boundaries, contains the supplied token,
            under the rules of the supplied collation.</p></def></gitem><gitem><label>Signatures</label><def><example role="signature"><proto name="contains-token" return-type="xs:boolean" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="input" type="xs:string*"/><arg name="token" type="xs:string"/></proto></example><example role="signature"><proto name="contains-token" return-type="xs:boolean" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="input" type="xs:string*"/><arg name="token" type="xs:string"/><arg name="collation" type="xs:string"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>The two-argument form of this function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-dependent">context-dependent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>.  It depends on 
		collations.
	</p><p>The three-argument form of this function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-dependent">context-dependent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>.  It depends on 
		collations, and static base URI.
	</p></def></gitem><gitem><label>Rules</label><def><p>If <code>$input</code> is the empty sequence, the function returns <code>false</code>.</p><p>Leading and trailing whitespace is trimmed from the supplied value of <code>$token</code>. If the trimmed value of <code>$token</code>
            is a zero-length string, the function returns <code>false</code>.</p><p>The collation used by this function is determined according to the rules in <specref ref="choosing-a-collation"/>.</p><p>The function returns true if and only if there is string in <code>$input</code> which, 
            after tokenizing at whitespace boundaries, contains a token
         that is equal to the trimmed value of <code>$token</code> under
         the rules of the selected collation.</p><p>That is, the function returns the value of the expression:</p><eg xml:space="preserve">some $t in $input!fn:tokenize(.) satisfies 
                 compare($t, fn:replace($token, '^\s*|\s*$', ''), $collation) eq 0)</eg></def></gitem><gitem><label>Notes</label><def><p role="note">Interior whitespace within <code>$token</code> will cause the function to return <code>false</code>,
         unless such whitespace is ignored by the selected collation.</p><p role="note">This function can be used for processing space-separated attribute values
            (for example, the XHTML and DITA class attribute),
            where one often needs to test for the presence
            of a single token in a space-separated list. The function is designed to work
            both when the attribute has been validated against an XSD list type, and when it
            appears as a single untyped string. It differs from the
            HTML 5 definition in that HTML 5 recognizes form feed (x0C) as a separator.
            To reproduce the HTML token matching behavior, the HTML ASCII case-insensitive collation
            should be used: see <specref ref="html-ascii-case-insensitive-collation"/>.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>fn:contains-token("red green blue ", "red")</code> returns <code>true()</code>.</p><p>The expression <code>fn:contains-token(("red", "green", "blue"), " red ")</code> returns <code>true()</code>.</p><p>The expression <code>fn:contains-token("red, green, blue", "red")</code> returns <code>false()</code>.</p><p>The expression <code>fn:contains-token("red green blue", "RED", "http://www.w3.org/2005/xpath-functions/collation/html-ascii-case-insensitive")</code> returns <code>true()</code>.</p></def></gitem></glist></div3></div2><div2 id="string-value-functions"><head>Functions on string values</head><p>The following functions are defined on values of type <code>xs:string</code> and
                    types derived from it.</p><table class="index"><thead><tr><th rowspan="1" colspan="1">Function</th><th rowspan="1" colspan="1">Meaning</th></tr></thead><tbody><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:concat</code></td><td rowspan="1" colspan="1">Returns the concatenation of the string values of the arguments.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:string-join</code></td><td rowspan="1" colspan="1">Returns a string created by concatenating the items in a sequence, with a defined
            separator between adjacent items.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:substring</code></td><td rowspan="1" colspan="1">Returns the portion of the value of <code>$sourceString</code> beginning at the position
            indicated by the value of <code>$start</code> and continuing for the number of <termref def="character">characters</termref> indicated by the value of
            <code>$length</code>.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:string-length</code></td><td rowspan="1" colspan="1">Returns the number of <termref def="character">characters</termref> in a string.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:normalize-space</code></td><td rowspan="1" colspan="1">Returns the value of <code>$arg</code> with leading and trailing whitespace removed, and
            sequences of internal whitespace reduced to a single space character.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:normalize-unicode</code></td><td rowspan="1" colspan="1">Returns the value of <code>$arg</code> after applying Unicode normalization.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:upper-case</code></td><td rowspan="1" colspan="1">Converts a string to upper case.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:lower-case</code></td><td rowspan="1" colspan="1">Converts a string to lower case.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:translate</code></td><td rowspan="1" colspan="1">Returns the value of <code>$arg</code> modified by replacing or removing individual
            characters. </td></tr></tbody></table><notes><p>When the above operators and functions are applied to datatypes derived from
                        <code>xs:string</code>, they are guaranteed to return values that are instances of
                        <code>xs:string</code>, but the value might or might not be an instance of the
                        particular subtype of <code>xs:string</code> to which they were applied. </p><p>The strings returned by <code>fn:concat</code> and <code>fn:string-join</code> are not guaranteed to be normalized.  
			   But see note in <code>fn:concat</code>.
                </p></notes><div3 id="func-concat"><head>fn:concat</head><glist><gitem><label>Summary</label><def><p>Returns the concatenation of the string values of the arguments.</p></def></gitem><gitem><label>Operator Mapping</label><def><p> The two-argument form of
         this function defines the semantics of the "||" operator.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="concat" return-type="xs:string" isOp="yes" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg1" type="xs:anyAtomicType?"/><arg name="arg2" type="xs:anyAtomicType?"/><arg name="..." type="xs:anyAtomicType?"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>This function accepts two or more <code>xs:anyAtomicType</code> arguments and casts each
            one to <code>xs:string</code>. The function returns the <code>xs:string</code> that is
            the concatenation of the values of its arguments after conversion. If any argument is
            the empty sequence, that argument is treated as the zero-length string.</p><p>The <code>fn:concat</code> function is specified to allow two or more arguments, which
            are concatenated together. This is the only function specified in this document that
            allows a variable number of arguments. This capability is retained for compatibility
            with <bibref ref="xpath"/>. </p></def></gitem><gitem><label>Notes</label><def><p role="note">As mentioned in <specref ref="string-types"/> Unicode normalization is not automatically
            applied to the result of <code>fn:concat</code>. If a normalized result is required,
               <code>fn:normalize-unicode</code> can be applied to the <code>xs:string</code>
            returned by <code>fn:concat</code>. The following XQuery:</p><eg role="note" xml:space="preserve">
let $v1 := "I plan to go to Mu"
let $v2 := "?nchen in September"
return concat($v1, $v2)</eg><p role="note">where the "?" represents either the actual Unicode character COMBINING DIARESIS (Unicode
            codepoint U+0308) or "&amp;#x0308;", will return:</p><p role="note">"I plan to go to Mu?nchen in September"</p><p role="note">where the "?" represents either the actual Unicode character COMBINING DIARESIS (Unicode
            codepoint U+0308) or "&amp;#x0308;". It is worth noting that the returned value is not
            normalized in NFC; however, it is normalized in NFD.</p><p role="note"> However, the following XQuery:</p><eg role="note" xml:space="preserve">
let $v1 := "I plan to go to Mu"
let $v2 := "?nchen in September"
return normalize-unicode(concat($v1, $v2))</eg><p role="note">where the "?" represents either the actual Unicode character COMBINING DIARESIS (Unicode
            codepoint U+0308) or "&amp;#x0308;", will return:</p><p role="note"> "I plan to go to München in September"</p><p role="note">This returned result is normalized in NFC.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>fn:concat('un', 'grateful')</code> returns <code>"ungrateful"</code>.</p><p>The expression <code>fn:concat('Thy ', (), 'old ', "groans", "", ' ring',
                  ' yet', ' in', ' my', ' ancient',' ears.')</code> returns <code>"Thy old groans ring yet in my ancient ears."</code>.</p><p>The expression <code>fn:concat('Ciao!',())</code> returns <code>"Ciao!"</code>.</p><p>The expression <code>fn:concat('Ingratitude, ', 'thou ', 'marble-hearted', ' fiend!')</code> returns <code>"Ingratitude, thou marble-hearted fiend!"</code>.</p><p>The expression <code>fn:concat(01, 02, 03, 04, true())</code> returns <code>"1234true"</code>.</p><p>The expression <code>10 || '/' || 6</code> returns <code>"10/6"</code>.</p></def></gitem></glist></div3><div3 id="func-string-join"><head>fn:string-join</head><glist><gitem><label>Summary</label><def><p>Returns a string created by concatenating the items in a sequence, with a defined
            separator between adjacent items.</p></def></gitem><gitem><label>Signatures</label><def><example role="signature"><proto name="string-join" return-type="xs:string" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg1" type="xs:anyAtomicType*"/></proto></example><example role="signature"><proto name="string-join" return-type="xs:string" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg1" type="xs:anyAtomicType*"/><arg name="arg2" type="xs:string"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>The effect of calling the single-argument version of this function is the same as
            calling the two-argument version with <code>$arg2</code> set to a zero-length
            string.</p><p>The function returns an <code>xs:string</code> created by <phrase diff="chg" at="D">casting each item 
            in the sequence <code>$arg1</code> to an <code>xs:string</code>, 
            and then concatenating the result strings in order,</phrase> 
            using the value of <code>$arg2</code> as a
            separator between adjacent strings. If the value of <code>$arg2</code> is the zero-length
            string, then the members of <code>$arg1</code> are concatenated without a separator.</p></def></gitem><gitem><label>Notes</label><def><p role="note">If the value of <code>$arg1</code> is the empty sequence, the function returns the
            zero-length string.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>fn:string-join(1 to 9)</code> returns <code>"123456789"</code>.</p><p>The expression <code>fn:string-join(('Now', 'is', 'the', 'time', '...'),
                  ' ')</code> returns <code>"Now is the time ..."</code>.</p><p>The expression <code>fn:string-join(('Blow, ', 'blow, ', 'thou ', 'winter ', 'wind!'),
                  '')</code> returns <code>"Blow, blow, thou winter wind!"</code>.</p><p>The expression <code>fn:string-join((), 'separator')</code> returns <code>""</code>.</p><p>The expression <code>fn:string-join(1 to 5, ', ')</code> returns <code>"1, 2, 3, 4, 5"</code>.</p><eg xml:space="preserve">let $doc := &lt;doc&gt;
  &lt;chap&gt;
    &lt;section xml:id="xyz"/&gt;
  &lt;/chap&gt;
&lt;/doc&gt;</eg><p>The expression <code>$doc//@xml:id ! fn:string-join((node-name(), '="', ., '"'))</code> returns <code>'xml:id="xyz"'</code>.</p><p>The expression <code>$doc//section ! fn:string-join(ancestor-or-self::*/name(), '/')</code> returns <code>"doc/chap/section"</code>.</p></def></gitem></glist></div3><div3 id="func-substring"><head>fn:substring</head><glist><gitem><label>Summary</label><def><p>Returns the portion of the value of <code>$sourceString</code> beginning at the position
            indicated by the value of <code>$start</code> and continuing for the number of <termref def="character">characters</termref> indicated by the value of
            <code>$length</code>.</p></def></gitem><gitem><label>Signatures</label><def><example role="signature"><proto name="substring" return-type="xs:string" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="sourceString" type="xs:string?"/><arg name="start" type="xs:double"/></proto></example><example role="signature"><proto name="substring" return-type="xs:string" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="sourceString" type="xs:string?"/><arg name="start" type="xs:double"/><arg name="length" type="xs:double"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>If the value of <code>$sourceString</code> is the empty sequence, the function returns
            the zero-length string. </p><p>Otherwise, the function returns a string comprising those <termref def="character">characters</termref> of <code>$sourceString</code> whose index position (counting
            from one) is greater than or equal to the value of <code>$start</code> (rounded to an
            integer), and (if <code>$length</code> is specified) less than the sum of
               <code>$start</code> and <code>$length</code> (both rounded to integers).</p><p>The characters returned do not extend beyond <code>$sourceString</code>. If
               <code>$start</code> is zero or negative, only those characters in positions greater
            than zero are returned.</p><p>More specifically, the three argument version of the function returns the characters in
               <code>$sourceString</code> whose position <code>$p</code> satisfies:</p><p diff="chg" at="E">
            <code>fn:round($start) &lt;= $p and $p &lt; fn:round($start) + fn:round($length)</code>
         </p><p>The two argument version of the function assumes that <code>$length</code> is infinite
            and thus returns the <termref def="character">characters</termref> in
               <code>$sourceString</code> whose position <code>$p</code> satisfies:</p><p>
            <code>fn:round($start) &lt;= $p</code>
         </p><p>In the above computations, the rules for <code>op:numeric-less-than</code> and
               <code>op:numeric-greater-than</code> apply.</p></def></gitem><gitem><label>Notes</label><def><p role="note">The first character of a string is located at position 1, not position 0.</p><p role="note">The second and third arguments allow <code>xs:double</code> values (rather than
         requiring <code>xs:integer</code>) in order to achieve compatibility with XPath 1.0.</p><p role="note">A surrogate pair counts as one character, not two.</p><p role="note">The consequences of supplying values such as <code>NaN</code> or positive or negative
         infinity for the <code>$start</code> or <code>$length</code> arguments follow from the
         above rules, and are not always intuitive.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>fn:substring("motor car", 6)</code> returns <code>" car"</code>. <emph>(Characters starting at position 6 to the end of
                     <code>$sourceString</code> are selected.)</emph></p><p/><p>The expression <code>fn:substring("metadata", 4, 3)</code> returns <code>"ada"</code>. <emph>(Characters at positions greater than or equal to 4 and less than 7 are
                  selected.)</emph></p><p>The expression <code>fn:substring("12345", 1.5, 2.6)</code> returns <code>"234"</code>. <emph>(Characters at positions greater than or equal to 2 and less than 5 are
                  selected.)</emph></p><p>The expression <code>fn:substring("12345", 0, 3)</code> returns <code>"12"</code>. <emph>(Characters at positions greater than or equal to 0 and less than 3 are
                  selected. Since the first position is 1, these are the characters at positions 1
                  and 2.)</emph></p><p>The expression <code>fn:substring("12345", 5, -3)</code> returns <code>""</code>. <emph>(Characters at positions greater than or equal to 5 and less than 2 are
                  selected.)</emph></p><p>The expression <code>fn:substring("12345", -3, 5)</code> returns <code>"1"</code>. <emph>(Characters at positions greater than or equal to -3 and less than 2
                  are selected. Since the first position is 1, this is the character at position
                  1.)</emph></p><p>The expression <code>fn:substring("12345", 0 div 0E0, 3)</code> returns <code>""</code>. <emph>(Since <code>0 div 0E0</code> returns <code>NaN</code>, and
                     <code>NaN</code> compared to any other number returns <code>false</code>, no
                  characters are selected.)</emph></p><p>The expression <code>fn:substring("12345", 1, 0 div 0E0)</code> returns <code>""</code>. <emph>(As above.)</emph></p><p>The expression <code>fn:substring((), 1, 3)</code> returns <code>""</code>.</p><p>The expression <code>fn:substring("12345", -42, 1 div 0E0)</code> returns <code>"12345"</code>. <emph>(Characters at positions greater than or equal to -42 and less than
                     <code>INF</code> are selected.)</emph></p><p>The expression <code>fn:substring("12345", -1 div 0E0, 1 div 0E0)</code> returns <code>""</code>. <emph>(Since the value of <code>-INF + INF</code> is <code>NaN</code>, no
                  characters are selected.)</emph></p></def></gitem></glist></div3><div3 id="func-string-length"><head>fn:string-length</head><glist><gitem><label>Summary</label><def><p>Returns the number of <termref def="character">characters</termref> in a string.</p></def></gitem><gitem><label>Signatures</label><def><example role="signature"><proto name="string-length" return-type="xs:integer" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"/></example><example role="signature"><proto name="string-length" return-type="xs:integer" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg" type="xs:string?"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>The zero-argument form of this function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-dependent">context-dependent</termref>,  and <termref def="dt-focus-dependent">focus-dependent</termref>. </p><p>The one-argument form of this function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>The function returns an <code>xs:integer</code> equal to the length in <termref def="character">characters</termref> of the value of <code>$arg</code>.</p><p>Calling the zero-argument version of the function is equivalent to calling
               <code>fn:string-length(fn:string(.))</code>.</p><p>If the value of <code>$arg</code> is the empty sequence, the function returns the
               <code>xs:integer</code> value zero (0).</p></def></gitem><gitem><label>Error Conditions</label><def><p>If <code>$arg</code> is not specified and the context item is <xtermref ref="dt-absent" spec="DM31">absent</xtermref>, a dynamic error is raised: <xerrorref spec="XP" class="DY" code="0002" type="dynamic"/>.</p></def></gitem><gitem><label>Notes</label><def><p role="note">Unlike some programming languages, a <termref def="codepoint">codepoint</termref>
            greater than 65535 counts as one character, not two.</p><p role="note">There are situations where <code>fn:string-length()</code> has a different effect
            from <code>fn:string-length(.)</code>. For example, if the context item
         is an attribute node typed as an <code>xs:integer</code> with the string value <code>000001</code>,
         then <code>fn:string-length()</code> returns 6 (the length of the string value of the node), while 
            <code>fn:string-length(.)</code> raises a type error (because the result of atomization
            is not an <code>xs:string</code>).</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>fn:string-length("Harp not on that string, madam; that is past.")</code> returns <code>45</code>.</p><p>The expression <code>fn:string-length(())</code> returns <code>0</code>.</p></def></gitem></glist></div3><div3 id="func-normalize-space"><head>fn:normalize-space</head><glist><gitem><label>Summary</label><def><p>Returns the value of <code>$arg</code> with leading and trailing whitespace removed, and
            sequences of internal whitespace reduced to a single space character.</p></def></gitem><gitem><label>Signatures</label><def><example role="signature"><proto name="normalize-space" return-type="xs:string" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"/></example><example role="signature"><proto name="normalize-space" return-type="xs:string" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg" type="xs:string?"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>The zero-argument form of this function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-dependent">context-dependent</termref>,  and <termref def="dt-focus-dependent">focus-dependent</termref>. </p><p>The one-argument form of this function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>If the value of <code>$arg</code> is the empty sequence, the function returns the
            zero-length string.</p><p>The function returns a string constructed by stripping leading and trailing whitespace
            from the value of <code>$arg</code>, and replacing sequences of one or more adjacent
            whitespace characters with a single space, <code>#x20</code>.</p><p>The whitespace characters are defined in the metasymbol S (Production 3) of <bibref ref="xml"/>.</p><p>If no argument is supplied, then <code>$arg</code> defaults to the string value
            (calculated using <code>fn:string</code>) of the context item (<code>.</code>). </p></def></gitem><gitem><label>Error Conditions</label><def><p>If no argument is supplied and the context item is <xtermref ref="dt-absent" spec="DM31">absent</xtermref> then a dynamic error is raised: <xerrorref spec="XP" class="DY" code="0002" type="dynamic"/>.</p></def></gitem><gitem><label>Notes</label><def><p role="note">The definition of whitespace is unchanged in <bibref ref="xml11"/>. It is repeated here
         for convenience:</p><p role="note"><code>S ::= (#x20 | #x9 | #xD | #xA)+</code></p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>fn:normalize-space(" The    wealthy curled darlings
                                        of    our    nation. ")</code> returns <code>"The wealthy curled darlings of our nation."</code>.</p><p>The expression <code>fn:normalize-space(())</code> returns <code>""</code>.</p></def></gitem></glist></div3><div3 id="func-normalize-unicode"><head>fn:normalize-unicode</head><glist><gitem><label>Summary</label><def><p>Returns the value of <code>$arg</code> after applying Unicode normalization.</p></def></gitem><gitem><label>Signatures</label><def><example role="signature"><proto name="normalize-unicode" return-type="xs:string" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg" type="xs:string?"/></proto></example><example role="signature"><proto name="normalize-unicode" return-type="xs:string" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg" type="xs:string?"/><arg name="normalizationForm" type="xs:string"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>If the value of <code>$arg</code> is the empty sequence, the function returns the
            zero-length string.</p><p>If the single-argument version of the function is used, the result is the same as
            calling the two-argument version with <code>$normalizationForm</code> set to the string
            "NFC".</p><p>Otherwise, the function returns the value of <code>$arg</code> normalized according to
            the rules of the normalization form identified by the value of
               <code>$normalizationForm</code>.</p><p>The effective value of <code>$normalizationForm</code> is the value of the expression
               <code>fn:upper-case(fn:normalize-space($normalizationForm))</code>.</p><ulist><item><p>If the effective value of <code>$normalizationForm</code> is <quote>NFC</quote>,
                  then the function returns the value of <code>$arg</code> converted to Unicode
                  Normalization Form C (NFC).</p></item><item><p>If the effective value of <code>$normalizationForm</code> is <quote>NFD</quote>,
                  then the function returns the value of <code>$arg</code> converted to Unicode
                  Normalization Form D (NFD).</p></item><item><p>If the effective value of <code>$normalizationForm</code> is <quote>NFKC</quote>,
                  then the function returns the value of <code>$arg</code> in Unicode Normalization
                  Form KC (NFKC).</p></item><item><p>If the effective value of <code>$normalizationForm</code> is <quote>NFKD</quote>,
                  then the function returns the value of <code>$arg</code> converted to Unicode
                  Normalization Form KD (NFKD).</p></item><item><p>If the effective value of <code>$normalizationForm</code> is
                     <quote>FULLY-NORMALIZED</quote>, then the function returns the value of
                     <code>$arg</code> converted to fully normalized form. </p></item><item><p>If the effective value of <code>$normalizationForm</code> is the zero-length
                  string, no normalization is performed and <code>$arg</code> is returned.</p></item></ulist><p>Normalization forms NFC, NFD, NFKC, and NFKD, and the algorithms to be used for
            converting a string to each of these forms, are defined in <bibref ref="UNICODE-TR15"/>.</p><p>The motivation for normalization form FULLY-NORMALIZED is explained in <bibref ref="charmod-normalization"/>. However, as that specification did not progress beyond
            working draft status, the normative specification is as follows:</p><ulist><item><p>A string is <term>fully-normalized</term> if (a) it is in normalization form NFC
                  as defined in <bibref ref="UNICODE-TR15"/>, and (b) it does not start
                  with a composing character.</p></item><item><p>A composing character is a character that is one or both of the following:</p><ulist><item><p>the second character in the canonical decomposition mapping of some
                        character that is not listed in the Composition Exclusion Table defined in
                        <bibref ref="UNICODE-TR15"/>;</p></item><item><p>of non-zero canonical combining class (as defined in <bibref ref="Unicode"/>).</p></item></ulist></item><item><p>A string is converted to FULLY-NORMALIZED form as follows:</p><ulist><item><p>if the first character in the string is a composing character, prepend a
                        single space (x20);</p></item><item><p>convert the resulting string to normalization form NFC.</p></item></ulist></item></ulist><p>Conforming implementations <rfc2119>must</rfc2119> support normalization form "NFC" and
               <rfc2119>may</rfc2119> support normalization forms "NFD", "NFKC", "NFKD", and
            "FULLY-NORMALIZED". They <rfc2119>may</rfc2119> also support other normalization forms
            with <termref def="implementation-defined">implementation-defined</termref> semantics. </p><p>It is <termref def="implementation-defined">implementation-defined</termref> which
            version of Unicode (and therefore, of the normalization algorithms and their underlying
            data) is supported by the implementation. See <bibref ref="UNICODE-TR15"/> for
            details of the stability policy regarding changes to the normalization rules in future
            versions of Unicode. If the input string contains codepoints that are unassigned in the
            relevant version of Unicode, or for which no normalization rules are defined, the
               <code>fn:normalize-unicode</code> function leaves such codepoints unchanged. If the
            implementation supports the requested normalization form then it <rfc2119>must</rfc2119>
            be able to handle every input string without raising an error.</p></def></gitem><gitem><label>Error Conditions</label><def><p>A <phrase>dynamic</phrase> error is raised <errorref class="CH" code="0003"/> if the
            effective value of the <code>$normalizationForm</code> argument is not one of the values
            supported by the implementation.</p></def></gitem></glist></div3><div3 id="func-upper-case"><head>fn:upper-case</head><glist><gitem><label>Summary</label><def><p>Converts a string to upper case.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="upper-case" return-type="xs:string" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg" type="xs:string?"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>If the value of <code>$arg</code> is the empty sequence, the zero-length string is
            returned.</p><p>Otherwise, the function returns the value of <code>$arg</code> after translating every
               <termref def="character">character</termref> to its upper-case correspondent as
            defined in the appropriate case mappings section in the Unicode standard <bibref ref="Unicode"/>. For versions of Unicode beginning with the 2.1.8 update, only
            locale-insensitive case mappings should be applied. Beginning with version 3.2.0 (and
            likely future versions) of Unicode, precise mappings are described in default case
            operations, which are full case mappings in the absence of tailoring for particular
            languages and environments. Every lower-case character that does not have an upper-case
            correspondent, as well as every upper-case character, is included in the returned value
            in its original form. </p></def></gitem><gitem><label>Notes</label><def><p role="note">Case mappings may change the length of a string. In general, the
               <code>fn:upper-case</code> and <code>fn:lower-case</code> functions are not inverses
            of each other: <code>fn:lower-case(fn:upper-case($arg))</code> is not guaranteed to
            return <code>$arg</code>, nor is <code>fn:upper-case(fn:lower-case($arg))</code>. The
            Latin small letter dotless i (as used in Turkish) is perhaps the most prominent
            lower-case letter which will not round-trip. The Latin capital letter i with dot above
            is the most prominent upper-case letter which will not round trip; there are others,
            such as Latin capital letter Sharp S (#1E9E) which was introduced in Unicode 5.1.</p><p role="note"> These functions may not always be linguistically appropriate (e.g. Turkish i without
            dot) or appropriate for the application (e.g. titlecase). In cases such as Turkish, a
            simple translation should be used first.</p><p role="note"> Because the function is not sensitive to locale, results will not always match user
            expectations. In Quebec, for example, the standard uppercase equivalent of "è" is "È",
            while in metropolitan France it is more commonly "E"; only one of these is supported by
            the functions as defined.</p><p role="note"> Many characters of class Ll lack uppercase equivalents in the Unicode case mapping
            tables; many characters of class Lu lack lowercase equivalents.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>fn:upper-case("abCd0")</code> returns <code>"ABCD0"</code>.</p></def></gitem></glist></div3><div3 id="func-lower-case"><head>fn:lower-case</head><glist><gitem><label>Summary</label><def><p>Converts a string to lower case.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="lower-case" return-type="xs:string" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg" type="xs:string?"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>If the value of <code>$arg</code> is the empty sequence, the zero-length string is
            returned.</p><p>Otherwise, the function returns the value of <code>$arg</code> after translating every
               <termref def="character">character</termref> to its lower-case correspondent as
            defined in the appropriate case mappings section in the Unicode standard <bibref ref="Unicode"/>. For versions of Unicode beginning with the 2.1.8 update, only
            locale-insensitive case mappings should be applied. Beginning with version 3.2.0 (and
            likely future versions) of Unicode, precise mappings are described in default case
            operations, which are full case mappings in the absence of tailoring for particular
            languages and environments. Every upper-case character that does not have a lower-case
            correspondent, as well as every lower-case character, is included in the returned value
            in its original form. </p></def></gitem><gitem><label>Notes</label><def><p role="note">Case mappings may change the length of a string. In general, the
               <code>fn:upper-case</code> and <code>fn:lower-case</code> functions are not inverses
            of each other: <code>fn:lower-case(fn:upper-case($arg))</code> is not guaranteed to
            return <code>$arg</code>, nor is <code>fn:upper-case(fn:lower-case($arg))</code>. The
            Latin small letter dotless i (as used in Turkish) is perhaps the most prominent
            lower-case letter which will not round-trip. The Latin capital letter i with dot above
            is the most prominent upper-case letter which will not round trip; there are others,
            such as Latin capital letter Sharp S (#1E9E) which was introduced in Unicode 5.1.</p><p role="note"> These functions may not always be linguistically appropriate (e.g. Turkish i without
            dot) or appropriate for the application (e.g. titlecase). In cases such as Turkish, a
            simple translation should be used first.</p><p role="note"> Because the function is not sensitive to locale, results will not always match user
            expectations. In Quebec, for example, the standard uppercase equivalent of "è" is "È",
            while in metropolitan France it is more commonly "E"; only one of these is supported by
            the functions as defined.</p><p role="note"> Many characters of class Ll lack uppercase equivalents in the Unicode case mapping
            tables; many characters of class Lu lack lowercase equivalents.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>fn:lower-case("ABc!D")</code> returns <code>"abc!d"</code>.</p></def></gitem></glist></div3><div3 id="func-translate"><head>fn:translate</head><glist><gitem><label>Summary</label><def><p>Returns the value of <code>$arg</code> modified by replacing or removing individual
            characters. </p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="translate" return-type="xs:string" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg" type="xs:string?"/><arg name="mapString" type="xs:string"/><arg name="transString" type="xs:string"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>If the value of <code>$arg</code> is the empty sequence, the function returns the
            zero-length string.</p><p>Otherwise, the function returns a result string constructed by processing each <termref def="character">character</termref> in the value of <code>$arg</code>, in order,
            according to the following rules:</p><olist><item><p>If the character does not appear in the value of <code>$mapString</code> then it
                  is added to the result string unchanged.</p></item><item><p>If the character first appears in the value of <code>$mapString</code> at some
                  position <emph>M</emph>, where the value of <code>$transString</code> is
                     <emph>M</emph> or more characters in length, then the character at position
                     <emph>M</emph> in <code>$transString</code> is added to the result string.</p></item><item><p>If the character first appears in the value of <code>$mapString</code> at some
                  position <emph>M</emph>, where the value of <code>$transString</code> is less than
                     <emph>M</emph> characters in length, then the character is omitted from the
                  result string.</p></item></olist></def></gitem><gitem><label>Notes</label><def><p role="note">If <code>$mapString</code> is the zero-length string then the function returns
               <code>$arg</code> unchanged.</p><p role="note">If a character occurs more than once in <code>$mapString</code>, then the first
            occurrence determines the action taken.</p><p role="note">If <code>$transString</code> is longer than <code>$mapString</code>, the excess
            characters are ignored.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>fn:translate("bar","abc","ABC")</code> returns <code>"BAr"</code>.</p><p>The expression <code>fn:translate("--aaa--","abc-","ABC")</code> returns <code>"AAA"</code>.</p><p>The expression <code>fn:translate("abcdabc", "abc", "AB")</code> returns <code>"ABdAB"</code>.</p></def></gitem></glist></div3></div2><div2 id="substring.functions"><head>Functions based on substring matching</head><p>The functions described in the section examine a string <code>$arg1</code> to see
                    whether it contains another string <code>$arg2</code> as a substring. The result
                    depends on whether <code>$arg2</code> is a substring of <code>$arg1</code>, and
               if so, on the range of <termref def="character">characters</termref> in <code>$arg1</code> which <code>$arg2</code> matches.</p><p>When the <termref def="dt-codepoint-collation">Unicode codepoint collation</termref>
                    is used, this simply involves determining whether <code>$arg1</code> contains a
               contiguous sequence of characters whose <termref def="codepoint">codepoints</termref> are the same, one for one,
                    with the codepoints of the characters in <code>$arg2</code>.</p><p>When a collation is specified, the rules are more complex.</p><p>All collations support the capability of deciding whether two <termref def="string">strings</termref> are
                    considered equal, and if not, which of the strings should be regarded as
                    preceding the other. For functions such as <code>fn:compare</code>, this is
                    all that is required. For other functions, such as <code>fn:contains</code>,
                    the collation needs to support an additional property: it must be able to
                    decompose the string into a sequence of collation units, each unit consisting of
                    one or more characters, such that two strings can be compared by pairwise
                    comparison of these units. ("collation unit" is equivalent to "collation
                    element" as defined in <bibref ref="UNICODE-TR10"/>.) The string
                    <code>$arg1</code> is then considered to contain <code>$arg2</code> as a
                    substring if the sequence of collation units corresponding to <code>$arg2</code>
                    is a subsequence of the sequence of the collation units corresponding to
                    <code>$arg1</code>. The characters in <code>$arg1</code> that match are the
                    characters corresponding to these collation units.</p><p>This rule may occasionally lead to surprises. For example, consider a collation
                    that treats "Jaeger" and "Jäger" as equal. It might do this by
                    treating "ä" as representing two collation units, in which case the
                        expression <code>fn:contains("Jäger", "eg")</code> will return
                    <code>true</code>. Alternatively, a collation might treat "ae" as a single
                    collation unit, in which case the expression <code>fn:contains("Jaeger",
                    "eg")</code> will return <code>false</code>. The results of these functions thus
                    depend strongly on the properties of the collation that is used.</p><p>In addition,
                    collations may specify that some collation units should be ignored during matching. If hyphen is an ignored
					collation unit, then <code>fn:contains("code-point", "codepoint")</code> will be true, 
					and <code>fn:contains("codepoint", "-")</code> will also be true.</p><p> In the definitions below, we refer to the terms <term>match</term> and
                    <term>minimal match</term> as defined in definitions DS2 and DS4 of 
                    <bibref ref="UNICODE-TR10"/>. In applying these definitions:</p><ulist><item><p>
                     <var>C</var> is the collation; that is, the value of the <code>$collation</code>
                    argument if specified, otherwise the default collation.</p></item><item><p>
                     <var>P</var> is the (candidate) substring <code>$arg2</code>
                  </p></item><item><p>
                     <var>Q</var> is the (candidate) containing string <code>$arg1</code>
                  </p></item><item><p>The boundary condition <var>B</var> is satisfied at the start and end of a
                    string, and between any two characters that belong to different collation units
                    ("collation elements" in the language of <bibref ref="UNICODE-TR10"/>). It
                    is not satisfied between two characters that belong to the same collation unit.</p></item></ulist><p>It is possible to define collations that do not have the ability to decompose a
                    string into units suitable for substring matching. An argument to a function
                    defined in this section may be a URI that identifies a collation that is able to
                    compare two strings, but that does not have the capability to split the string
                    into collation units. Such a collation may cause the function to fail, or to
                    give unexpected results or it may be rejected as an unsuitable argument. The
                    ability to decompose strings into collation units is an <termref def="implementation-defined"/> property of the collation.</p><table class="index"><thead><tr><th rowspan="1" colspan="1">Function</th><th rowspan="1" colspan="1">Meaning</th></tr></thead><tbody><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:contains</code></td><td rowspan="1" colspan="1">Returns true if the string <code>$arg1</code> contains <code>$arg2</code> as a
            substring, taking collations into account.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:starts-with</code></td><td rowspan="1" colspan="1">Returns true if the string <code>$arg1</code> contains <code>$arg2</code> as a leading
            substring, taking collations into account.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:ends-with</code></td><td rowspan="1" colspan="1">Returns true if the string <code>$arg1</code> contains <code>$arg2</code> as a trailing
            substring, taking collations into account.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:substring-before</code></td><td rowspan="1" colspan="1">Returns the part of <code>$arg1</code> that precedes the first occurrence of
               <code>$arg2</code>, taking collations into account.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:substring-after</code></td><td rowspan="1" colspan="1">Returns the part of <code>$arg1</code> that follows the first occurrence of
               <code>$arg2</code>, taking collations into account.</td></tr></tbody></table><div3 id="func-contains"><head>fn:contains</head><glist><gitem><label>Summary</label><def><p>Returns true if the string <code>$arg1</code> contains <code>$arg2</code> as a
            substring, taking collations into account.</p></def></gitem><gitem><label>Signatures</label><def><example role="signature"><proto name="contains" return-type="xs:boolean" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg1" type="xs:string?"/><arg name="arg2" type="xs:string?"/></proto></example><example role="signature"><proto name="contains" return-type="xs:boolean" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg1" type="xs:string?"/><arg name="arg2" type="xs:string?"/><arg name="collation" type="xs:string"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>The two-argument form of this function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-dependent">context-dependent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>.  It depends on 
		collations.
	</p><p>The three-argument form of this function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-dependent">context-dependent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>.  It depends on 
		collations, and static base URI.
	</p></def></gitem><gitem><label>Rules</label><def><p>If the value of <code>$arg1</code> or <code>$arg2</code> is the empty sequence, or
            contains only ignorable collation units, it is interpreted as the zero-length
            string.</p><p>If the value of <code>$arg2</code> is the zero-length string, then the function returns
               <code>true</code>.</p><p>If the value of <code>$arg1</code> is the zero-length string, the function returns
               <code>false</code>.</p><p>The collation used by this function is determined according to the rules in <specref ref="choosing-a-collation"/>.</p><p>The function returns an <code>xs:boolean</code> indicating whether or not the value of
               <code>$arg1</code> contains (at the beginning, at the end, or anywhere within) at
            least one sequence of collation units that provides a <term>minimal match</term> to the
            collation units in the value of <code>$arg2</code>, according to the collation that is
            used.</p><note><p><term>Minimal match</term> is defined in <bibref ref="UNICODE-TR10"/>. </p></note></def></gitem><gitem><label>Error Conditions</label><def><p>A <phrase>dynamic</phrase> error <rfc2119>may</rfc2119> be raised <errorref class="CH" code="0004"/> if the specified collation does not support collation units.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The collation used in these examples, <code>http://example.com/CollationA</code> is a
               collation in which both "-" and "*" are ignorable collation units.</p><p>"Ignorable collation unit" is equivalent to "ignorable collation element" in <bibref ref="UNICODE-TR10"/>.</p><p>The expression <code>fn:contains ( "tattoo", "t")</code> returns <code>true()</code>.</p><p>The expression <code>fn:contains ( "tattoo", "ttt")</code> returns <code>false()</code>.</p><p>The expression <code>fn:contains ( "", ())</code> returns <code>true()</code>. <emph>(The first rule is applied, followed by the second
                  rule.)</emph></p><p>The expression <code>fn:contains ( "abcdefghi", "-d-e-f-",
                  "http://www.w3.org/2013/collation/UCA?lang=en;alternate=blanked;strength=primary")</code> returns <code>true()</code>.</p><p>The expression <code>fn:contains ( "a*b*c*d*e*f*g*h*i*", "d-ef-",
                  "http://www.w3.org/2013/collation/UCA?lang=en;alternate=blanked;strength=primary")</code> returns <code>true()</code>.</p><p>The expression <code>fn:contains ( "abcd***e---f*--*ghi", "def",
                  "http://www.w3.org/2013/collation/UCA?lang=en;alternate=blanked;strength=primary")</code> returns <code>true()</code>.</p><p>The expression <code>fn:contains ( (), "--***-*---",
                  "http://www.w3.org/2013/collation/UCA?lang=en;alternate=blanked;strength=primary")</code> returns <code>true()</code>. <emph>(The second argument contains only ignorable collation units and is
                  equivalent to the zero-length string.)</emph></p></def></gitem></glist></div3><div3 id="func-starts-with"><head>fn:starts-with</head><glist><gitem><label>Summary</label><def><p>Returns true if the string <code>$arg1</code> contains <code>$arg2</code> as a leading
            substring, taking collations into account.</p></def></gitem><gitem><label>Signatures</label><def><example role="signature"><proto name="starts-with" return-type="xs:boolean" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg1" type="xs:string?"/><arg name="arg2" type="xs:string?"/></proto></example><example role="signature"><proto name="starts-with" return-type="xs:boolean" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg1" type="xs:string?"/><arg name="arg2" type="xs:string?"/><arg name="collation" type="xs:string"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>The two-argument form of this function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-dependent">context-dependent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>.  It depends on 
		collations.
	</p><p>The three-argument form of this function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-dependent">context-dependent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>.  It depends on 
		collations, and static base URI.
	</p></def></gitem><gitem><label>Rules</label><def><p>If the value of <code>$arg1</code> or <code>$arg2</code> is the empty sequence, or
            contains only ignorable collation units, it is interpreted as the zero-length
            string.</p><p>If the value of <code>$arg2</code> is the zero-length string, then the function returns
               <code>true</code>. If the value of <code>$arg1</code> is the zero-length string and
            the value of <code>$arg2</code> is not the zero-length string, then the function returns
               <code>false</code>.</p><p>The collation used by this function is determined according to the rules in <specref ref="choosing-a-collation"/>.</p><p>The function returns an <code>xs:boolean</code> indicating whether or not the value of
               <code>$arg1</code> starts with a sequence of collation units that provides a
               <term>match</term> to the collation units of <code>$arg2</code> according to the
            collation that is used.</p><note><p><term>Match</term> is defined in <bibref ref="UNICODE-TR10"/>.</p></note></def></gitem><gitem><label>Error Conditions</label><def><p>A <phrase>dynamic</phrase> error <rfc2119>may</rfc2119> be raised <errorref class="CH" code="0004"/> if the specified collation does not support collation units.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The collation used in these examples, <code>http://example.com/CollationA</code> is a
               collation in which both "-" and "*" are ignorable collation units.</p><p>"Ignorable collation unit" is equivalent to "ignorable collation element" in <bibref ref="UNICODE-TR10"/>.</p><p>The expression <code>fn:starts-with("tattoo", "tat")</code> returns <code>true()</code>.</p><p>The expression <code>fn:starts-with ( "tattoo", "att")</code> returns <code>false()</code>.</p><p>The expression <code>fn:starts-with ((), ())</code> returns <code>true()</code>.</p><p>The expression <code>fn:starts-with ( "abcdefghi", "-a-b-c-",
                  "http://www.w3.org/2013/collation/UCA?lang=en;alternate=blanked;strength=primary")</code> returns <code>true()</code>.</p><p>The expression <code>fn:starts-with ( "a*b*c*d*e*f*g*h*i*", "a-bc-",
                  "http://www.w3.org/2013/collation/UCA?lang=en;alternate=blanked;strength=primary")</code> returns <code>true()</code>.</p><p>The expression <code>fn:starts-with ( "abcd***e---f*--*ghi", "abcdef",
                  "http://www.w3.org/2013/collation/UCA?lang=en;alternate=blanked;strength=primary")</code> returns <code>true()</code>.</p><p>The expression <code>fn:starts-with ( (), "--***-*---",
                  "http://www.w3.org/2013/collation/UCA?lang=en;alternate=blanked;strength=primary")</code> returns <code>true()</code>. <emph>(The second argument contains only ignorable collation units and is
                  equivalent to the zero-length string.)</emph></p><p>The expression <code>fn:starts-with ( "-abcdefghi", "-abc",
                  "http://www.w3.org/2013/collation/UCA?lang=en;alternate=blanked;strength=primary")</code> returns <code>true()</code>.</p></def></gitem></glist></div3><div3 id="func-ends-with"><head>fn:ends-with</head><glist><gitem><label>Summary</label><def><p>Returns true if the string <code>$arg1</code> contains <code>$arg2</code> as a trailing
            substring, taking collations into account.</p></def></gitem><gitem><label>Signatures</label><def><example role="signature"><proto name="ends-with" return-type="xs:boolean" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg1" type="xs:string?"/><arg name="arg2" type="xs:string?"/></proto></example><example role="signature"><proto name="ends-with" return-type="xs:boolean" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg1" type="xs:string?"/><arg name="arg2" type="xs:string?"/><arg name="collation" type="xs:string"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>The two-argument form of this function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-dependent">context-dependent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>.  It depends on 
		collations.
	</p><p>The three-argument form of this function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-dependent">context-dependent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>.  It depends on 
		collations, and static base URI.
	</p></def></gitem><gitem><label>Rules</label><def><p>If the value of <code>$arg1</code> or <code>$arg2</code> is the empty sequence, or
            contains only ignorable collation units, it is interpreted as the zero-length
            string.</p><p>If the value of <code>$arg2</code> is the zero-length string, then the function returns
               <code>true</code>. If the value of <code>$arg1</code> is the zero-length string and
            the value of <code>$arg2</code> is not the zero-length string, then the function returns
               <code>false</code>.</p><p>The collation used by this function is determined according to the rules in <specref ref="choosing-a-collation"/>.</p><p>The function returns an <code>xs:boolean</code> indicating whether or not the value of
               <code>$arg1</code> <phrase diff="chg" at="B">ends</phrase> with a sequence of collation units that provides a
               <term>match</term> to the collation units of <code>$arg2</code> according to the
            collation that is used.</p><note><p>
               <term>Match</term> is defined in <bibref ref="UNICODE-TR10"/>. </p></note></def></gitem><gitem><label>Error Conditions</label><def><p>A <phrase>dynamic</phrase> error <rfc2119>may</rfc2119> be raised <errorref class="CH" code="0004"/> if the specified collation does not support collation units.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The collation used in these examples, <code>http://example.com/CollationA</code> is a
               collation in which both "-" and "*" are ignorable collation units.</p><p>"Ignorable collation unit" is equivalent to "ignorable collation element" in <bibref ref="UNICODE-TR10"/>.</p><p>The expression <code>fn:ends-with ( "tattoo", "tattoo")</code> returns <code>true()</code>.</p><p>The expression <code>fn:ends-with ( "tattoo", "atto")</code> returns <code>false()</code>.</p><p>The expression <code>fn:ends-with ((), ())</code> returns <code>true()</code>.</p><p>The expression <code>fn:ends-with ( "abcdefghi", "-g-h-i-",
                  "http://www.w3.org/2013/collation/UCA?lang=en;alternate=blanked;strength=primary")</code> returns <code>true()</code>.</p><p>The expression <code>fn:ends-with ( "abcd***e---f*--*ghi", "defghi",
                  "http://www.w3.org/2013/collation/UCA?lang=en;alternate=blanked;strength=primary")</code> returns <code>true()</code>.</p><p>The expression <code>fn:ends-with ( "abcd***e---f*--*ghi", "defghi",
                  "http://www.w3.org/2013/collation/UCA?lang=en;alternate=blanked;strength=primary")</code> returns <code>true()</code>.</p><p>The expression <code>fn:ends-with ( (), "--***-*---",
                  "http://www.w3.org/2013/collation/UCA?lang=en;alternate=blanked;strength=primary")</code> returns <code>true()</code>. <emph>(The second argument contains only ignorable collation units and is
                  equivalent to the zero-length string.)</emph></p><p>The expression <code>fn:ends-with ( "abcdefghi", "ghi-",
                  "http://www.w3.org/2013/collation/UCA?lang=en;alternate=blanked;strength=primary")</code> returns <code>true()</code>.</p></def></gitem></glist></div3><div3 id="func-substring-before"><head>fn:substring-before</head><glist><gitem><label>Summary</label><def><p>Returns the part of <code>$arg1</code> that precedes the first occurrence of
               <code>$arg2</code>, taking collations into account.</p></def></gitem><gitem><label>Signatures</label><def><example role="signature"><proto name="substring-before" return-type="xs:string" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg1" type="xs:string?"/><arg name="arg2" type="xs:string?"/></proto></example><example role="signature"><proto name="substring-before" return-type="xs:string" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg1" type="xs:string?"/><arg name="arg2" type="xs:string?"/><arg name="collation" type="xs:string"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>The two-argument form of this function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-dependent">context-dependent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>.  It depends on 
		collations.
	</p><p>The three-argument form of this function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-dependent">context-dependent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>.  It depends on 
		collations, and static base URI.
	</p></def></gitem><gitem><label>Rules</label><def><p> If the value of <code>$arg1</code> or <code>$arg2</code> is the empty sequence, or
            contains only ignorable collation units, it is interpreted as the zero-length
            string.</p><p>If the value of <code>$arg2</code> is the zero-length string, then the function returns
            the zero-length string. </p><p>If the value of <code>$arg1</code> does not contain a string that is equal to the value
            of <code>$arg2</code>, then the function returns the zero-length string. </p><p>The collation used by this function is determined according to the rules in <specref ref="choosing-a-collation"/>.</p><p>The function returns the substring of the value of <code>$arg1</code> that precedes in
            the value of <code>$arg1</code> the first occurrence of a sequence of collation units
            that provides a <term>minimal match</term> to the collation units of <code>$arg2</code>
            according to the collation that is used.</p><note><p><term>Minimal match</term> is defined in <bibref ref="UNICODE-TR10"/>. </p></note></def></gitem><gitem><label>Error Conditions</label><def><p>A <phrase>dynamic</phrase> error <rfc2119>may</rfc2119> be raised <errorref class="CH" code="0004"/> if the specified collation does not support collation units.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The collation used in these examples, <code>http://example.com/CollationA</code> is a
               collation in which both "-" and "*" are ignorable collation units.</p><p>"Ignorable collation unit" is equivalent to "ignorable collation element" in <bibref ref="UNICODE-TR10"/>.</p><p>The expression <code>fn:substring-before ( "tattoo", "attoo")</code> returns <code>"t"</code>.</p><p>The expression <code>fn:substring-before ( "tattoo", "tatto")</code> returns <code>""</code>.</p><p>The expression <code>fn:substring-before ((), ())</code> returns <code>""</code>.</p><p>The expression <code>fn:substring-before ( "abcdefghi", "--d-e-",
                  "http://www.w3.org/2013/collation/UCA?lang=en;alternate=blanked;strength=primary")</code> returns <code>"abc"</code>.</p><p>The expression <code>fn:substring-before ( "abc--d-e-fghi", "--d-e-",
                  "http://www.w3.org/2013/collation/UCA?lang=en;alternate=blanked;strength=primary")</code> returns <code>"abc--"</code>.</p><p>The expression <code>fn:substring-before ( "a*b*c*d*e*f*g*h*i*", "***cde",
                  "http://www.w3.org/2013/collation/UCA?lang=en;alternate=blanked;strength=primary")</code> returns <code>"a*b*"</code>.</p><p>The expression <code>fn:substring-before ( "Eureka!", "--***-*---",
                  "http://www.w3.org/2013/collation/UCA?lang=en;alternate=blanked;strength=primary")</code> returns <code>""</code>. <emph>(The second argument contains only ignorable collation units and is
                  equivalent to the zero-length string.)</emph></p></def></gitem></glist></div3><div3 id="func-substring-after"><head>fn:substring-after</head><glist><gitem><label>Summary</label><def><p>Returns the part of <code>$arg1</code> that follows the first occurrence of
               <code>$arg2</code>, taking collations into account.</p></def></gitem><gitem><label>Signatures</label><def><example role="signature"><proto name="substring-after" return-type="xs:string" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg1" type="xs:string?"/><arg name="arg2" type="xs:string?"/></proto></example><example role="signature"><proto name="substring-after" return-type="xs:string" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg1" type="xs:string?"/><arg name="arg2" type="xs:string?"/><arg name="collation" type="xs:string"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>The two-argument form of this function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-dependent">context-dependent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>.  It depends on 
		collations.
	</p><p>The three-argument form of this function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-dependent">context-dependent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>.  It depends on 
		collations, and static base URI.
	</p></def></gitem><gitem><label>Rules</label><def><p>If the value of <code>$arg1</code> or <code>$arg2</code> is the empty sequence, or
            contains only ignorable collation units, it is interpreted as the zero-length
            string.</p><p>If the value of <code>$arg2</code> is the zero-length string, then the function returns
            the value of <code>$arg1</code>.</p><p>If the value of <code>$arg1</code> does not contain a string that is equal to the value
            of <code>$arg2</code>, then the function returns the zero-length string. </p><p>The collation used by this function is determined according to the rules in <specref ref="choosing-a-collation"/>.</p><p>The function returns the substring of the value of <code>$arg1</code> that follows in
            the value of <code>$arg1</code> the first occurrence of a sequence of collation units
            that provides a <term>minimal match</term> to the collation units of <code>$arg2</code>
            according to the collation that is used. </p><note><p><term>Minimal match</term> is defined in <bibref ref="UNICODE-TR10"/>. </p></note></def></gitem><gitem><label>Error Conditions</label><def><p>A dynamic error <rfc2119>may</rfc2119> be raised <errorref class="CH" code="0004"/> if
            the specified collation does not support collation units.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The collation used in these examples, <code>http://example.com/CollationA</code> is a
               collation in which both "-" and "*" are ignorable collation units.</p><p>"Ignorable collation unit" is equivalent to "ignorable collation element" in <bibref ref="UNICODE-TR10"/>.</p><p>The expression <code>fn:substring-after("tattoo", "tat")</code> returns <code>"too"</code>.</p><p>The expression <code>fn:substring-after("tattoo", "tattoo")</code> returns <code>""</code>.</p><p>The expression <code>fn:substring-after((), ())</code> returns <code>""</code>.</p><p>The expression <code> fn:substring-after("abcdefghi", "--d-e-",
                  "http://www.w3.org/2013/collation/UCA?lang=en;alternate=blanked;strength=primary")</code> returns <code>"fghi"</code>.</p><p>The expression <code>fn:substring-after("abc--d-e-fghi", "--d-e-",
                  "http://www.w3.org/2013/collation/UCA?lang=en;alternate=blanked;strength=primary")</code> returns <code>"-fghi"</code>.</p><p>The expression <code>fn:substring-after ( "a*b*c*d*e*f*g*h*i*", "***cde***",
                  "http://www.w3.org/2013/collation/UCA?lang=en;alternate=blanked;strength=primary")</code> returns <code>"*f*g*h*i*"</code>.</p><p>The expression <code>fn:substring-after ( "Eureka!", "--***-*---",
                  "http://www.w3.org/2013/collation/UCA?lang=en;alternate=blanked;strength=primary")</code> returns <code>"Eureka!"</code>. <emph>(The second argument contains only ignorable collation units and is
                  equivalent to the zero-length string.)</emph></p></def></gitem></glist></div3></div2><div2 id="string.match"><head>String functions that use regular expressions</head><p>The three functions described in this section make use of a regular expression
                    syntax for pattern matching. This is described below.</p><table class="index"><thead><tr><th rowspan="1" colspan="1">Function</th><th rowspan="1" colspan="1">Meaning</th></tr></thead><tbody><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:matches</code></td><td rowspan="1" colspan="1">Returns true if the supplied string matches a given regular expression.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:replace</code></td><td rowspan="1" colspan="1">Returns a string produced from the input string by replacing any substrings that match a
            given regular expression with a supplied replacement string.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:tokenize</code></td><td rowspan="1" colspan="1">Returns a sequence of strings constructed by splitting the input wherever a separator is
            found; the separator is any substring that matches a given regular expression.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:analyze-string</code></td><td rowspan="1" colspan="1">Analyzes a string using a regular expression, returning an XML structure that identifies
            which parts of the input string matched or failed to match the regular expression, and
            in the case of matched substrings, which substrings matched each capturing group in the
            regular expression.</td></tr></tbody></table><div3 id="regex-syntax"><head>Regular expression syntax</head><p>The regular expression syntax used by these functions is defined in terms of
                        the regular expression syntax specified in XML Schema (see <bibref ref="xmlschema-2"/>), 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 omits some facilities that are widely-used
                        with languages such as Perl. This section, therefore, describes extensions
                        to the XML Schema regular expressions syntax that reinstate these capabilities.</p><note><p>
It is recommended that implementers consult <bibref ref="UNICODE-TR18"/> for information on using regular expression processing on Unicode characters.</p></note><p>The regular expression syntax and semantics are identical to those
                            defined in <bibref ref="xmlschema-2"/> with the additions described in the 
                  following sub-sections.</p><note><p>In <bibref ref="xmlschema11-2"/> there are no substantive technical changes
                  to the syntax or semantics of regular expressions relative to XSD 1.0, but a number
                  of errors and ambiguities have been resolved. For example, the rules for the 
                  interpretation of hyphens within square brackets in a regular expression have been 
                  clarified; and the semantics of regular expressions are no longer tied to a specific 
                  version of Unicode.</p><p>Implementers, even in cases where XSD 1.1 is not supported, are advised to consult
               the XSD 1.1 regular expression specification for guidance on how to handle cases where
               the XSD 1.0 specification is unclear or inconsistent.</p></note><div4 id="matching-start-and-end"><head>Matching the Start and End of the String</head><p> Two meta-characters, <code>^</code> and <code>$</code> are
                                    added. By default, the meta-character <code>^</code> matches the
                                    start of the entire string, while <code>$</code> matches the end
                                    of the entire string. In multi-line mode, <code>^</code> matches
                                    the start of any line (that is, the start of the entire string,
                                    and the position immediately after a newline character), while
                                    <code>$</code> matches the end of any line (that is, the end of
                                    the entire string, and the position immediately before a newline
                                    character). Newline here means the character <code>#x0A</code> only.</p><p>This means that the production in <bibref ref="xmlschema-2"/>:</p><p><code>[10] Char ::= [^.\?*+()|#x5B#x5D]</code>
                                </p><p>is modified to read:</p><p><code>[10] Char ::= [^.\?*+{}()|^$#x5B#x5D]</code>
                     </p><p>The XSD 1.1 grammar for regular expressions uses the same
                     production rule, but renumbered and renamed <code>[73] NormalChar</code>; it
                     is affected in the same way.</p><p>The characters <code>#x5B</code> and <code>#x5D</code> correspond
                                    to "<code>[</code>" and "<code>]</code>" respectively.</p><note><p>The definition of Char (production [10]) in <bibref ref="xmlschema-2"/> has a known error in which it omits the left brace ("{") and right brace ("}").  That error is corrected here.</p></note><p>The following production:</p><p><code>[11] charClass ::= charClassEsc | charClassExpr | WildCardEsc</code>
                                </p><p>is modified to read:</p><p><code>[11] charClass ::= charClassEsc | charClassExpr |
                                        WildCardEsc | "^" | "$"</code>
                     </p><p>Using XSD 1.1 as the baseline the equivalent is to change
                     the production:</p><p><code>[74] charClass ::= SingleCharEsc | charClassEsc | charClassExpr | WildCardEsc</code>
                     </p><p>to read:</p><p><code>[74] charClass ::= SingleCharEsc | charClassEsc | charClassExpr |
                        WildCardEsc | "^" | "$"</code>
                     </p><p>Single character escapes are extended to allow the
       <code>$</code> character to be escaped. The following production
       is changed:</p><p>
       <code>[24]SingleCharEsc ::= '\' [nrt\|.?*+(){}#x2D#x5B#x5D#x5E]</code>
    </p><p>to</p><p>
       <code>[24]SingleCharEsc ::= '\' [nrt\|.?*+(){}$#x2D#x5B#x5D#x5E]</code>
    </p><p>(In the XSD 1.1 version of the regular expression grammar, the production rule
       for <code>SingleCharEsc</code> is unchanged, but is renumbered [84])</p></div4><div4 id="reluctant-quantifiers"><head>Reluctant Quantifiers</head><p><emph>Reluctant quantifiers</emph> are supported. They are
                                    indicated by a 
                                        <code>?</code>
                                     following a quantifier. Specifically:</p><ulist><item><p><code>X??</code> matches X, once or not at all</p></item><item><p><code>X*?</code> matches X, zero or more times</p></item><item><p><code>X+?</code> matches X, one or more times</p></item><item><p><code>X{n}?</code> matches X, exactly n times</p></item><item><p><code>X{n,}?</code> matches X, at least n times</p></item><item><p><code>X{n,m}?</code> matches X, at least n times, but
                                            not more than m times</p></item></ulist><p>The effect of these quantifiers is that the regular expression
                                    matches the <emph>shortest</emph> possible substring consistent
                                    with the match as a whole succeeding. Without the 
                                        <code>?</code>
                                    , the regular expression matches the
                                    <emph>longest</emph> possible substring.</p><p>To achieve this, the production in <bibref ref="xmlschema-2"/>:</p><p><code>[4] quantifier ::= [?*+] | ( '{' quantity '}' )</code>
                                </p><p>is changed to:</p><p><code>[4] quantifier ::= ( [?*+] | ( '{' quantity '}' ) ) '?'?</code>
                     </p><p>(In the XSD 1.1 version of the regular expression grammar,
                     this rule is unchanged, but is renumbered [67])</p><note><p>Reluctant quantifiers have no effect on the results of the
                                        boolean <code>fn:matches</code> function, since this
                                        function is only interested in discovering whether a match
                                        exists, and not where it exists.</p></note></div4><div4 id="captured-subexpressions"><head>Captured Sub-Expressions</head><p>Sub-expressions (groups) within the regular expression are
                        recognized. The regular expression syntax defined by <bibref ref="xmlschema-2"/> 
						      allows a regular expression to contain parenthesized sub-expressions, but attaches no special
                        significance to them. Some operations associated with regular expressions (for example,
                           back-references, and the <code>fn:replace</code> function) allow access to the parts of the
                           input string that matched a sub-expression (called captured substrings).</p><p diff="chg" at="D"><termdef id="dt-capturing-subexpression" term="capturing sub-expression">A 
                        left parenthesis is recognized as a capturing left parenthesis provided 
                        it is not immediately followed by <code>?:</code> (see below), is not within a character group (square brackets), 
                        and is not escaped with a backslash. The sub-expression enclosed by a capturing left 
                        parenthesis and its matching right parenthesis is referred to as a <term>capturing sub-expression</term>.</termdef></p><p>More specifically, the <termref def="dt-capturing-subexpression">capturing sub-expression</termref> 
                        enclosed by the <var>N</var>th capturing left parenthesis within the regular expression (determined by
                        its character position in left-to-right order, and
                        counting from one) is referred to as the <var>N</var>th capturing sub-expression.
                     </p><p diff="chg" at="D">For example, in the regular expression <code>A(BC(?:D(EF(GH[()]))))</code>, the string matched
                        by the sub-expression <code>BC(?:D(EF(GH[()])))</code> is capturing sub-expression 1, the string
                        matched by <code>EF(GH[()])</code> is capturing sub-expression 2, and the string matched by
                        <code>GH[()]</code> is capturing sub-expression 3.
                     </p><p diff="chg" at="D">When, in the course of evaluating a regular expression, a particular substring of the input
                     matches a capturing sub-expression, that substring becomes available as a <term>captured substring</term>.
                        The string matched by the <var>N</var>th capturing sub-expression is referred to as the 
                        <var>N</var>th captured substring. By convention, the substring captured by the entire
                        regular expression is treated as captured substring 0 (zero).</p><p>When a <termref def="dt-capturing-subexpression">capturing sub-expression</termref> is matched
                        more than once (because it is within a construct that allows repetition), then
                        only the last substring that it matched will be captured. Note that this rule
                        is not sufficient in all cases to ensure an unambiguous result, especially in
                        cases where (a) the regular expression contains nested repeating constructs,
                        and/or (b) the repeating construct matches a zero-length string. In such cases
                        it is implementation-dependent which substring is captured. For example given
                        the regular expression <code>(a*)+</code> and the input string <code>"aaaa"</code>, an implementation
                        might legitimately capture either <code>"aaaa"</code> or a zero length string as the content
                        of the captured subgroup.</p><p>Parentheses that are required to group terms within the regular expression, but which are
                        not required for capturing of substrings, can be represented using
                        the syntax <code>(?:xxxx)</code>. To achieve this, the production rule for <code>atom</code>
                        in <bibref ref="xmlschema-2"/> is changed to replace the alternative:</p><p><code>( '(' regExp ')' )</code>
                     </p><p>with:</p><p><code>( '(' '?:'? regExp ')' )</code>
                     </p><p>(For the new versions of the XSD 1.0 and XSD 1.1 production rules for
                     <code>atom</code>, see below.)</p><p><phrase diff="add" at="E">In the absence of back-references (see below), </phrase>
                        the presence of the optional <code>?:</code> has no effect on the set of strings
                     that match the regular expression, but causes the left parenthesis not to be counted
                     by operations (such as <code>fn:replace</code> and back-references) that number the capturing sub-expressions 
                        within a regular expression.</p></div4><div4 id="back-references"><head>Back-References</head><p> Back-references are allowed 
			    outside a character class expression. 
				A back-reference is an additional kind of atom.
				The construct <code>\N</code> where
                <code>N</code> is a single digit is always recognized as a
                back-reference; if this is followed by further digits, these
                digits are taken to be part of the back-reference if and only if
                the resulting number <var>NN</var> is such that
				    the back-reference is preceded by the opening parenthesis of the <var>NN</var>th 
                capturing left parenthesis.
				The regular expression is invalid if a back-reference refers to a
				capturing sub-expression that does not exist or whose
                closing right parenthesis occurs after the back-reference.
                     </p><p>A back-reference with number <var>N</var> matches a string that is the same as
                        the value of the <code>N</code>th captured substring.</p><p>For example, the regular expression
                <code>('|").*\1</code> matches a sequence of characters
                delimited either by an apostrophe at the start and end, or by a
                quotation mark at the start and end. </p><p>If no string has been matched by the <code>N</code>th capturing 
               sub-expression, the back-reference is interpreted as matching 
               a zero-length string.</p><p>Combining this change with the introduction of
                        non-capturing groups (see above), back-references change the following production:</p><p>
                           <code>[9] atom ::= Char | charClass | ( '(' regExp ')' )</code>
                     </p><p>to</p><p>
                           <code>[9] atom ::= Char | charClass | ( '(' '?:'? regExp ')' ) | backReference</code>
                     </p><p>
                           <code>[9a] backReference ::= "\" [1-9][0-9]*</code>
                     </p><p>With respect to the XSD 1.1 version of the regular expression grammar,
                     the effect is to change:</p><p>
                           <code>[72] atom ::= NormalChar | charClass | ( '(' regExp ')' )</code>
                     </p><p>to</p><p>
                           <code>[72] atom ::= NormalChar | charClass | ( '(' '?:'? regExp ')' ) | backReference</code>
                     </p><p>
                           <code>[72a] backReference ::= "\" [1-9][0-9]*</code>
                     </p><note><p>
                           Within a character class expression, 
                              <code>\</code> followed by a digit is invalid.
			 Some other regular expression languages interpret this as an octal character reference.
                        </p></note></div4><div4 id="unicode-block-names"><head>Unicode Block Names</head><p>A regular expression that uses a Unicode block name that is not defined in the version(s) of Unicode
                     supported by the processor (for example <code>\p{IsBadBlockName}</code>) is deemed to be invalid
                        <errorref class="RX" code="0002"/>.</p><note><p>XSD 1.0 does not say how this situation should be handled; XSD 1.1
                        says that it should be handled by treating all characters as matching.</p></note></div4></div3><div3 id="flags"><head>Flags</head><p>All these functions provide an optional parameter, <code>$flags</code>,
                    to set options for the interpretation of the regular expression. The
                    parameter accepts a <code>xs:string</code>, 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 characters present that are not defined here as flags, then a dynamic error
                    is raised <errorref class="RX" code="0001"/>.</p><p>The following options are defined:</p><ulist><item><p><code>s</code>: If present, the match operates in "dot-all"
                        mode. (Perl calls this the single-line mode.) If the
                        <code>s</code> flag is not specified, the meta-character
                        <code>.</code> matches any character except a newline
                        (<code>#x0A</code>) or carriage return (<code>#x0D</code>) 
                        character. In dot-all mode, the
                        meta-character <code>.</code> matches any character whatsoever.
                        Suppose the input contains "hello" and "world" on two lines.
                        This will not be matched by the regular expression
                        "hello.*world" unless dot-all mode is enabled.</p></item><item><p>
                           <code>m</code>: If present, the match operates in multi-line
			            mode. By default, the meta-character <code>^</code> matches the
			            start of the entire string, while $ matches the end of the
			            entire string. In multi-line mode, <code>^</code> matches the
			            start of any line (that is, the start of the entire string, and
			            the position immediately after a newline character
						other than a newline
			            that appears as the last character in the string), while
			            <code>$</code> matches the end of any line 
						(that is, the position immediately
			            before a newline character, and the end of the entire string if there is no
			            newline character at the end of the string).
			            Newline here means the character <code>#x0A</code> only.</p></item><item><p><code>i</code>: If present, the match operates in
                        case-insensitive mode. The detailed rules are as follows. 
                        In these
                        rules, a character C2 is considered to be a <emph>case-variant</emph> of 
                        another character C1 if the following XPath expression returns 
                        <code>true</code> when the two characters
                           are considered as strings of length one, and the 
                           <termref def="dt-codepoint-collation">Unicode codepoint collation</termref> is used:</p><p>
                           <code>fn:lower-case(C1) eq fn:lower-case(C2) or
                        fn:upper-case(C1) eq fn:upper-case(C2)</code>
                        </p><p>
                                     Note that the case-variants of a character under this definition 
                                     are always single characters.</p><olist><item><p>
                                    When a normal character (<code>Char</code>) is used as an atom, 
                                    it represents 
                                    the set containing that character and all its case-variants. 
                                    For example, the regular expression "z" will match both "z" and 
                                    "Z".</p></item><item><p>
                                    A character range (production <code>charRange</code>
                                    in the XSD 1.0 grammar, replaced by productions <code>charRange</code> and <code>singleChar</code>
                                    in XSD 1.1) represents the set 
                                    containing all the characters that it would match in the absence 
                                    of the "<code>i</code>" flag, together with their case-variants. 
                                    For example, 
                                    the regular expression "[A-Z]" will match all
                                    the letters A-Z and all the letters a-z. It will also match 
                                    certain other characters such as <code>#x212A</code> (KELVIN SIGN), since 
                                    <code>fn:lower-case("#x212A")</code> is "k".</p><p>
                                    This rule applies also to a character range used in a character 
                                    class subtraction (<code>charClassSub</code>): thus [A-Z-[IO]] will match 
                                    characters such as "A", "B", "a", and "b", but will not match 
                                    "I", "O", "i", or "o".</p><p>
                                    The rule also applies to a character range used as part of a 
                                    negative character group: thus [^Q] will match every character 
                                    except "Q" and "q" (these being the only case-variants of "Q" in 
                                    Unicode).</p></item><item><p>
                                    A back-reference is compared using case-blind comparison: 
                                    that is, each character must either be the same as the 
                                    corresponding character of the previously matched string, or must 
                                    be a case-variant of that character. For example, the strings 
                                    "Mum", "mom", "Dad", and "DUD" all match the regular
                                    expression "([md])[aeiou]\1" when the "<code>i</code>" flag is used.</p></item><item><p>
                                    All other constructs are unaffected by the "<code>i</code>" flag. 
                                    For example, 
                                    "\p{Lu}" continues to match upper-case letters only.</p></item></olist></item><item><p><code>x</code>: If present, whitespace characters 
                                    (#x9, #xA, #xD and #x20) in the regular 
                                    expression are removed prior to matching with one exception:  
                                    whitespace characters within character class expressions 
                                    (<code>charClassExpr</code>) are not removed. This flag can be used, 
                                    for example, to break up long regular expressions into readable lines.</p><p> Examples:</p><p> 
                           <code>fn:matches("helloworld", "hello world", "x")</code> returns <code>true()</code>
                        </p><p> 
                           <code>fn:matches("helloworld", "hello[ ]world", "x")</code> returns <code>false()</code>
                        </p><p> 
                           <code>fn:matches("hello world", "hello\ sworld", "x")</code> returns <code>true()</code>
                        </p><p> 
                           <code>fn:matches("hello world", "hello world", "x")</code> returns <code>false()</code>
                        </p></item><item><p><code>q</code>: if present, all characters in the regular expression
                     are treated as representing themselves, not as metacharacters. In effect, every
                     character that would normally have a special meaning in a regular expression is implicitly escaped
                     by preceding it with a backslash.</p><p>Furthermore, when this flag is present, the characters <code>$</code> and
                         <code>\</code> have no special significance when used in the replacement string
                         supplied to the <code>fn:replace</code> function.</p><p>This flag can be used in conjunction with the <code>i</code> flag. If it is used
                           together with the <code>m</code>, <code>s</code>, or <code>x</code> flag, that flag
                           has no effect.</p><p>Examples:</p><p><code>fn:tokenize("12.3.5.6", ".", "q")</code> returns <code>("12", "3", "5", "6")</code></p><p><code>fn:replace("a\b\c", "\", "\\", "q")</code> returns <code>"a\\b\\c"</code></p><p><code>fn:replace("a/b/c", "/", "$", "q")</code> returns <code>"a$b$c"</code></p><p><code>fn:matches("abcd", ".*", "q")</code> returns <code>false()</code></p><p><code>fn:matches("Mr. B. Obama", "B. OBAMA", "iq")</code> returns <code>true()</code></p></item></ulist></div3><div3 id="func-matches"><head>fn:matches</head><glist><gitem><label>Summary</label><def><p>Returns true if the supplied string matches a given regular expression.</p></def></gitem><gitem><label>Signatures</label><def><example role="signature"><proto name="matches" return-type="xs:boolean" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="input" type="xs:string?"/><arg name="pattern" type="xs:string"/></proto></example><example role="signature"><proto name="matches" return-type="xs:boolean" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="input" type="xs:string?"/><arg name="pattern" type="xs:string"/><arg name="flags" type="xs:string"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>The effect of calling the first version of this function (omitting the argument
               <code>$flags</code>) is the same as the effect of calling the second version with the
               <code>$flags</code> argument set to a zero-length string. Flags are defined in
               <specref ref="flags"/>.</p><p>If <code>$input</code> is the empty sequence, it is interpreted as the zero-length
            string.</p><p>The function returns <code>true</code> if <code>$input</code> or some substring of
               <code>$input</code> matches the regular expression supplied as <code>$pattern</code>.
            Otherwise, the function returns <code>false</code>. The matching rules are influenced by
            the value of <code>$flags</code> if present. </p></def></gitem><gitem><label>Error Conditions</label><def><p>A dynamic error is raised <errorref class="RX" code="0002"/> if the value of
               <code>$pattern</code> is invalid according to the rules described in <specref ref="regex-syntax"/>. </p><p>A dynamic error is raised <errorref class="RX" code="0001"/> if the value of
               <code>$flags</code> is invalid according to the rules described in <specref ref="flags"/>. </p></def></gitem><gitem><label>Notes</label><def><p role="note">Unless the metacharacters <code>^</code> and <code>$</code> are used as anchors, the
            string is considered to match the pattern if any substring matches the pattern. But if
            anchors are used, the anchors must match the start/end of the string (in string mode),
            or the start/end of a line (in multi-line mode). </p><p role="note">This is different from the behavior of patterns in <bibref ref="xmlschema-2"/>, where
            regular expressions are <emph>implicitly</emph> anchored.</p><p role="note">Regular expression matching is defined on the basis of Unicode code points; it takes no
            account of collations.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>fn:matches("abracadabra", "bra")</code> returns <code>true()</code>.</p><p>The expression <code>fn:matches("abracadabra", "^a.*a$")</code> returns <code>true()</code>.</p><p>The expression <code>fn:matches("abracadabra", "^bra")</code> returns <code>false()</code>.</p><p>Given the source document:</p><eg xml:space="preserve">let $poem := 
&lt;poem author="Wilhelm Busch"&gt;
Kaum hat dies der Hahn gesehen,
Fängt er auch schon an zu krähen:
Kikeriki! Kikikerikih!!
Tak, tak, tak! - da kommen sie.
&lt;/poem&gt;</eg><p>the following function calls produce the following results, with the
                  <code>poem</code> element as the context node:</p><p>The expression <code>fn:matches($poem, "Kaum.*krähen")</code> returns <code>false()</code>.</p><p>The expression <code>fn:matches($poem, "Kaum.*krähen", "s")</code> returns <code>true()</code>.</p><p>The expression <code>fn:matches($poem, "^Kaum.*gesehen,$", "m")</code> returns <code>true()</code>.</p><p>The expression <code>fn:matches($poem, "^Kaum.*gesehen,$")</code> returns <code>false()</code>.</p><p>The expression <code>fn:matches($poem, "kiki", "i")</code> returns <code>true()</code>.</p></def></gitem></glist></div3><div3 id="func-replace"><head>fn:replace</head><glist><gitem><label>Summary</label><def><p>Returns a string produced from the input string by replacing any substrings that match a
            given regular expression with a supplied replacement string.</p></def></gitem><gitem><label>Signatures</label><def><example role="signature"><proto name="replace" return-type="xs:string" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="input" type="xs:string?"/><arg name="pattern" type="xs:string"/><arg name="replacement" type="xs:string"/></proto></example><example role="signature"><proto name="replace" return-type="xs:string" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="input" type="xs:string?"/><arg name="pattern" type="xs:string"/><arg name="replacement" type="xs:string"/><arg name="flags" type="xs:string"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>The effect of calling the first version of this function (omitting the argument
               <code>$flags</code>) is the same as the effect of calling the second version with the
               <code>$flags</code> argument set to a zero-length string. Flags are defined in
               <specref ref="flags"/>.</p><p>The <code>$flags</code> argument is interpreted in the same manner as for the
               <code>fn:matches</code> function. </p><p>If <code>$input</code> is the empty sequence, it is interpreted as the zero-length
            string.</p><p>The function returns the <code>xs:string</code> that is obtained by replacing each
            non-overlapping substring of <code>$input</code> that matches the given
               <code>$pattern</code> with an occurrence of the <code>$replacement</code> string.</p><p>If two overlapping substrings of <code>$input</code> both match the
               <code>$pattern</code>, then only the first one (that is, the one whose first <termref def="character">character</termref> comes first in the <code>$input</code> string) is
            replaced.</p><p>If the <code>q</code> flag is present, the replacement string is used <emph>as
            is</emph>.</p><p>Otherwise, within the <code>$replacement</code> string, a variable <code>$N</code> may
            be used to refer to the substring captured by the Nth parenthesized sub-expression in
            the regular expression. For each match of the pattern, these variables are assigned the
            value of the content matched by the relevant sub-expression, and the modified
            replacement string is then substituted for the <termref def="character">characters</termref> in <code>$input</code> that matched the pattern.
               <code>$0</code> refers to the substring captured by the regular expression as a
            whole.</p><p>More specifically, the rules are as follows, where <code>S</code> is the number of
            parenthesized sub-expressions in the regular expression, and <code>N</code> is the
            decimal number formed by taking all the digits that consecutively follow the
               <code>$</code> character:</p><olist><item><p>If <code>N</code>=<code>0</code>, then the variable is replaced by the substring
                  matched by the regular expression as a whole.</p></item><item><p>If <code>1</code>&lt;=<code>N</code>&lt;=<code>S</code>, then the variable is
                  replaced by the substring captured by the Nth parenthesized sub-expression. If the
                     <code>Nth</code> parenthesized sub-expression was not matched, then the
                  variable is replaced by the zero-length string.</p></item><item><p>If <code>S</code>&lt;<code>N</code>&lt;=<code>9</code>, then the variable is
                  replaced by the zero-length string.</p></item><item><p>Otherwise (if <code>N</code>&gt;<code>S</code> and
                     <code>N</code>&gt;<code>9</code>), the last digit of <code>N</code> is taken to
                  be a literal character to be included "as is" in the replacement string, and the
                  rules are reapplied using the number <code>N</code> formed by stripping off this
                  last digit.</p></item></olist><p>For example, if the replacement string is 
               <code>"$23"</code>
             and there are 5 substrings, the result contains the value of the substring that
            matches the second sub-expression, followed by the digit 
               <code>3</code>.</p><p>Unless the <code>q</code> flag is used, a literal <code>$</code> character within the
            replacement string must be written as <code>\$</code>, and a literal <code>\</code>
            character must be written as <code>\\</code>.</p><p> If two alternatives within the pattern both match at the same position in the
               <code>$input</code>, then the match that is chosen is the one matched by the first
            alternative. For example:</p><eg xml:space="preserve"> fn:replace("abcd", "(ab)|(a)", "[1=$1][2=$2]") returns "[1=ab][2=]cd"</eg></def></gitem><gitem><label>Error Conditions</label><def><p>A dynamic error is raised <errorref class="RX" code="0002"/> if the value of
               <code>$pattern</code> is invalid according to the rules described in section <specref ref="regex-syntax"/>. </p><p>A dynamic error is raised <errorref class="RX" code="0001"/> if the value of
               <code>$flags</code> is invalid according to the rules described in section <specref ref="flags"/>. </p><p>A dynamic error is raised <errorref class="RX" code="0003"/> if the pattern matches a
            zero-length string, that is, if the expression <code>fn:matches("", $pattern,
               $flags)</code> returns <code>true</code>. It is not an error, however, if a captured
            substring is zero-length.</p><p><phrase diff="add" at="E">In the absence of the <code>q</code> flag,</phrase>
            a dynamic error is raised <errorref class="RX" code="0004"/> if the value of
               <code>$replacement</code> contains a dollar sign (<code>$</code>) character that is not
            immediately followed by a digit <code>0-9</code> and not immediately preceded by a
            backslash (<code>\</code>).</p><p><phrase diff="add" at="E">In the absence of the <code>q</code> flag,</phrase>
            a dynamic error is raised <errorref class="RX" code="0004"/> if the value of
               <code>$replacement</code> contains a backslash (<code>\</code>) character that is not part of a
               <code>\\</code> pair, unless it is immediately followed by a dollar sign (<code>$</code>)
            character.</p></def></gitem><gitem><label>Notes</label><def><p role="note"><!--bug 10261-->If the input string contains no substring that matches the regular
            expression, the result of the function is a single string identical to the input
            string.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>fn:replace("abracadabra", "bra", "*")</code> returns <code>"a*cada*"</code>.</p><p>The expression <code>fn:replace("abracadabra", "a.*a", "*")</code> returns <code>"*"</code>.</p><p>The expression <code>fn:replace("abracadabra", "a.*?a", "*")</code> returns <code>"*c*bra"</code>.</p><p>The expression <code>fn:replace("abracadabra", "a", "")</code> returns <code>"brcdbr"</code>.</p><p>The expression <code>fn:replace("abracadabra", "a(.)", "a$1$1")</code> returns <code>"abbraccaddabbra"</code>.</p><p>The expression <code>fn:replace("abracadabra", ".*?", "$1")</code> raises an error,
               because the pattern matches the zero-length string </p><p>The expression <code>fn:replace("AAAA", "A+", "b")</code> returns <code>"b"</code>.</p><p>The expression <code>fn:replace("AAAA", "A+?", "b")</code> returns <code>"bbbb"</code>.</p><p>The expression <code>fn:replace("darted", "^(.*?)d(.*)$", "$1c$2")</code> returns <code>"carted"</code>. <emph>(The first <code>d</code> is replaced.)</emph></p></def></gitem></glist></div3><div3 id="func-tokenize"><head>fn:tokenize</head><glist><gitem><label>Summary</label><def><p>Returns a sequence of strings constructed by splitting the input wherever a separator is
            found; the separator is any substring that matches a given regular expression.</p></def></gitem><gitem><label>Signatures</label><def><example role="signature"><proto name="tokenize" return-type="xs:string*" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="input" type="xs:string?"/></proto></example><example role="signature"><proto name="tokenize" return-type="xs:string*" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="input" type="xs:string?"/><arg name="pattern" type="xs:string"/></proto></example><example role="signature"><proto name="tokenize" return-type="xs:string*" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="input" type="xs:string?"/><arg name="pattern" type="xs:string"/><arg name="flags" type="xs:string"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p diff="add" at="B">The one-argument form of this function
         splits the supplied string at whitespace boundaries. More specifically, calling <code>fn:tokenize($input)</code>
         is equivalent to calling <code>fn:tokenize(fn:normalize-space($input), ' '))</code> where the second argument
         is a single space character (x20).</p><p>The effect of calling the two-argument form of this function (omitting the argument
               <code>$flags</code>) is the same as the effect of calling the three-argument version with the
               <code>$flags</code> argument set to a zero-length string. Flags are defined in
               <specref ref="flags"/>.</p><p>The following rules apply to the three-argument form of the function:</p><ulist><item><p>The <code>$flags</code> argument is interpreted in the same way as for the
               <code>fn:matches</code> function.</p></item><item><p>If <code>$input</code> is the empty sequence, or if <code>$input</code> is the
            zero-length string, the function returns the empty sequence.</p></item><item><p>The function returns a sequence of strings formed by breaking the <code>$input</code>
            string into a sequence of strings, treating any substring that matches
               <code>$pattern</code> as a separator. The separators themselves are not returned.</p></item><item><p><phrase diff="chg" at="B">Except with the one-argument form of the function,</phrase>
            if a separator occurs at the start of the <code>$input</code> string, the result
            sequence will start with a zero-length string. Similarly, zero-length strings will also occur in
            the result sequence if a separator occurs at the end of the <code>$input</code> string,
            or if two adjacent substrings match the supplied <code>$pattern</code>.</p></item><item><p>If two alternatives within the supplied <code>$pattern</code> both match at the same
            position in the <code>$input</code> string, then the match that is chosen is the first.
            For example:</p><eg xml:space="preserve"> fn:tokenize("abracadabra", "(ab)|(a)") returns ("", "r", "c", "d", "r", "")</eg></item></ulist></def></gitem><gitem><label>Error Conditions</label><def><p>A dynamic error is raised <errorref class="RX" code="0002"/> if the value of
               <code>$pattern</code> is invalid according to the rules described in section <specref ref="regex-syntax"/>.</p><p>A dynamic error is raised <errorref class="RX" code="0001"/> if the value of
               <code>$flags</code> is invalid according to the rules described in section <specref ref="flags"/>.</p><p>A dynamic error is raised <errorref class="RX" code="0003"/> if the supplied
               <code>$pattern</code> matches a zero-length string, that is, if <code>fn:matches("",
               $pattern, $flags)</code> returns <code>true</code>. </p></def></gitem><gitem><label>Notes</label><def><p role="note"><!--bug 10261-->If the input string is not zero length, and no separators are found in
            the input string, the result of the function is a single string identical to the input
            string.</p><p role="note">The one-argument form of the function has a similar effect to
         the two-argument form with <code>\s+</code> as the separator pattern, except that the one-argument
         form strips leading and trailing whitespace, whereas the two-argument form delivers an extra
         zero-length token if leading or trailing whitespace is present.</p><p role="note">The function returns no information about the separators that were found
         in the string. If this information is required, the <code>fn:analyze-string</code> function
         can be used instead.</p><p role="note">The separator used by the one-argument form of the function is any sequence
            of tab (x09), newline (x0A), carriage return (x0D) or space (x20) characters. This is the same as the
         separator recognized by list-valued attributes as defined in XSD. It is not the same as the separator
         recognized by list-valued attributes in HTML5, which also treats form-feed (x0C) as whitespace.
         If it is necessary to treat form-feed as a separator, an explicit separator pattern should be used.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>fn:tokenize(" red green blue ")</code> returns <code>("red", "green", "blue")</code>.</p><p>The expression <code>fn:tokenize("The cat sat on the mat", "\s+")</code> returns <code>("The", "cat", "sat", "on", "the", "mat")</code>.</p><p>The expression <code>fn:tokenize(" red green blue ", "\s+")</code> returns <code>("", "red", "green", "blue", "")</code>.</p><p>The expression <code>fn:tokenize("1, 15, 24, 50", ",\s*")</code> returns <code>("1", "15", "24", "50")</code>.</p><p>The expression <code>fn:tokenize("1,15,,24,50,", ",")</code> returns <code>("1", "15", "", "24", "50", "")</code>.</p><p><code>fn:tokenize("abba", ".?")</code> raises the dynamic error <errorref class="RX" code="0003"/>.</p><p>The expression <code>fn:tokenize("Some unparsed &lt;br&gt; HTML &lt;BR&gt; text",
                  "\s*&lt;br&gt;\s*", "i")</code> returns <code>("Some unparsed", "HTML", "text")</code>.</p></def></gitem></glist></div3><div3 id="func-analyze-string"><head>fn:analyze-string</head><glist><gitem><label>Summary</label><def><p>Analyzes a string using a regular expression, returning an XML structure that identifies
            which parts of the input string matched or failed to match the regular expression, and
            in the case of matched substrings, which substrings matched each capturing group in the
            regular expression.</p></def></gitem><gitem><label>Signatures</label><def><example role="signature"><proto name="analyze-string" return-type="element(fn:analyze-string-result)" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="input" type="xs:string?"/><arg name="pattern" type="xs:string"/></proto></example><example role="signature"><proto name="analyze-string" return-type="element(fn:analyze-string-result)" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="input" type="xs:string?"/><arg name="pattern" type="xs:string"/><arg name="flags" type="xs:string"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-nondeterministic">nondeterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>The effect of calling the first version of this function (omitting the argument
               <code>$flags</code>) is the same as the effect of calling the second version with the
               <code>$flags</code> argument set to a zero-length string. Flags are defined in
               <specref ref="flags"/>.</p><p>The <code>$flags</code> argument is interpreted in the same way as for the
               <code>fn:matches</code> function.</p><p>If <code>$input</code> is the empty sequence the function behaves as if
               <code>$input</code> were the zero-length string. In this situation the result will be
            an element node with no children.</p><p>The function returns an element node whose local name is
               <code>analyze-string-result</code>. This element and all its descendant elements have
            the namespace URI <code>http://www.w3.org/2005/xpath-functions</code>. The namespace
            prefix is <termref def="implementation-dependent">implementation-dependent</termref>. The children of this element are a
            sequence of <code>fn:match</code> and <code>fn:non-match</code> elements. This sequence
            is formed by breaking the <code>$input</code> string into a sequence of strings,
            returning any substring that matches <code>$pattern</code> as the content of a
               <code>match</code> element, and any intervening substring as the content of a
               <code>non-match</code> element.</p><p>More specifically, the function starts at the beginning of the input string and attempts
            to find the first substring that matches the regular expression. If there are several
            matches, the first match is defined to be the one whose starting position comes first in
            the string. If several alternatives within the regular expression both match at the same
            position in the input string, then the match that is chosen is the first alternative
            that matches. For example, if the input string is <code>The quick brown fox jumps</code>
            and the regular expression is <code>jump|jumps</code>, then the match that is chosen is
               <code>jump</code>.</p><p>Having found the first match, the instruction proceeds to find the second and subsequent
            matches by repeating the search, starting at the first <termref def="character">character</termref> that was not included in the previous match.</p><p>The input string is thus partitioned into a sequence of substrings, some of which match
            the regular expression, others which do not match it. Each substring will contain at
            least one character. This sequence is represented in the result by the sequence of
               <code>fn:match</code> and <code>fn:non-match</code> children of the returned element
            node; the string value of the <code>fn:match</code> or <code>fn:non-match</code> element
            will be the corresponding substring of <code>$input</code>, and the string value of the
            returned element node will therefore be the same as <code>$input</code>.</p><p>The content of an <code>fn:non-match</code> element is always a single text node.</p><p>The content of a <code>fn:match</code> element, however, is in general a sequence of
            text nodes and <code>fn:group</code> element children. An <code>fn:group</code> element
            with a <code>nr</code> attribute having the integer value <var>N</var> identifies the
            substring captured by the <var>Nth</var> parenthesized sub-expression in the regular
            expression. For each capturing subexpression there will be at most one corresponding
               <code>fn:group</code> element in each <code>fn:match</code> element in the
            result.</p><p>If the function is called twice with the same arguments, it is <termref def="implementation-dependent">implementation-dependent</termref> whether the two calls return the same element node
            or distinct (but deep equal) element nodes. In this respect it is <termref def="nondeterministic">non-deterministic with respect to node identity</termref>.</p><p>The base URI of the element nodes in the result is <termref def="implementation-dependent">implementation-dependent</termref>.</p><p>A schema is defined for the structure of the returned element: see <specref ref="schema-for-analyze-string"/>.</p><p diff="chg" at="D">The result of the function will always be such that validation against this schema would succeed.
         However, it is <termref def="dt-implementation-defined">implementation-defined</termref> whether the result is typed or untyped,
         that is, whether the elements and attributes in the returned tree have type annotations that reflect
         the result of validating against this schema.</p></def></gitem><gitem><label>Error Conditions</label><def><p>A dynamic error is raised <errorref class="RX" code="0002"/> if the value of
               <code>$pattern</code> is invalid according to the rules described in section <specref ref="regex-syntax"/>.</p><p>A dynamic error is raised <errorref class="RX" code="0001"/> if the value of
               <code>$flags</code> is invalid according to the rules described in section <specref ref="flags"/>.</p><p>A dynamic error is raised <errorref class="RX" code="0003"/> if the supplied
               <code>$pattern</code> matches a zero-length string, that is, if <code>fn:matches("",
               $pattern, $flags)</code> returns <code>true</code>.</p></def></gitem><gitem><label>Notes</label><def><p role="note">It is <rfc2119>recommended</rfc2119> that a processor that implements schema awareness should return typed nodes.
            The concept of "schema awareness", however, is a matter for host languages to define and is outside
            the scope of the function library specification.</p><p role="note">The declarations and definitions in the schema are not automatically available in
            the static context of the <code>fn:analyze-string</code> call (or of any other
            expression). The contents of the static context are host-language defined, and in some
            host languages are implementation-defined.</p><p role="note">The schema defines the outermost element, <code>analyze-string-result</code>, in such
         a way that mixed content is permitted. In fact the element will only have element nodes (<code>match</code>
         and <code>non-match</code>) as its children, never text nodes. Although this might have originally been an
            oversight, defining the <code>analyze-string-result</code> element with <code>mixed="true"</code> allows it
         to be atomized, which is potentially useful (the atomized value will be the original input string),
         and the capability has therefore been retained for compatibility with the 3.0 version of this
         specification.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>In the following examples, the result document is shown in serialized form, with
               whitespace between the element nodes. This whitespace is not actually present in the
               result.</p><p>The expression <code>fn:analyze-string("The cat sat on the mat.", "\w+")</code> returns (with whitespace added for legibility):</p><eg xml:space="preserve">
&lt;analyze-string-result xmlns="http://www.w3.org/2005/xpath-functions"&gt;
  &lt;match&gt;The&lt;/match&gt;
  &lt;non-match&gt; &lt;/non-match&gt;
  &lt;match&gt;cat&lt;/match&gt;
  &lt;non-match&gt; &lt;/non-match&gt;
  &lt;match&gt;sat&lt;/match&gt;
  &lt;non-match&gt; &lt;/non-match&gt;
  &lt;match&gt;on&lt;/match&gt;
  &lt;non-match&gt; &lt;/non-match&gt;
  &lt;match&gt;the&lt;/match&gt;
  &lt;non-match&gt; &lt;/non-match&gt;
  &lt;match&gt;mat&lt;/match&gt;
  &lt;non-match&gt;.&lt;/non-match&gt;
&lt;/analyze-string-result&gt;</eg><p>The expression <code>fn:analyze-string("2008-12-03",
                  "^(\d+)\-(\d+)\-(\d+)$")</code> returns (with whitespace added for legibility):</p><eg xml:space="preserve">
&lt;analyze-string-result xmlns="http://www.w3.org/2005/xpath-functions"&gt;
  &lt;match&gt;&lt;group nr="1"&gt;2008&lt;/group&gt;-&lt;group nr="2"
          &gt;12&lt;/group&gt;-&lt;group nr="3"&gt;03&lt;/group&gt;&lt;/match&gt;
&lt;/analyze-string-result&gt;</eg><p>The expression <code>fn:analyze-string("A1,C15,,D24, X50,",
                  "([A-Z])([0-9]+)")</code> returns (with whitespace added for legibility):</p><eg xml:space="preserve">
&lt;analyze-string-result xmlns="http://www.w3.org/2005/xpath-functions"&gt;                  
  &lt;match&gt;&lt;group nr="1"&gt;A&lt;/group&gt;&lt;group nr="2"&gt;1&lt;/group&gt;&lt;/match&gt;
  &lt;non-match&gt;,&lt;/non-match&gt;
  &lt;match&gt;&lt;group nr="1"&gt;C&lt;/group&gt;&lt;group nr="2"&gt;15&lt;/group&gt;&lt;/match&gt;
  &lt;non-match&gt;,,&lt;/non-match&gt;
  &lt;match&gt;&lt;group nr="1"&gt;D&lt;/group&gt;&lt;group nr="2"&gt;24&lt;/group&gt;&lt;/match&gt;
  &lt;non-match&gt;, &lt;/non-match&gt;
  &lt;match&gt;&lt;group nr="1"&gt;X&lt;/group&gt;&lt;group nr="2"&gt;50&lt;/group&gt;&lt;/match&gt;
  &lt;non-match&gt;,&lt;/non-match&gt;
&lt;/analyze-string-result&gt;</eg></def></gitem></glist></div3></div2></div1><div1 id="anyURI-functions"><head>Functions that manipulate URIs</head><p>This section specifies functions that manipulate URI values, either as instances
            of <code>xs:anyURI</code> or as strings.</p><table class="index"><thead><tr><th rowspan="1" colspan="1">Function</th><th rowspan="1" colspan="1">Meaning</th></tr></thead><tbody><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:resolve-uri</code></td><td rowspan="1" colspan="1">Resolves a relative IRI reference against an absolute IRI.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:encode-for-uri</code></td><td rowspan="1" colspan="1">Encodes reserved characters in a string that is intended to be used in the path segment
            of a URI.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:iri-to-uri</code></td><td rowspan="1" colspan="1">Converts a string containing an IRI into a URI according to the rules of <bibref ref="rfc3987"/>.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:escape-html-uri</code></td><td rowspan="1" colspan="1">Escapes a URI in the same way that HTML user agents handle attribute values expected to
            contain URIs.</td></tr></tbody></table><div2 id="func-resolve-uri"><head>fn:resolve-uri</head><glist><gitem><label>Summary</label><def><p>Resolves a relative IRI reference against an absolute IRI.</p></def></gitem><gitem><label>Signatures</label><def><example role="signature"><proto name="resolve-uri" return-type="xs:anyURI?" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="relative" type="xs:string?"/></proto></example><example role="signature"><proto name="resolve-uri" return-type="xs:anyURI?" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="relative" type="xs:string?"/><arg name="base" type="xs:string"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>The one-argument form of this function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-dependent">context-dependent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>.  It depends on 
		static base URI.
	</p><p>The two-argument form of this function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>The function is defined to operate on IRI references as defined in <bibref ref="rfc3987"/>, and the implementation <rfc2119>must</rfc2119> permit all arguments that are valid
            according to that specification. In addition, the implementation <rfc2119>may</rfc2119>
            accept some or all strings that conform to the rules for (absolute or relative) Legacy
            Extended IRI references as defined in <bibref ref="LEIRI"/>. For the purposes of this
            section, the terms IRI and IRI reference include these extensions, insofar as the
            implementation chooses to support them.</p><p>The following rules apply in order:</p><olist diff="chg" at="B"><item><p>If <code>$relative</code> is the empty sequence, the function returns the empty
               sequence.</p></item><item><p>If <code>$relative</code> is an absolute IRI (as defined above), then it is returned
               unchanged.</p></item><item><p>If the <code>$base</code> argument is not supplied, then:</p><olist><item><p>If the static base URI in the static context is not absent, it is used as the effective
               value of <code>$base</code>.</p></item><item><p>Otherwise, a dynamic error is raised: <phrase diff="chg" at="D"><errorref class="NS" code="0005"/></phrase>.</p></item></olist></item><item><p>The function resolves the relative IRI reference <code>$relative</code>
               against the base IRI <code>$base</code> using the algorithm defined in <bibref ref="rfc3986"/>, adapted by treating any <termref def="character">character</termref>
               that would not be valid in an RFC3986 URI or relative reference in the same way that
               RFC3986 treats unreserved characters. No percent-encoding takes place.</p></item></olist></def></gitem><gitem><label>Error Conditions</label><def><p>The first form of this function resolves <code>$relative</code> against the value of the
            base-uri property from the static context. A dynamic error is raised <errorref class="NS" code="0005"/> if the base-uri property is not initialized in the static
            context. </p><p>A dynamic error is raised <errorref class="RG" code="0002"/> if <code>$relative</code>
            is not a valid IRI according to the rules of RFC3987, extended with an
            implementation-defined subset of the extensions permitted in LEIRI, or if it is not a
            suitable relative reference to use as input to the RFC3986 resolution algorithm extended
            to handle additional unreserved characters. </p><p>A dynamic error is raised <errorref class="RG" code="0002"/> if <code>$base</code> is
            not a valid IRI according to the rules of RFC3987, extended with an
            implementation-defined subset of the extensions permitted in LEIRI, or if it is not a
            suitable IRI to use as input to the chosen resolution algorithm (for example, if it is a
            relative IRI reference, if it is a non-hierarchic URI, or if it contains a fragment
            identifier). </p><p>A dynamic error is raised <errorref class="RG" code="0009"/> if the chosen resolution
            algorithm fails for any other reason. </p></def></gitem><gitem><label>Notes</label><def><p role="note">Resolving a URI does not dereference it. This is merely a syntactic operation on two
               <termref def="string">strings</termref>.</p><p role="note">The algorithms in the cited RFCs include some variations that are optional or
            recommended rather than mandatory; they also describe some common practices that are not
            recommended, but which are permitted for backwards compatibility. Where the cited RFCs
            permit variations in behavior, so does this specification. </p><p role="note">Throughout this family of specifications, the phrase "resolving a relative URI (or IRI)
            reference" should be understood as using the rules of this function, unless otherwise
            stated.</p><p role="note">RFC3986 defines an algorithm for resolving relative references 
            in the context of the URI syntax defined in that RFC. RFC3987 describes a modification 
            to that algorithm to make it applicable to IRIs (specifically: additional characters 
            permitted in an IRI are handled the same way that RFC3986 handles unreserved characters). 
            The LEIRI specification does not explicitly define a resolution algorithm, but suggests 
            that it <emph>should not</emph> be done by converting the LEIRI to a URI, and 
            <emph>should not</emph> involve percent-encoding. This specification fills this gap 
            by defining resolution for LEIRIs in the same way that RFC3987 defines resolution for IRIs,
            that is by specifying that additional characters are handled as unreserved characters.</p></def></gitem></glist></div2><div2 id="func-encode-for-uri"><head>fn:encode-for-uri</head><glist><gitem><label>Summary</label><def><p>Encodes reserved characters in a string that is intended to be used in the path segment
            of a URI.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="encode-for-uri" return-type="xs:string" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="uri-part" type="xs:string?"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>If <code>$uri-part</code> is the empty sequence, the function returns the zero-length
            string.</p><p>This function applies the URI escaping rules defined in section 2 of <bibref ref="rfc3986"/> to the <code>xs:string</code> supplied as <code>$uri-part</code>. The
            effect of the function is to escape reserved characters. Each such character in the
            string is replaced with its percent-encoded form as described in <bibref ref="rfc3986"/>.</p><p>Since <bibref ref="rfc3986"/> recommends that, for consistency, URI producers and
            normalizers should use uppercase hexadecimal digits for all percent-encodings, this
            function must always generate hexadecimal values using the upper-case letters A-F.</p></def></gitem><gitem><label>Notes</label><def><p role="note">All characters are escaped except those identified as "unreserved" by <bibref ref="rfc3986"/>, that is the upper- and lower-case letters A-Z, the digits 0-9,
            HYPHEN-MINUS ("-"), LOW LINE ("_"), FULL STOP ".", and TILDE "~".</p><p role="note">This function escapes URI delimiters and therefore cannot be used indiscriminately to
            encode "invalid" characters in a path segment.</p><p role="note">This function is invertible but not idempotent. This is because a string containing a
            percent character will be modified by applying the function: for example
               <code>100%</code> becomes <code>100%25</code>, while <code>100%25</code> becomes
               <code>100%2525</code>.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>fn:encode-for-uri("http://www.example.com/00/Weather/CA/Los%20Angeles#ocean")</code> returns <code>"http%3A%2F%2Fwww.example.com%2F00%2FWeather%2FCA%2FLos%2520Angeles%23ocean"</code>. <emph>(This is probably not what the user intended because all of the
                  delimiters have been encoded.)</emph></p><p>The expression <code>concat("http://www.example.com/",
                  encode-for-uri("~bébé"))</code> returns <code>"http://www.example.com/~b%C3%A9b%C3%A9"</code>.</p><p>The expression <code>concat("http://www.example.com/", encode-for-uri("100% organic"))</code> returns <code>"http://www.example.com/100%25%20organic"</code>.</p></def></gitem></glist></div2><div2 id="func-iri-to-uri"><head>fn:iri-to-uri</head><glist><gitem><label>Summary</label><def><p>Converts a string containing an IRI into a URI according to the rules of <bibref ref="rfc3987"/>.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="iri-to-uri" return-type="xs:string" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="iri" type="xs:string?"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>If <code>$iri</code> is the empty sequence, the function returns the zero-length
            string.</p><p>Otherwise, the function converts the value of <code>$iri</code> into a URI according to
            the rules given in Section 3.1 of <bibref ref="rfc3987"/> by percent-encoding characters
            that are allowed in an IRI but not in a URI. If <code>$iri</code> contains a character
            that is invalid in an IRI, such as the space character (see note below), the invalid
            character is replaced by its percent-encoded form as described in <bibref ref="rfc3986"/> before the conversion is performed.</p><p>Since <bibref ref="rfc3986"/> recommends that, for consistency, URI producers and
            normalizers should use uppercase hexadecimal digits for all percent-encodings, this
            function must always generate hexadecimal values using the upper-case letters A-F.</p></def></gitem><gitem><label>Notes</label><def><p role="note">The function is idempotent but not invertible. Both the inputs <code>My Documents</code>
            and <code>My%20Documents</code> will be converted to the output
               <code>My%20Documents</code>.</p><p role="note">This function does not check whether <code>$iri</code> is a valid IRI. It treats it as
            an <termref def="string">string</termref> and operates on the <termref def="character">characters</termref> in the string.</p><p role="note"> The following printable ASCII characters are invalid in an IRI: "&lt;", "&gt;", <quote>
               " </quote> (double quote), space, "{", "}", "|", "\", "^", and "`". Since these
            characters should not appear in an IRI, if they do appear in <code>$iri</code> they will
            be percent-encoded. In addition, characters outside the range x20-x7E will be
            percent-encoded because they are invalid in a URI. </p><p role="note"> Since this function does not escape the PERCENT SIGN "%" and this character is not
            allowed in data within a URI, users wishing to convert character strings (such as file
            names) that include "%" to a URI should manually escape "%" by replacing it with "%25".
         </p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>fn:iri-to-uri
                  ("http://www.example.com/00/Weather/CA/Los%20Angeles#ocean")</code> returns <code>"http://www.example.com/00/Weather/CA/Los%20Angeles#ocean"</code>.</p><p>The expression <code>fn:iri-to-uri ("http://www.example.com/~bébé")</code> returns <code>"http://www.example.com/~b%C3%A9b%C3%A9"</code>.</p></def></gitem></glist></div2><div2 id="func-escape-html-uri"><head>fn:escape-html-uri</head><glist><gitem><label>Summary</label><def><p>Escapes a URI in the same way that HTML user agents handle attribute values expected to
            contain URIs.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="escape-html-uri" return-type="xs:string" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="uri" type="xs:string?"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>If <code>$uri</code> is the empty sequence, the function returns the zero-length
            string.</p><p>Otherwise, the function escapes all <termref def="character">characters</termref> except
            printable characters of the US-ASCII coded character set, specifically the <termref def="codepoint">codepoints</termref> between 32 and 126 (decimal) inclusive. Each
            character in <code>$uri</code> to be escaped is replaced by an escape sequence, which is
            formed by encoding the character as a sequence of octets in UTF-8, and then representing
            each of these octets in the form %HH, where HH is the hexadecimal representation of the
            octet. This function must always generate hexadecimal values using the upper-case
            letters A-F.</p></def></gitem><gitem><label>Notes</label><def><p role="note">The behavior of this function corresponds to the recommended handling of non-ASCII
            characters in URI attribute values as described in <bibref ref="HTML40"/> Appendix
            B.2.1.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>fn:escape-html-uri("http://www.example.com/00/Weather/CA/Los Angeles#ocean")</code> returns <code>"http://www.example.com/00/Weather/CA/Los Angeles#ocean"</code>.</p><p>The expression <code>fn:escape-html-uri("javascript:if (navigator.browserLanguage == 'fr') window.open('http://www.example.com/~bébé');")</code> returns <code>"javascript:if (navigator.browserLanguage == 'fr') window.open('http://www.example.com/~b%C3%A9b%C3%A9');"</code>.</p></def></gitem></glist></div2></div1><div1 id="boolean-functions"><head>Functions and operators on Boolean values</head><p>This section defines functions and operators on the <code>xs:boolean</code> datatype.</p><div2 id="boolean-constructors"><head>Boolean constant functions</head><p>Since no literals are defined in XPath to reference the constant boolean values true and false,
			two functions are provided for the purpose.</p><table class="index"><thead><tr><th rowspan="1" colspan="1">Function</th><th rowspan="1" colspan="1">Meaning</th></tr></thead><tbody><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:true</code></td><td rowspan="1" colspan="1">Returns the <code>xs:boolean</code> value <code>true</code>.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:false</code></td><td rowspan="1" colspan="1">Returns the <code>xs:boolean</code> value <code>false</code>.</td></tr></tbody></table><div3 id="func-true"><head>fn:true</head><glist><gitem><label>Summary</label><def><p>Returns the <code>xs:boolean</code> value <code>true</code>.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="true" return-type="xs:boolean" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"/></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>The result is equivalent to <code>xs:boolean("1")</code>.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>fn:true()</code> returns <code>xs:boolean(1)</code>.</p></def></gitem></glist></div3><div3 id="func-false"><head>fn:false</head><glist><gitem><label>Summary</label><def><p>Returns the <code>xs:boolean</code> value <code>false</code>.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="false" return-type="xs:boolean" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"/></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>The result is equivalent to <code>xs:boolean("0")</code>.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>fn:false()</code> returns <code>xs:boolean(0)</code>.</p></def></gitem></glist></div3></div2><div2 id="op.boolean"><head>Operators on Boolean values</head><p>The following functions define the semantics of operators on boolean values in
                        <bibref ref="xquery-31"/> and <bibref ref="xpath-31"/>:</p><table class="index"><thead><tr><th rowspan="1" colspan="1">Function</th><th rowspan="1" colspan="1">Meaning</th></tr></thead><tbody><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">op:boolean-equal</code></td><td rowspan="1" colspan="1">Returns <code>true</code> if the two arguments are the same boolean value.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">op:boolean-less-than</code></td><td rowspan="1" colspan="1">Returns true if the first argument is false and the second is true.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">op:boolean-greater-than</code></td><td rowspan="1" colspan="1">Returns true if the first argument is true and the second is false.</td></tr></tbody></table><p>The ordering operators <code>op:boolean-less-than</code>
                    and <code>op:boolean-greater-than</code> are provided for application purposes
                    and for compatibility with <bibref ref="xpath"/>. The <bibref ref="xmlschema-2"/>
                    datatype <code>xs:boolean</code> is not ordered.</p><div3 id="func-boolean-equal"><head>op:boolean-equal</head><glist><gitem><label>Summary</label><def><p>Returns <code>true</code> if the two arguments are the same boolean value.</p></def></gitem><gitem><label>Operator Mapping</label><def><p>Defines the semantics of the "eq"
         operator when applied to two <code>xs:boolean</code> values.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="boolean-equal" return-type="xs:boolean" isOp="yes" prefix="op" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="value1" type="xs:boolean"/><arg name="value2" type="xs:boolean"/></proto></example></def></gitem><gitem><label>Rules</label><def><p>The function returns <code>true</code> if both arguments are <code>true</code> or if
            both arguments are <code>false</code>. It returns <code>false</code> if one of the
            arguments is <code>true</code> and the other argument is <code>false</code>. </p></def></gitem></glist></div3><div3 id="func-boolean-less-than"><head>op:boolean-less-than</head><glist><gitem><label>Summary</label><def><p>Returns true if the first argument is false and the second is true.</p></def></gitem><gitem><label>Operator Mapping</label><def><p>Defines the
         semantics of the "lt" operator when applied to two <code>xs:boolean</code> values. Also
         used in the definition of the "ge" operator.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="boolean-less-than" return-type="xs:boolean" isOp="yes" prefix="op" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg1" type="xs:boolean"/><arg name="arg2" type="xs:boolean"/></proto></example></def></gitem><gitem><label>Rules</label><def><p>The function returns <code>true</code> if <code>$arg1</code> is <code>false</code> and
               <code>$arg2</code> is <code>true</code>. Otherwise, it returns
            <code>false</code>.</p></def></gitem></glist></div3><div3 id="func-boolean-greater-than"><head>op:boolean-greater-than</head><glist><gitem><label>Summary</label><def><p>Returns true if the first argument is true and the second is false.</p></def></gitem><gitem><label>Operator Mapping</label><def><p>Defines the
         semantics of the "gt" operator when applied to two <code>xs:boolean</code> values. Also
         used in the definition of the "le" operator.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="boolean-greater-than" return-type="xs:boolean" isOp="yes" prefix="op" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg1" type="xs:boolean"/><arg name="arg2" type="xs:boolean"/></proto></example></def></gitem><gitem><label>Rules</label><def><p>The function call <code>op:boolean-greater-than($A, $B)</code> is defined to return the
            same result as <code>op:boolean-less-than($B, $A)</code></p></def></gitem></glist></div3></div2><div2 id="boolean-value-functions"><head>Functions on Boolean values</head><p>The following functions are defined on boolean values:</p><table class="index"><thead><tr><th rowspan="1" colspan="1">Function</th><th rowspan="1" colspan="1">Meaning</th></tr></thead><tbody><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:boolean</code></td><td rowspan="1" colspan="1">Computes the effective boolean value of the sequence <code>$arg</code>.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:not</code></td><td rowspan="1" colspan="1">Returns <code>true</code> if the effective boolean value of <code>$arg</code> is
               <code>false</code>, or <code>false</code> if it is <code>true</code>.</td></tr></tbody></table><div3 id="func-boolean"><head>fn:boolean</head><glist><gitem><label>Summary</label><def><p>Computes the effective boolean value of the sequence <code>$arg</code>.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="boolean" return-type="xs:boolean" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg" type="item()*"/></proto></example></def></gitem><gitem><label>Rules</label><def><p>The function computes the effective boolean value of a sequence, defined according to
            the following rules. See also <xspecref spec="XP31" ref="id-ebv"/>.</p><ulist><item><p>If <code>$arg</code> is the empty sequence, <code>fn:boolean</code> returns
                     <code>false</code>.</p></item><item><p>If <code>$arg</code> is a sequence whose first item is a node,
                     <code>fn:boolean</code> returns <code>true</code>.</p></item><item><p>If <code>$arg</code> is a singleton value of type <code>xs:boolean</code> or a
                  derived from <code>xs:boolean</code>, <code>fn:boolean</code> returns
                     <code>$arg</code>.</p></item><item><p>If <code>$arg</code> is a singleton value of type <code>xs:string</code> or a type
                  derived from <code>xs:string</code>, <code>xs:anyURI</code> or a type derived from
                     <code>xs:anyURI</code>, or <code>xs:untypedAtomic</code>,
                     <code>fn:boolean</code> returns <code>false</code> if the operand value has
                  zero length; otherwise it returns <code>true</code>.</p></item><item><p>If <code>$arg</code> is a singleton value of any numeric type or a type derived
                  from a numeric type, <code>fn:boolean</code> returns <code>false</code> if the
                  operand value is <code>NaN</code> or is numerically equal to zero; otherwise it
                  returns <code>true</code>.</p></item></ulist></def></gitem><gitem><label>Error Conditions</label><def><p>In all cases other than those listed above, <code>fn:boolean</code> raises a type error <errorref class="RG" code="0006"/>.</p></def></gitem><gitem><label>Notes</label><def><p role="note">The result of this function is not necessarily the same as <code>$arg cast as
               xs:boolean</code>. For example, <code>fn:boolean("false")</code> returns the value
               <code>true</code> whereas <code>"false" cast as xs:boolean</code> (which can also be
            written <code>xs:boolean("false")</code>) returns <code>false</code>.</p></def></gitem><gitem><label>Examples</label><def role="example"><eg xml:space="preserve">let $abc := ("a", "b", "")</eg><p><code>fn:boolean($abc)</code> raises a type error <errorref class="RG" code="0006"/>.</p><p>The expression <code>fn:boolean($abc[1])</code> returns <code>true()</code>.</p><p>The expression <code>fn:boolean($abc[0])</code> returns <code>false()</code>.</p><p>The expression <code>fn:boolean($abc[3])</code> returns <code>false()</code>.</p><p><code>fn:boolean([])</code> raises a type error <errorref class="RG" code="0006"/>.</p></def></gitem></glist></div3><div3 id="func-not"><head>fn:not</head><glist><gitem><label>Summary</label><def><p>Returns <code>true</code> if the effective boolean value of <code>$arg</code> is
               <code>false</code>, or <code>false</code> if it is <code>true</code>.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="not" return-type="xs:boolean" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg" type="item()*"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>The value of <code>$arg</code> is first reduced to an effective boolean value by
            applying the <code>fn:boolean()</code> function. The function returns <code>true</code>
            if the effective boolean value is <code>false</code>, or <code>false</code> if the
            effective boolean value is <code>true</code>. </p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>fn:not(fn:true())</code> returns <code>false()</code>.</p><p>The expression <code>fn:not(())</code> returns <code>true()</code>.</p><p>The expression <code>fn:not("false")</code> returns <code>false()</code>.</p><p><code>fn:not(1 to 10)</code> raises a type error <errorref class="RG" code="0006"/>.</p></def></gitem></glist></div3></div2></div1><div1 id="durations"><head>Functions and operators on durations</head><p>Operators are defined on the following type:</p><ulist><item><p>xs:duration</p></item></ulist><p>and on the two defined subtypes (see <specref ref="duration-subtypes"/>):</p><ulist><item><p>xs:yearMonthDuration</p></item><item><p>xs:dayTimeDuration</p></item></ulist><p>No ordering relation is defined on <code>xs:duration</code> values.
			Two <code>xs:duration</code> values may however be compared for equality.</p><p>Operations on durations (including equality comparison, casting to string, and extraction of components) 
			all treat the duration as normalized. This means that the seconds and minutes components 
			will always be less than 60, the hours component less than 24, and the months component 
			less than 12.  Thus, for example, a duration of 120 seconds always gives the same result 
			as a duration of two minutes.</p><p>Conditions such as underflow and overflow may occur with arithmetic on
	         durations: see <specref ref="duration-limits"/> </p><note><p>This means that in practice, the information content of an <code>xs:duration</code>
			value can be reduced to an <code>xs:integer</code> number of months, and an <code>xs:decimal</code>
			number of seconds. For the two defined subtypes this is further simplified so that one of these two
			components is fixed at zero. Operations such as comparison of durations and arithmetic on durations
			can be expressed in terms of numeric operations applied to these two components.</p></note><div2 id="duration-subtypes"><head>Two totally ordered subtypes of duration</head><p diff="add" at="A">Two subtypes of <code>xs:duration</code>, namely <code>xs:yearMonthDuration</code>
               and <code>xs:dayTimeDuration</code>, are defined in <bibref ref="xmlschema11-2"/>. These types <rfc2119>must</rfc2119>
            be available in the data model whether or not the implementation supports other aspects of XSD 1.1.</p><p diff="add" at="A">The significance of these subtypes is that arithmetic and ordering become well defined; this is not the
            case for <code>xs:duration</code> values in general, because of the variable number of days in a month. For this reason, many of the functions
            and operators on durations require the arguments/operands to belong to these two subtypes.</p><p diff="del" at="B-bug25447">Two totally ordered subtypes of <code>xs:duration</code> are defined in <xspecref spec="DM31" ref="types"/>
                    specification using the mechanisms described in <bibref ref="xmlschema-2"/> for
                    defining user-defined types. Additional details about these types is given below.</p><note diff="del" at="B-bug25447"><p>These types were not defined in XSD 1.0, but they are defined in the current draft of XSD 1.1. The description given
			here is believed to be equivalent to that in XSD 1.1, and will become non-normative when XSD 1.1 reaches
			Recommendation status.</p></note><div3 id="dt-yearMonthDuration" diff="del" at="B-bug25447"><head>xs:yearMonthDuration</head><p> [Definition] <code>xs:yearMonthDuration</code> is derived from
                        <code>xs:duration</code> by restricting its lexical representation to
                        contain only the year and month components. The value space of
                        <code>xs:yearMonthDuration</code> is the set of <code>xs:integer</code>
                        month values. The year and month components of
                        <code>xs:yearMonthDuration</code> correspond to the Gregorian year and
                        month components defined in section 5.5.3.2 of <bibref ref="ISO8601"/>, respectively.</p><div4 id="lexical-yearMonthDuration"><head>Lexical representation</head><p>The lexical representation for <code>xs:yearMonthDuration</code> is the
                                <bibref ref="ISO8601"/> 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 <code>xs:integer</code>.</p><p>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 <code>xs:yearMonthDuration</code> of 1 year, 2 months, one
                            would write: P1Y2M. One could also indicate a
                            <code>xs:yearMonthDuration</code> of minus 13 months as: -P13M. </p><p>Reduced precision and truncated representations of this format are
                            allowed provided they conform to the following: </p><p>If the number of years or months in any expression equals zero (0), the
                            number and its corresponding designator <rfc2119>may</rfc2119> be omitted.
                            However, at least one number and its designator <rfc2119>must</rfc2119> be
                            present. For example, P1347Y and P1347M are allowed; P-1347M is not
                            allowed, although -P1347M is allowed. P1Y2MT is not allowed. Also, P24YM
                            is not allowed, nor is PY43M since Y must have at least one preceding
                            digit and M must have one preceding digit.</p></div4><div4 id="calculating-value-yearMonthDuration"><head>Calculating the value from the lexical representation</head><p>The value of a <code>xs:yearMonthDuration</code> lexical form is
                            obtained by multiplying the value of the years component by 12 and
                            adding the value of the months component. The value is positive or
                            negative depending on the preceding sign.</p></div4><div4 id="canonical-yearMonthDuration"><head>Canonical representation</head><p>The canonical representation of <code>xs:yearMonthDuration</code>
                            restricts the value of the months component to <code>xs:integer</code>
                            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 <code>xs:integer</code>
                            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. For negative durations, the canonical form is
                            calculated using the absolute value of the duration and a negative sign
                            is prepended to it. If a component has the value zero (0), then the
                            number and the designator for that component <rfc2119>must</rfc2119> be
                            omitted. However, if the value is zero (0) months, the canonical form is "P0M".</p></div4><div4 id="order-yearMonthDuration"><head>Order relation on xs:yearMonthDuration</head><p>Let the function that calculates the value of an
                            <code>xs:yearMonthDuration</code> in the manner described above be
                            called V(d). Then for two <code>xs:yearMonthDuration</code> values x
                            and y, x &gt; y if and only if V(x) &gt; V(y). The order relation on
                            <code>yearMonthDuration</code> is a total order.</p></div4></div3><div3 id="dt-dayTimeDuration" diff="del" at="B-bug25447"><head>xs:dayTimeDuration</head><p>[Definition] <code>xs:dayTimeDuration</code> is derived from
                        <code>xs:duration</code> by restricting its lexical representation to
                        contain only the days, hours, minutes and seconds components. The value
                        space of <code>xs:dayTimeDuration</code> is the set of fractional second
                        values. The components of <code>xs:dayTimeDuration</code> correspond to the
                        day, hour, minute and second components defined in Section 5.5.3.2 of
                            <bibref ref="ISO8601"/>, respectively.</p><div4 id="lexical-dayTimeDuration"><head>Lexical representation</head><p>The lexical representation for <code>xs:dayTimeDuration</code> is the
                                <bibref ref="ISO8601"/> 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.</p><p>The values of the days, hours and minutes components are not restricted,
                            but allow an arbitrary unsigned <code>xs:integer</code>. Similarly, the
                            value of the seconds component allows an arbitrary unsigned
                            <code>xs:decimal</code>. 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 <bibref ref="ISO8601"/> Date and Time Formats.</p><p>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:</p><ulist><item><p>If the number of days, hours, minutes, or seconds in any
                                    expression equals zero (0), the number and its corresponding
                                    designator <rfc2119>may</rfc2119> be omitted. However, at least
                                    one number and its designator <rfc2119>must</rfc2119> be present.</p></item><item><p>The seconds part <rfc2119>may</rfc2119> have a decimal fraction.</p></item><item><p>The designator 'T' <rfc2119>must</rfc2119> be absent if and only if
                                    all of the time items are absent. The designator 'P' <rfc2119>must</rfc2119> always be present.</p></item></ulist><p>For example, P13D, PT47H, P3DT2H, -PT35.89S and P4DT251M are all allowed.
                            P-134D is not allowed (invalid location of minus sign), although -P134D
                            is allowed. </p></div4><div4 id="calculating-value-dayTimeDuration"><head>Calculating the value of a xs:dayTimeDuration from the lexical representation</head><p>The value of a <code>xs:dayTimeDuration</code> lexical form in
                            fractional seconds is obtained by converting the days, hours, minutes
                            and seconds value to fractional seconds using the conversion rules: 24
                            hours = 1 day, 60 minutes = 1 hour and 60 seconds = 1 minute.</p></div4><div4 id="canonical-dayTimeDuration"><head>Canonical representation</head><p>The canonical representation of <code>xs:dayTimeDuration</code>
                            restricts the value of the hours component to <code>xs:integer</code>
                            values between 0 and 23, both inclusive; the value of the minutes
                            component to <code>xs:integer</code> values between 0 and 59; both
                            inclusive; and the value of the seconds component to
                            <code>xs:decimal</code> valued from 0.0 to 59.999... (see <bibref ref="xmlschema-2"/>, Appendix D).</p><p>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 86,400 (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 3,600 (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. For
                            negative durations, the canonical form is calculated using the absolute
                            value of the duration and a negative sign is prepended to it. If a
                            component has the value zero (0) then the number and the designator for
                            that component must be omitted. However, if all the components of the
                            lexical form are zero (0), the canonical form is <code>PT0S</code>.</p></div4><div4 id="order-dayTimeDuration"><head>Order relation on xs:dayTimeDuration</head><p>Let the function that calculates the value of a
                            <code>xs:dayTimeDuration</code> in the manner described above be called
                            <emph>V(d)</emph>. Then for two <code>xs:dayTimeDuration</code> values
                            <emph>x</emph> and <emph>y, x &gt; y</emph> if and only if <emph>V(x)
                                &gt; V(y)</emph>. The order relation on
                            <code>xs:dayTimeDuration</code> is a total order. </p></div4></div3></div2><div2 id="comp.duration"><head>Comparison operators on durations</head><table class="index"><thead><tr><th rowspan="1" colspan="1">Function</th><th rowspan="1" colspan="1">Meaning</th></tr></thead><tbody><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">op:yearMonthDuration-less-than</code></td><td rowspan="1" colspan="1">Returns true if <code>$arg1</code> is a shorter duration than <code>$arg2</code>.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">op:yearMonthDuration-greater-than</code></td><td rowspan="1" colspan="1">Returns true if <code>$arg1</code> is a longer duration than <code>$arg2</code>.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">op:dayTimeDuration-less-than</code></td><td rowspan="1" colspan="1">Returns true if <code>$arg1</code> is a shorter duration than <code>$arg2</code>.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">op:dayTimeDuration-greater-than</code></td><td rowspan="1" colspan="1">Returns true if <code>$arg1</code> is a longer duration than <code>$arg2</code>.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">op:duration-equal</code></td><td rowspan="1" colspan="1">Returns true if <code>$arg1</code> and <code>$arg2</code> are durations of the same
            length.</td></tr></tbody></table><p>The following comparison operators are defined on the <bibref ref="xmlschema-2"/>
                    duration datatypes. Each operator takes two operands of the same
                    type and returns an <code>xs:boolean</code> result. As discussed in <bibref ref="xmlschema-2"/>, the
                    order relation on <code>xs:duration</code> is a partial order rather than 
                    a total order. For this reason, only equality is defined on <code>xs:duration</code>. 
					A full complement of comparison and
                    arithmetic functions are defined on the two subtypes of duration described in
                        <specref ref="duration-subtypes"/> which do have a total order.</p><div3 id="func-yearMonthDuration-less-than"><head>op:yearMonthDuration-less-than</head><glist><gitem><label>Summary</label><def><p>Returns true if <code>$arg1</code> is a shorter duration than <code>$arg2</code>.</p></def></gitem><gitem><label>Operator Mapping</label><def><p>Defines
         the semantics of the "lt" operator when applied to two <code>xs:yearMonthDuration</code>
         values. Also used in the definition of the "ge" operator.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="yearMonthDuration-less-than" return-type="xs:boolean" isOp="yes" prefix="op" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg1" type="xs:yearMonthDuration"/><arg name="arg2" type="xs:yearMonthDuration"/></proto></example></def></gitem><gitem><label>Rules</label><def><p>If the number of months in the value of <code>$arg1</code> is numerically less than the
            number of months in the value of <code>$arg2</code>, the function returns true.</p><p>Otherwise, the function returns false.</p></def></gitem><gitem><label>Notes</label><def><p role="note">Either or both durations may be negative.</p></def></gitem></glist></div3><div3 id="func-yearMonthDuration-greater-than"><head>op:yearMonthDuration-greater-than</head><glist><gitem><label>Summary</label><def><p>Returns true if <code>$arg1</code> is a longer duration than <code>$arg2</code>.</p></def></gitem><gitem><label>Operator Mapping</label><def><p>Defines
         the semantics of the "gt" operator when applied to two <code>xs:yearMonthDuration</code>
         values. Also used in the definition of the "le" operator.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="yearMonthDuration-greater-than" return-type="xs:boolean" isOp="yes" prefix="op" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg1" type="xs:yearMonthDuration"/><arg name="arg2" type="xs:yearMonthDuration"/></proto></example></def></gitem><gitem><label>Rules</label><def><p>The function call <code>op:yearMonthDuration-greater-than($A, $B)</code> is defined to
            return the same result as <code>op:yearMonthDuration-less-than($B, $A)</code></p></def></gitem></glist></div3><div3 id="func-dayTimeDuration-less-than"><head>op:dayTimeDuration-less-than</head><glist><gitem><label>Summary</label><def><p>Returns true if <code>$arg1</code> is a shorter duration than <code>$arg2</code>.</p></def></gitem><gitem><label>Operator Mapping</label><def><p>Defines the
         semantics of the "lt" operator when applied to two <code>xs:dayTimeDuration</code> values.
         Also used in the definition of the "ge" operator.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="dayTimeDuration-less-than" return-type="xs:boolean" isOp="yes" prefix="op" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg1" type="xs:dayTimeDuration"/><arg name="arg2" type="xs:dayTimeDuration"/></proto></example></def></gitem><gitem><label>Rules</label><def><p>If the number of seconds in the value of <code>$arg1</code> is numerically less than the
            number of seconds in the value of <code>$arg2</code>, the function returns true.</p><p>Otherwise, the function returns false.</p></def></gitem><gitem><label>Notes</label><def><p role="note">Either or both durations may be negative</p></def></gitem></glist></div3><div3 id="func-dayTimeDuration-greater-than"><head>op:dayTimeDuration-greater-than</head><glist><gitem><label>Summary</label><def><p>Returns true if <code>$arg1</code> is a longer duration than <code>$arg2</code>.</p></def></gitem><gitem><label>Operator Mapping</label><def><p>Defines the
         semantics of the "gt" operator when applied to two <code>xs:dayTimeDuration</code> values.
         Also used in the definition of the "le" operator.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="dayTimeDuration-greater-than" return-type="xs:boolean" isOp="yes" prefix="op" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg1" type="xs:dayTimeDuration"/><arg name="arg2" type="xs:dayTimeDuration"/></proto></example></def></gitem><gitem><label>Rules</label><def><p>The function call <code>op:dayTimeDuration-greater-than($A, $B)</code> is defined to
            return the same result as <code>op:dayTimeDuration-less-than($B, $A)</code></p></def></gitem></glist></div3><div3 id="func-duration-equal"><head>op:duration-equal</head><glist><gitem><label>Summary</label><def><p>Returns true if <code>$arg1</code> and <code>$arg2</code> are durations of the same
            length.</p></def></gitem><gitem><label>Operator Mapping</label><def><p>Defines the
         semantics of the "eq" operators when applied to two <code>xs:duration</code> values. Also
         used in the definition of the "ne" operator.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="duration-equal" return-type="xs:boolean" isOp="yes" prefix="op" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg1" type="xs:duration"/><arg name="arg2" type="xs:duration"/></proto></example></def></gitem><gitem><label>Rules</label><def><p>If the <code>xs:yearMonthDuration</code> components of <code>$arg1</code> and
               <code>$arg2</code> are equal and the <code>xs:dayTimeDuration</code> components of
               <code>$arg1</code> and <code>$arg2</code> are equal, the function returns
               <code>true</code>.</p><p>Otherwise, the function returns false.</p><p>The semantics of this function are:</p><eg xml:space="preserve">
xs:yearMonthDuration($arg1) div xs:yearMonthDuration('P1M')  eq
xs:yearMonthDuration($arg2) div xs:yearMonthDuration('P1M')
    and
xs:dayTimeDuration($arg1) div xs:dayTimeDuration('PT1S')  eq
xs:dayTimeDuration($arg2) div xs:dayTimeDuration('PT1S')
</eg><p>that is, the function returns <code>true</code> if the months and seconds values of the
            two durations are equal.</p></def></gitem><gitem><label>Notes</label><def><p role="note">Note that this function, like any other, may be applied to arguments that are derived
            from the types given in the function signature, including the two subtypes
               <code>xs:dayTimeDuration</code> and <code>xs:yearMonthDuration</code>. With the
            exception of the zero-length duration, no instance of <code>xs:dayTimeDuration</code>
            can ever be equal to an instance of <code>xs:yearMonthDuration</code>.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>op:duration-equal(xs:duration("P1Y"),
                  xs:duration("P12M"))</code> returns <code>true()</code>.</p><p>The expression <code>op:duration-equal(xs:duration("PT24H"),
                  xs:duration("P1D"))</code> returns <code>true()</code>.</p><p>The expression <code>op:duration-equal(xs:duration("P1Y"),
                  xs:duration("P365D"))</code> returns <code>false()</code>.</p><p>The expression <code>op:duration-equal(xs:yearMonthDuration("P0Y"),
                  xs:dayTimeDuration("P0D"))</code> returns <code>true()</code>.</p><p>The expression <code>op:duration-equal(xs:yearMonthDuration("P1Y"),
                  xs:dayTimeDuration("P365D"))</code> returns <code>false()</code>.</p><p>The expression <code>op:duration-equal(xs:yearMonthDuration("P2Y"),
                  xs:yearMonthDuration("P24M"))</code> returns <code>true()</code>.</p><p>The expression <code>op:duration-equal(xs:dayTimeDuration("P10D"),
                  xs:dayTimeDuration("PT240H"))</code> returns <code>true()</code>.</p><p>The expression <code>op:duration-equal(xs:duration("P2Y0M0DT0H0M0S"),
                  xs:yearMonthDuration("P24M"))</code> returns <code>true()</code>.</p><p>The expression <code>op:duration-equal(xs:duration("P0Y0M10D"),
                  xs:dayTimeDuration("PT240H"))</code> returns <code>true()</code>.</p></def></gitem></glist></div3></div2><div2 id="component-extraction-durations"><head>Component extraction functions on durations</head><p>The duration datatype may be considered to be a composite datatypes
                    in that it contains distinct properties or components. The extraction functions specified
                    below extract a single component from a duration value. 
For <code>xs:duration</code> and its subtypes, including the two subtypes <code>xs:yearMonthDuration</code> and
 <code>xs:dayTimeDuration</code>, the components are normalized: this means that the seconds and minutes 
 components will always be less than 60, the hours component less than 24, and the months component less than 12.
</p><table class="index"><thead><tr><th rowspan="1" colspan="1">Function</th><th rowspan="1" colspan="1">Meaning</th></tr></thead><tbody><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:years-from-duration</code></td><td rowspan="1" colspan="1">Returns the number of years in a duration.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:months-from-duration</code></td><td rowspan="1" colspan="1">Returns the number of months in a duration.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:days-from-duration</code></td><td rowspan="1" colspan="1">Returns the number of days in a duration.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:hours-from-duration</code></td><td rowspan="1" colspan="1">Returns the number of hours in a duration.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:minutes-from-duration</code></td><td rowspan="1" colspan="1">Returns the number of minutes in a duration.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:seconds-from-duration</code></td><td rowspan="1" colspan="1">Returns the number of seconds in a duration.</td></tr></tbody></table><div3 id="func-years-from-duration"><head>fn:years-from-duration</head><glist><gitem><label>Summary</label><def><p>Returns the number of years in a duration.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="years-from-duration" return-type="xs:integer?" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg" type="xs:duration?"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>If <code>$arg</code> is the empty sequence, the function returns the empty sequence.</p><p>Otherwise, the function returns an <code>xs:integer</code> representing the years
            component in the value of <code>$arg</code>. <phrase diff="chg" at="B">Given that a duration
            is a <code>($months, $seconds)</code> tuple, the result is the value of <code>($months idiv 12)</code></phrase>.</p><p>If <code>$arg</code> is a negative duration then the result will be negative.</p><p>If <code>$arg</code> is an <code>xs:dayTimeDuration</code> the function returns 0.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>fn:years-from-duration(xs:yearMonthDuration("P20Y15M"))</code> returns <code>21</code>.</p><p>The expression <code>fn:years-from-duration(xs:yearMonthDuration("-P15M"))</code> returns <code>-1</code>.</p><p>The expression <code>fn:years-from-duration(xs:dayTimeDuration("-P2DT15H"))</code> returns <code>0</code>.</p></def></gitem></glist></div3><div3 id="func-months-from-duration"><head>fn:months-from-duration</head><glist><gitem><label>Summary</label><def><p>Returns the number of months in a duration.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="months-from-duration" return-type="xs:integer?" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg" type="xs:duration?"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>If <code>$arg</code> is the empty sequence, the function returns the empty sequence.</p><p>Otherwise, the function returns an <code>xs:integer</code> representing the months
            component in the value of <code>$arg</code>. <phrase diff="chg" at="B">Given that a duration
               is a <code>($months, $seconds)</code> tuple, the result is the value of <code>($months mod 12)</code></phrase>.</p><p>If <code>$arg</code> is a negative duration then the result will be negative.</p><p>If <code>$arg</code> is an <code>xs:dayTimeDuration</code> the function returns 0.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>fn:months-from-duration(xs:yearMonthDuration("P20Y15M"))</code> returns <code>3</code>.</p><p>The expression <code>fn:months-from-duration(xs:yearMonthDuration("-P20Y18M"))</code> returns <code>-6</code>.</p><p>The expression <code>fn:months-from-duration(xs:dayTimeDuration("-P2DT15H0M0S"))</code> returns <code>0</code>.</p></def></gitem></glist></div3><div3 id="func-days-from-duration"><head>fn:days-from-duration</head><glist><gitem><label>Summary</label><def><p>Returns the number of days in a duration.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="days-from-duration" return-type="xs:integer?" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg" type="xs:duration?"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>If <code>$arg</code> is the empty sequence, the function returns the empty sequence.</p><p>Otherwise, the function returns an <code>xs:integer</code> representing the days
            component in the value of <code>$arg</code>. <phrase diff="chg" at="B">Given that a duration
               is a <code>($months, $seconds)</code> tuple, the result is the value of <code>($seconds idiv 86400)</code></phrase>.</p><p>If <code>$arg</code> is a negative duration then the result will be negative.</p><p>If <code>$arg</code> is an <code>xs:yearMonthDuration</code> the function returns 0.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>fn:days-from-duration(xs:dayTimeDuration("P3DT10H"))</code> returns <code>3</code>.</p><p>The expression <code>fn:days-from-duration(xs:dayTimeDuration("P3DT55H"))</code> returns <code>5</code>.</p><p>The expression <code>fn:days-from-duration(xs:yearMonthDuration("P3Y5M"))</code> returns <code>0</code>.</p></def></gitem></glist></div3><div3 id="func-hours-from-duration"><head>fn:hours-from-duration</head><glist><gitem><label>Summary</label><def><p>Returns the number of hours in a duration.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="hours-from-duration" return-type="xs:integer?" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg" type="xs:duration?"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>If <code>$arg</code> is the empty sequence, the function returns the empty sequence.</p><p>Otherwise, the function returns an <code>xs:integer</code> representing the hours
            component in the value of <code>$arg</code>. <phrase diff="chg" at="B">Given that a duration
               is a <code>($months, $seconds)</code> tuple, the result is the value of <code>($seconds mod 86400) idiv 3600</code></phrase>.</p><p>If <code>$arg</code> is a negative duration then the result will be negative.</p><p>If <code>$arg</code> is an <code>xs:yearMonthDuration</code> the function returns 0.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>fn:hours-from-duration(xs:dayTimeDuration("P3DT10H"))</code> returns <code>10</code>.</p><p>The expression <code>fn:hours-from-duration(xs:dayTimeDuration("P3DT12H32M12S"))</code> returns <code>12</code>.</p><p>The expression <code>fn:hours-from-duration(xs:dayTimeDuration("PT123H"))</code> returns <code>3</code>.</p><p>The expression <code>fn:hours-from-duration(xs:dayTimeDuration("-P3DT10H"))</code> returns <code>-10</code>.</p></def></gitem></glist></div3><div3 id="func-minutes-from-duration"><head>fn:minutes-from-duration</head><glist><gitem><label>Summary</label><def><p>Returns the number of minutes in a duration.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="minutes-from-duration" return-type="xs:integer?" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg" type="xs:duration?"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>If <code>$arg</code> is the empty sequence, the function returns the empty sequence.</p><p>Otherwise, the function returns an <code>xs:integer</code> representing the minutes
            component in the value of <code>$arg</code>. <phrase diff="chg" at="B">Given that a duration
               is a <code>($months, $seconds)</code> tuple, the result is the value of <code>($seconds mod 3600) idiv 60</code></phrase>.</p><p>If <code>$arg</code> is a negative duration then the result will be negative.</p><p>If <code>$arg</code> is an <code>xs:yearMonthDuration</code> the function returns 0.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>fn:minutes-from-duration(xs:dayTimeDuration("P3DT10H"))</code> returns <code>0</code>.</p><p>The expression <code>fn:minutes-from-duration(xs:dayTimeDuration("-P5DT12H30M"))</code> returns <code>-30</code>.</p></def></gitem></glist></div3><div3 id="func-seconds-from-duration"><head>fn:seconds-from-duration</head><glist><gitem><label>Summary</label><def><p>Returns the number of seconds in a duration.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="seconds-from-duration" return-type="xs:decimal?" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg" type="xs:duration?"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>If <code>$arg</code> is the empty sequence, the function returns the empty sequence.</p><p>Otherwise, the function returns an <code>xs:decimal</code> representing the seconds
            component in the value of <code>$arg</code>. <phrase diff="chg" at="B">Given that a duration
               is a <code>($months, $seconds)</code> tuple, the result is the value of <code>($seconds mod 60)</code>
            as an <code>xs:decimal</code></phrase>.</p><p>If <code>$arg</code> is a negative duration then the result will be negative.</p><p>If <code>$arg</code> is an <code>xs:yearMonthDuration</code> the function returns 0.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>fn:seconds-from-duration(xs:dayTimeDuration("P3DT10H12.5S"))</code> returns <code>12.5</code>.</p><p>The expression <code>fn:seconds-from-duration(xs:dayTimeDuration("-PT256S"))</code> returns <code>-16.0</code>.</p></def></gitem></glist></div3></div2><div2 id="duration-arithmetic"><head>Arithmetic operators on durations</head><table class="index"><thead><tr><th rowspan="1" colspan="1">Function</th><th rowspan="1" colspan="1">Meaning</th></tr></thead><tbody><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">op:add-yearMonthDurations</code></td><td rowspan="1" colspan="1">Returns the result of adding two <code>xs:yearMonthDuration</code> values. </td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">op:subtract-yearMonthDurations</code></td><td rowspan="1" colspan="1">Returns the result of subtracting one <code>xs:yearMonthDuration</code> value from
            another. </td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">op:multiply-yearMonthDuration</code></td><td rowspan="1" colspan="1">Returns the result of multiplying the value of <code>$arg1</code> by <code>$arg2</code>.
            The result is rounded to the nearest month.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">op:divide-yearMonthDuration</code></td><td rowspan="1" colspan="1">Returns the result of dividing the value of <code>$arg1</code> by <code>$arg2</code>.
            The result is rounded to the nearest month.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">op:divide-yearMonthDuration-by-yearMonthDuration</code></td><td rowspan="1" colspan="1">Returns the ratio of two <code>xs:yearMonthDuration</code> values.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">op:add-dayTimeDurations</code></td><td rowspan="1" colspan="1">Returns the sum of two <code>xs:dayTimeDuration</code> values.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">op:subtract-dayTimeDurations</code></td><td rowspan="1" colspan="1">Returns the result of subtracting one <code>xs:dayTimeDuration</code> from another.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">op:multiply-dayTimeDuration</code></td><td rowspan="1" colspan="1">Returns the result of multiplying a <code>xs:dayTimeDuration</code> by a number.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">op:divide-dayTimeDuration</code></td><td rowspan="1" colspan="1">Returns the result of multiplying a <code>xs:dayTimeDuration</code> by a number.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">op:divide-dayTimeDuration-by-dayTimeDuration</code></td><td rowspan="1" colspan="1">Returns the ratio of two <code>xs:dayTimeDuration</code> values, as a decimal
            number.</td></tr></tbody></table><p>For operators that combine a duration and a date/time value, see <specref ref="dateTime-arithmetic"/>.</p><div3 id="func-add-yearMonthDurations"><head>op:add-yearMonthDurations</head><glist><gitem><label>Summary</label><def><p>Returns the result of adding two <code>xs:yearMonthDuration</code> values. </p></def></gitem><gitem><label>Operator Mapping</label><def><p>Defines the semantics of the
         "+" operator when applied to two <code>xs:yearMonthDuration</code> values.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="add-yearMonthDurations" return-type="xs:yearMonthDuration" isOp="yes" prefix="op" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg1" type="xs:yearMonthDuration"/><arg name="arg2" type="xs:yearMonthDuration"/></proto></example></def></gitem><gitem><label>Rules</label><def><p>The function returns the result of adding the value of <code>$arg1</code> to the value
            of <code>$arg2</code>. The result will be an <code>xs:yearMonthDuration</code> whose
            length in months is equal to the length in months of <code>$arg1</code> plus the length
            in months of <code>$arg2</code>.</p><p>For handling of overflow, see <specref ref="duration-limits"/>.</p></def></gitem><gitem><label>Notes</label><def><p role="note">Either duration (and therefore the result) may be negative.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>op:add-yearMonthDurations(xs:yearMonthDuration("P2Y11M"),
                  xs:yearMonthDuration("P3Y3M"))</code> returns <code>xs:yearMonthDuration("P6Y2M")</code>.</p></def></gitem></glist></div3><div3 id="func-subtract-yearMonthDurations"><head>op:subtract-yearMonthDurations</head><glist><gitem><label>Summary</label><def><p>Returns the result of subtracting one <code>xs:yearMonthDuration</code> value from
            another. </p></def></gitem><gitem><label>Operator Mapping</label><def><p>Defines the semantics of the
         "-" operator when applied to two <code>xs:yearMonthDuration</code> values.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="subtract-yearMonthDurations" return-type="xs:yearMonthDuration" isOp="yes" prefix="op" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg1" type="xs:yearMonthDuration"/><arg name="arg2" type="xs:yearMonthDuration"/></proto></example></def></gitem><gitem><label>Rules</label><def><p>The function returns the result of subtracting the value of <code>$arg2</code> from the
            value of <code>$arg1</code>. The result will be an <code>xs:yearMonthDuration</code>
            whose length in months is equal to the length in months of <code>$arg1</code> minus the
            length in months of <code>$arg2</code>.</p><p>For handling of overflow, see <specref ref="duration-limits"/>.</p></def></gitem><gitem><label>Notes</label><def><p role="note">Either duration (and therefore the result) may be negative.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>op:subtract-yearMonthDurations(xs:yearMonthDuration("P2Y11M"),
                  xs:yearMonthDuration("P3Y3M"))</code> returns <code>xs:yearMonthDuration("-P4M")</code>.</p></def></gitem></glist></div3><div3 id="func-multiply-yearMonthDuration"><head>op:multiply-yearMonthDuration</head><glist><gitem><label>Summary</label><def><p>Returns the result of multiplying the value of <code>$arg1</code> by <code>$arg2</code>.
            The result is rounded to the nearest month.</p></def></gitem><gitem><label>Operator Mapping</label><def><p>Defines the semantics of the
         "*" operator when applied to an <code>xs:yearMonthDuration</code> and a numeric
         value.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="multiply-yearMonthDuration" return-type="xs:yearMonthDuration" isOp="yes" prefix="op" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg1" type="xs:yearMonthDuration"/><arg name="arg2" type="xs:double"/></proto></example></def></gitem><gitem><label>Rules</label><def><p>The result is the <code>xs:yearMonthDuration</code> whose length in months is equal to
            the result of applying the <code>fn:round</code> function to the value obtained by
            multiplying the length in months of <code>$arg1</code> by the value of
               <code>$arg2</code>.</p><p>If <code>$arg2</code> is positive or negative zero, the result is a zero-length
            duration. If <code>$arg2</code> is positive or negative infinity, the result overflows
            and is handled as described in <specref ref="duration-limits"/>. </p><p>For handling of overflow and underflow, see <specref ref="duration-limits"/>.</p></def></gitem><gitem><label>Error Conditions</label><def><p>A dynamic error is raised <errorref class="CA" code="0005"/> if <code>$arg2</code> is
               <code>NaN</code>.</p></def></gitem><gitem><label>Notes</label><def><p role="note">Either duration (and therefore the result) may be negative.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>op:multiply-yearMonthDuration(xs:yearMonthDuration("P2Y11M"),
                  2.3)</code> returns <code>xs:yearMonthDuration("P6Y9M")</code>.</p></def></gitem></glist></div3><div3 id="func-divide-yearMonthDuration"><head>op:divide-yearMonthDuration</head><glist><gitem><label>Summary</label><def><p>Returns the result of dividing the value of <code>$arg1</code> by <code>$arg2</code>.
            The result is rounded to the nearest month.</p></def></gitem><gitem><label>Operator Mapping</label><def><p>Defines the semantics of the
         "div" operator when applied to an <code>xs:yearMonthDuration</code> and a numeric
         value.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="divide-yearMonthDuration" return-type="xs:yearMonthDuration" isOp="yes" prefix="op" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg1" type="xs:yearMonthDuration"/><arg name="arg2" type="xs:double"/></proto></example></def></gitem><gitem><label>Rules</label><def><p>The result is the <code>xs:yearMonthDuration</code> whose length in months is equal to
            the result of applying the <code>fn:round</code> function to the value obtained by
            dividing the length in months of <code>$arg1</code> by the value of
            <code>$arg2</code>.</p><p>If <code>$arg2</code> is positive or negative infinity, the result is a zero-length
            duration. If <code>$arg2</code> is positive or negative zero, the result overflows and
            is handled as described in <specref ref="duration-limits"/>. </p><p>For handling of overflow and underflow, see <specref ref="duration-limits"/>.</p></def></gitem><gitem><label>Error Conditions</label><def><p>A dynamic error is raised <errorref class="CA" code="0005"/> if <code>$arg2</code> is
               <code>NaN</code>.</p></def></gitem><gitem><label>Notes</label><def><p role="note">Either operand (and therefore the result) may be negative.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>op:divide-yearMonthDuration(xs:yearMonthDuration("P2Y11M"),
                  1.5)</code> returns <code>xs:yearMonthDuration("P1Y11M")</code>.</p></def></gitem></glist></div3><div3 id="func-divide-yearMonthDuration-by-yearMonthDuration"><head>op:divide-yearMonthDuration-by-yearMonthDuration</head><glist><gitem><label>Summary</label><def><p>Returns the ratio of two <code>xs:yearMonthDuration</code> values.</p></def></gitem><gitem><label>Operator Mapping</label><def><p>Defines the semantics of the
         "div" operator when applied to two <code>xs:yearMonthDuration</code> values.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="divide-yearMonthDuration-by-yearMonthDuration" return-type="xs:decimal" isOp="yes" prefix="op" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg1" type="xs:yearMonthDuration"/><arg name="arg2" type="xs:yearMonthDuration"/></proto></example></def></gitem><gitem><label>Rules</label><def><p>The function returns the result of dividing the length in months of <code>$arg1</code>
            by the length in months of <code>$arg2</code>, according to the rules of the
               <code>op:numeric-divide</code> function for integer operands.</p><p>For handling of overflow and underflow, see <specref ref="duration-limits"/>.</p></def></gitem><gitem><label>Notes</label><def><p role="note">Either duration (and therefore the result) may be negative.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>op:divide-yearMonthDuration-by-yearMonthDuration(xs:yearMonthDuration("P3Y4M"),
                  xs:yearMonthDuration("-P1Y4M"))</code> returns <code>-2.5</code>.</p><p>The following example demonstrates how to calculate the length of an
                  <code>xs:yearMonthDuration</code> value in months:</p><p>The expression <code>op:divide-yearMonthDuration-by-yearMonthDuration(xs:yearMonthDuration("P3Y4M"),
                  xs:yearMonthDuration("P1M"))</code> returns <code>40</code>.</p></def></gitem></glist></div3><div3 id="func-add-dayTimeDurations"><head>op:add-dayTimeDurations</head><glist><gitem><label>Summary</label><def><p>Returns the sum of two <code>xs:dayTimeDuration</code> values.</p></def></gitem><gitem><label>Operator Mapping</label><def><p>Defines the semantics of the "+"
         operator when applied to two <code>xs:dayTimeDuration</code> values.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="add-dayTimeDurations" return-type="xs:dayTimeDuration" isOp="yes" prefix="op" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg1" type="xs:dayTimeDuration"/><arg name="arg2" type="xs:dayTimeDuration"/></proto></example></def></gitem><gitem><label>Rules</label><def><p>The function returns the result of adding the value of <code>$arg1</code> to the value
            of <code>$arg2</code>. The result is the <code>xs:dayTimeDuration</code> whose length in
            seconds is equal to the sum of the length in seconds of the two input durations.</p><p>For handling of overflow, see <specref ref="duration-limits"/>.</p></def></gitem><gitem><label>Notes</label><def><p role="note">Either duration (and therefore the result) may be negative.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>op:add-dayTimeDurations(xs:dayTimeDuration("P2DT12H5M"),
                  xs:dayTimeDuration("P5DT12H"))</code> returns <code>xs:dayTimeDuration('P8DT5M')</code>.</p></def></gitem></glist></div3><div3 id="func-subtract-dayTimeDurations"><head>op:subtract-dayTimeDurations</head><glist><gitem><label>Summary</label><def><p>Returns the result of subtracting one <code>xs:dayTimeDuration</code> from another.</p></def></gitem><gitem><label>Operator Mapping</label><def><p>Defines the semantics of the "-"
         operator when applied to two <code>xs:dayTimeDuration</code> values.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="subtract-dayTimeDurations" return-type="xs:dayTimeDuration" isOp="yes" prefix="op" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg1" type="xs:dayTimeDuration"/><arg name="arg2" type="xs:dayTimeDuration"/></proto></example></def></gitem><gitem><label>Rules</label><def><p>The function returns the result of subtracting the value of <code>$arg2</code> from the
            value of <code>$arg1</code>. The result is the <code>xs:dayTimeDuration</code> whose
            length in seconds is equal to the length in seconds of <code>$arg1</code> minus the
            length in seconds of <code>$arg2</code>.</p><p>For handling of overflow, see <specref ref="duration-limits"/>.</p></def></gitem><gitem><label>Notes</label><def><p role="note">Either duration (and therefore the result) may be negative.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>op:subtract-dayTimeDurations(xs:dayTimeDuration("P2DT12H"),
                  xs:dayTimeDuration("P1DT10H30M"))</code> returns <code>xs:dayTimeDuration('P1DT1H30M')</code>.</p></def></gitem></glist></div3><div3 id="func-multiply-dayTimeDuration"><head>op:multiply-dayTimeDuration</head><glist><gitem><label>Summary</label><def><p>Returns the result of multiplying a <code>xs:dayTimeDuration</code> by a number.</p></def></gitem><gitem><label>Operator Mapping</label><def><p>Defines the semantics of the "*"
         operator when applied to an <code>xs:dayTimeDuration</code> and a numeric
         value.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="multiply-dayTimeDuration" return-type="xs:dayTimeDuration" isOp="yes" prefix="op" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg1" type="xs:dayTimeDuration"/><arg name="arg2" type="xs:double"/></proto></example></def></gitem><gitem><label>Rules</label><def><p>The function returns the result of multiplying the value of <code>$arg1</code> by
               <code>$arg2</code>. The result is the <code>xs:dayTimeDuration</code> whose length in
            seconds is equal to the length in seconds of <code>$arg1</code> multiplied by the
            numeric value <code>$arg2</code>.</p><p>If <code>$arg2</code> is positive or negative zero, the result is a zero-length
            duration. If <code>$arg2</code> is positive or negative infinity, the result overflows
            and is handled as described in <specref ref="date-time-duration-conformance"/>. </p><p>For handling of overflow and underflow, see <specref ref="duration-limits"/>.</p></def></gitem><gitem><label>Error Conditions</label><def><p>A dynamic error is raised <errorref class="CA" code="0005"/> if <code>$arg2</code> is
               <code>NaN</code>.</p></def></gitem><gitem><label>Notes</label><def><p role="note">Either operand (and therefore the result) may be negative.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>op:multiply-dayTimeDuration(xs:dayTimeDuration("PT2H10M"),
                  2.1)</code> returns <code>xs:dayTimeDuration('PT4H33M')</code>.</p></def></gitem></glist></div3><div3 id="func-divide-dayTimeDuration"><head>op:divide-dayTimeDuration</head><glist><gitem><label>Summary</label><def><p>Returns the result of multiplying a <code>xs:dayTimeDuration</code> by a number.</p></def></gitem><gitem><label>Operator Mapping</label><def><p>Defines the semantics of the
         "div" operator when applied to two <code>xs:dayTimeDuration</code> values.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="divide-dayTimeDuration" return-type="xs:dayTimeDuration" isOp="yes" prefix="op" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg1" type="xs:dayTimeDuration"/><arg name="arg2" type="xs:double"/></proto></example></def></gitem><gitem><label>Rules</label><def><p>The function returns the result of dividing the value of <code>$arg1</code> by
               <code>$arg2</code>. The result is the <code>xs:dayTimeDuration</code> whose length in
            seconds is equal to the length in seconds of <code>$arg1</code> divided by the numeric
            value <code>$arg2</code>.</p><p>If <code>$arg2</code> is positive or negative infinity, the result is a zero-length
            duration. If <code>$arg2</code> is positive or negative zero, the result overflows and
            is handled as described in <specref ref="date-time-duration-conformance"/>. </p><p>For handling of overflow and underflow, see <specref ref="duration-limits"/>.</p></def></gitem><gitem><label>Error Conditions</label><def><p>A dynamic error is raised <errorref class="CA" code="0005"/> if <code>$arg2</code> is
               <code>NaN</code>.</p></def></gitem><gitem><label>Notes</label><def><p role="note">Either operand (and therefore the result) may be negative.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>op:divide-dayTimeDuration(xs:dayTimeDuration("P1DT2H30M10.5S"),
                  1.5)</code> returns <code>xs:duration("PT17H40M7S")</code>.</p></def></gitem></glist></div3><div3 id="func-divide-dayTimeDuration-by-dayTimeDuration"><head>op:divide-dayTimeDuration-by-dayTimeDuration</head><glist><gitem><label>Summary</label><def><p>Returns the ratio of two <code>xs:dayTimeDuration</code> values, as a decimal
            number.</p></def></gitem><gitem><label>Operator Mapping</label><def><p>Defines the semantics of the
         "div" operator when applied to two <code>xs:dayTimeDuration</code> values.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="divide-dayTimeDuration-by-dayTimeDuration" return-type="xs:decimal" isOp="yes" prefix="op" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg1" type="xs:dayTimeDuration"/><arg name="arg2" type="xs:dayTimeDuration"/></proto></example></def></gitem><gitem><label>Rules</label><def><p>The function returns the result of dividing the value of <code>$arg1</code> by
               <code>$arg2</code>. The result is the <code>xs:dayTimeDuration</code> whose length in
            seconds is equal to the length in seconds of <code>$arg1</code> divided by the length in
            seconds of <code>$arg2</code>. The calculation is performed by applying
               <code>op:numeric-divide</code> to the two <code>xs:decimal</code> operands.</p><p>For handling of overflow and underflow, see <specref ref="duration-limits"/>.</p></def></gitem><gitem><label>Notes</label><def><p role="note">Either operand (and therefore the result) may be negative.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>fn:round-half-to-even( op:divide-dayTimeDuration-by-dayTimeDuration(
                  xs:dayTimeDuration("P2DT53M11S"), xs:dayTimeDuration("P1DT10H")),
                  4)</code> returns <code>1.4378</code>.</p><p>This examples shows how to determine the number of seconds in a duration.</p><p>The expression <code>op:divide-dayTimeDuration-by-dayTimeDuration(xs:dayTimeDuration("P2DT53M11S"),
                  xs:dayTimeDuration("PT1S"))</code> returns <code>175991.0</code>.</p></def></gitem></glist></div3></div2></div1><div1 id="dates-times"><head>Functions and operators on dates and times</head><p>This section defines operations on the <bibref ref="xmlschema-2"/> date and time types.</p><p>
See <bibref ref="Working-With-Timezones"/> for a disquisition on working with date and time values with and without timezones.
</p><div2 id="date-time-types"><head>Date and time types</head><p>The operators described in this section are defined on the following date and
                    time types: </p><ulist><item><p><code>xs:dateTime</code></p></item><item><p><code>xs:date</code></p></item><item><p><code>xs:time</code></p></item><item><p><code>xs:gYearMonth</code></p></item><item><p><code>xs:gYear</code></p></item><item><p><code>xs:gMonthDay</code></p></item><item><p><code>xs:gMonth</code></p></item><item><p><code>xs:gDay</code></p></item></ulist><p>The only operation defined on					
                    <code>xs:gYearMonth</code>, <code>xs:gYear</code>,
                    <code>xs:gMonthDay</code>, <code>xs:gMonth</code> and <code>xs:gDay</code> values is 
               equality comparison<phrase diff="del" at="E">and component extraction</phrase>.
               For other types, further operations are provided, including component extraction, 
               order comparisons, arithmetic, formatted display, and timezone
					adjustment.</p><div3 id="date-time-duration-conformance"><head>Limits and precision</head><p diff="del" at="A">For a number of the above datatypes <bibref ref="xmlschema-2"/> extends the basic
                            <bibref ref="ISO8601"/> lexical representations, such as
                        YYYY-MM-DDThh:mm:ss.s for dateTime, by allowing a preceding minus sign, more
                        than four digits to represent the year field — no maximum is
                        specified — and an unlimited number of digits for fractional
                        seconds. Leap seconds are not supported.</p><p>All <emph>minimally conforming</emph> processors
                        <rfc2119>must</rfc2119>  support positive year values with a minimum of 4 digits (i.e.,
                        YYYY) and a minimum fractional second precision of 1 millisecond or three
                        digits (i.e., s.sss). However, <emph>conforming</emph> processors
                        <rfc2119>may</rfc2119>  set larger <termref def="implementation-defined"/> limits
                        on the maximum number of digits they support in these two situations.  Processors <rfc2119>may</rfc2119> also choose to support the year 0000 and 
                        years with negative values.  The results of operations on dates that cross the year 
                        0000 are <termref def="implementation-defined"/>.</p><p>A processor that limits the number of digits in date and time datatype
                        representations may encounter overflow and underflow conditions when it
                        tries to execute the functions in <specref ref="dateTime-arithmetic"/>. In
                        these situations, the processor <rfc2119>must</rfc2119> return 00:00:00 in case of time underflow.
                  It <rfc2119>must</rfc2119> raise a dynamic 
                  error <errorref class="DT" code="0001"/> in case of overflow.</p></div3></div2><div2 id="date-time-values"><head>Date/time datatype values</head><p>As defined in <xspecref spec="DM31" ref="dates-and-times"/>, <code>xs:dateTime</code>, 
			<code>xs:date</code>, <code>xs:time</code>,  <code>xs:gYearMonth</code>, <code>xs:gYear</code>, 
			<code>xs:gMonthDay</code>, <code>xs:gMonth</code>, <code>xs:gDay</code> values, 
			referred to collectively as date/time values, are represented as seven components or properties: 
			<code>year</code>, <code>month</code>, <code>day</code>, <code>hour</code>, <code>minute</code>, 
			<code>second</code> and <code>timezone</code>.  The first five components are 
			<code>xs:integer</code> values.  The value of the <code>second</code> component is an <code>xs:decimal</code> 
			and the value of the <code>timezone</code> component is an <code>xs:dayTimeDuration</code>.  
			For all the primitive date/time datatypes, the <code>timezone</code> property is optional and may or may not 
			be present. Depending on the datatype, some of the remaining six properties must be present and 
			some must be <xtermref ref="dt-absent" spec="DM31">absent</xtermref>.   
               Absent, or missing, properties are represented by the empty sequence.  
			This value is referred to as the <emph>local</emph> value in that the value retains its original timezone.  
			Before comparing or subtracting <code>xs:dateTime</code> values, this local value <rfc2119>must</rfc2119>  
			be translated or <emph>normalized</emph> to UTC.</p><p>For <code>xs:time</code>, <code>00:00:00</code> and <code>24:00:00</code> are alternate lexical forms 
			for the same value, whose canonical representation is <code>00:00:00</code>.  For <code>xs:dateTime</code>,
		    a time component <code>24:00:00</code> translates to <code>00:00:00</code> of the following day.</p><div3 id="date-time-lexical-mapping"><head>Examples</head><ulist><item><p>An <code>xs:dateTime</code> with lexical
                        representation <code>1999-05-31T05:00:00</code>
						is represented in the datamodel by <code>{1999, 5, 31, 5, 0, 0.0, ()}</code>.</p></item><item><p>An <code>xs:dateTime</code> with lexical
                        representation <code>1999-05-31T13:20:00-05:00</code> 
						is represented by <code>{1999, 5, 31, 13, 20, 0.0, -PT5H}</code>.</p></item><item><p>An <code>xs:dateTime</code> with lexical
                        representation <code>1999-12-31T24:00:00</code> 
						is represented by <code>{2000, 1, 1, 0, 0, 0.0, ()}</code>.</p></item><item><p>An <code>xs:date</code> with lexical
                        representation <code>2005-02-28+8:00</code> 
						is represented by <code>{2005, 2, 28, (), (), (), PT8H}</code>.</p></item><item><p>An <code>xs:time</code> with lexical
                        representation <code>24:00:00</code> 
						is represented by <code>{(), (), (), 0, 0, 0, ()}</code>.</p></item></ulist></div3></div2><div2 id="constructing-dateTime"><head>Constructing a dateTime</head><p>A function is provided for constructing a
                    <code>xs:dateTime</code> value from a <code>xs:date</code> value and a
                    <code>xs:time</code> value.</p><table class="index"><thead><tr><th rowspan="1" colspan="1">Function</th><th rowspan="1" colspan="1">Meaning</th></tr></thead><tbody><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:dateTime</code></td><td rowspan="1" colspan="1">Returns an <code>xs:dateTime</code> value created by combining an <code>xs:date</code>
            and an <code>xs:time</code>.</td></tr></tbody></table><div3 id="func-dateTime"><head>fn:dateTime</head><glist><gitem><label>Summary</label><def><p>Returns an <code>xs:dateTime</code> value created by combining an <code>xs:date</code>
            and an <code>xs:time</code>.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="dateTime" return-type="xs:dateTime?" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg1" type="xs:date?"/><arg name="arg2" type="xs:time?"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>If either <code>$arg1</code> or <code>$arg2</code> is the empty sequence the function
            returns the empty sequence.</p><p>Otherwise, the function returns an <code>xs:dateTime</code> whose date component is
            equal to <code>$arg1</code> and whose time component is equal to <code>$arg2</code>.</p><p>The timezone of the result is computed as follows:</p><ulist><item><p>If neither argument has a timezone, the result has no timezone.</p></item><item><p>If exactly one of the arguments has a timezone, or if both arguments have the same
                  timezone, the result has this timezone.</p></item></ulist></def></gitem><gitem><label>Error Conditions</label><def><p>A dynamic error is raised <errorref class="RG" code="0008"/> if the two arguments both
            have timezones and the timezones are different. </p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>fn:dateTime(xs:date("1999-12-31"),
                  xs:time("12:00:00"))</code> returns <code>xs:dateTime("1999-12-31T12:00:00")</code>.</p><p>The expression <code>fn:dateTime(xs:date("1999-12-31"),
                  xs:time("24:00:00"))</code> returns <code>xs:dateTime("1999-12-31T00:00:00")</code>. <emph>(This is because <code>"24:00:00"</code> is an alternate lexical form
                  for <code>"00:00:00"</code>).</emph></p></def></gitem></glist></div3></div2><div2 id="comp.datetime"><head>Comparison operators on duration, date and time values</head><table class="index"><thead><tr><th rowspan="1" colspan="1">Function</th><th rowspan="1" colspan="1">Meaning</th></tr></thead><tbody><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">op:dateTime-equal</code></td><td rowspan="1" colspan="1">Returns true if the two supplied <code>xs:dateTime</code> values refer to the same
            instant in time.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">op:dateTime-less-than</code></td><td rowspan="1" colspan="1">Returns <code>true</code> if the first argument represents an earlier instant in time
            than the second argument.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">op:dateTime-greater-than</code></td><td rowspan="1" colspan="1">Returns <code>true</code> if the first argument represents a later instant in time than
            the second argument.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">op:date-equal</code></td><td rowspan="1" colspan="1">Returns <code>true</code> if and only if the starting instants of the two supplied
               <code>xs:date</code> values are the same.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">op:date-less-than</code></td><td rowspan="1" colspan="1">Returns <code>true</code> if and only if the starting instant of <code>$arg1</code> is
            less than the starting instant of <code>$arg2</code>. Returns <code>false</code>
            otherwise.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">op:date-greater-than</code></td><td rowspan="1" colspan="1">Returns <code>true</code> if and only if the starting instant of <code>$arg1</code> is
            greater than the starting instant of <code>$arg2</code>. Returns <code>false</code>
            otherwise.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">op:time-equal</code></td><td rowspan="1" colspan="1">Returns <code>true</code> if the two <code>xs:time</code> values represent the same
            instant in time, when treated as being times on the same date, before adjusting the
            timezone.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">op:time-less-than</code></td><td rowspan="1" colspan="1">Returns <code>true</code> if the first <code>xs:time</code> value represents an earlier
            instant in time than the second, when both are treated as being times on the same date,
            before adjusting the timezone.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">op:time-greater-than</code></td><td rowspan="1" colspan="1">Returns <code>true</code> if the first <code>xs:time</code> value represents a later
            instant in time than the second, when both are treated as being times on the same date,
            before adjusting the timezone.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">op:gYearMonth-equal</code></td><td rowspan="1" colspan="1">Returns true if the two <code>xs:gYearMonth</code> values have the same starting
            instant.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">op:gYear-equal</code></td><td rowspan="1" colspan="1">Returns true if the two <code>xs:gYear</code> values have the same starting instant.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">op:gMonthDay-equal</code></td><td rowspan="1" colspan="1">Returns true if the two <code>xs:gMonthDay</code> values have the same starting instant,
            when considered as days in the same year.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">op:gMonth-equal</code></td><td rowspan="1" colspan="1">Returns true if the two <code>xs:gMonth</code> values have the same starting instant,
            when considered as months in the same year.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">op:gDay-equal</code></td><td rowspan="1" colspan="1">Returns true if the two <code>xs:gDay</code> values have the same starting instant, when
            considered as days in the same month of the same year.</td></tr></tbody></table><p>The following comparison operators are defined on the <bibref ref="xmlschema-2"/>
                    date/time datatypes. Each operator takes two operands of the same
                    type and returns an <code>xs:boolean</code> result.</p><p>
               <bibref ref="xmlschema-2"/> also states that the
                    order relation on date and time datatypes is
                    not a total order but a partial order because these
datatypes may or may not have a timezone.  This is handled as follows.
If either operand to a comparison function on date or time values does not have
                    an (explicit) timezone then, for the purpose of the operation, an implicit
                    timezone, provided by the dynamic context <xspecref spec="XP31" ref="id-xp-evaluation-context-components"/>, is assumed to be present as part of
                    the value. This creates a total order for all date and time values.</p><p>An <code>xs:dateTime</code> can be considered to consist of seven components:
<code>year</code>, <code>month</code>, <code>day</code>, <code>hour</code>, <code>minute</code>, 
<code>second</code> and <code>timezone</code>.  For <code>xs:dateTime</code> six components (<code>year</code>, 
<code>month</code>, <code>day</code>, <code>hour</code>, <code>minute</code> and <code>second</code>) are required  
and  <code>timezone</code> is optional.   For other date/time values, of the first six components, some are required 
			   and others must be <xtermref ref="dt-absent" spec="DM31">absent</xtermref>.  
			   <code>Timezone</code> is always optional.  For example, for <code>xs:date</code>, 
the <code>year</code>, <code>month</code> and <code>day</code> components are required and <code>hour</code>, 
<code>minute</code> and <code>second</code> components must be absent;  for <code>xs:time</code> the <code>hour</code>, 
<code>minute</code> and <code>second</code> components are required and <code>year</code>, <code>month</code> and 
<code>day</code> are missing;  for <code>xs:gDay</code>, <code>day</code> is required and <code>year</code>, 
<code>month</code>, <code>hour</code>, <code>minute</code> and <code>second</code> are missing.</p><note><p>In <bibref ref="xmlschema11-2"/>, a new <code>explicitTimezone</code> facet is available with values
            <code>optional</code>, <code>required</code>, or <code>prohibited</code> to 
            enable the timezone to be defined as mandatory or disallowed.</p></note><p>Values of the date/time datatypes <code>xs:time</code>, <code>xs:gMonthDay</code>, <code>xs:gMonth</code>, 
			and <code>xs:gDay</code>, can be considered to represent a sequence of recurring time instants or time periods.  
			An <code>xs:time</code> occurs every day.  An <code>xs:gMonth</code> occurs every year.  Comparison operators 
			on these datatypes compare the starting instants of equivalent occurrences in the recurring series.  
			These <code>xs:dateTime</code> values are calculated  as described below.</p><p>Comparison operators on <code>xs:date</code>, <code>xs:gYearMonth</code> and <code>xs:gYear</code> compare 
			their starting instants. These <code>xs:dateTime</code> values are calculated  as described below.</p><p>The starting instant of an occurrence of a date/time value is an <code>xs:dateTime</code> 
             calculated by filling 
			in the missing components of the local value from a reference <code>xs:dateTime</code>.  An example of a suitable
         reference <code>xs:dateTime</code> is <code>1972-01-01T00:00:00</code>. Then, for example, the starting
             instant corresponding to the <code>xs:date</code> value <code>2009-03-12</code> is 
             <code>2009-03-12T00:00:00</code>; the starting instant corresponding to the <code>xs:time</code> value
             <code>13:30:02</code> is <code>1972-01-01T13:30:02</code>; and the starting instant corresponding to the
             <code>gMonthDay</code> value <code>--02-29</code> is <code>1972-02-29T00:00:00</code> (which explains
             why a leap year was chosen for the reference).</p><note><p>In the previous version of this specification, the reference date/time chosen was
         <code>1972-12-31T00:00:00</code>. While this gives the same results, it produces a "starting instant" for 
         a <code>gMonth</code> or <code>gMonthDay</code> that bears no
         relation to the ordinary meaning of the term, and it also required special handling of short months. 
         The original choice was made to allow for leap seconds; but since leap seconds are not recognized 
         in date/time arithmetic, this is not actually necessary.</p></note><p>If the <code>xs:time</code> value written as
			<code>24:00:00</code> is to be compared, filling in the missing components gives <code>1972-01-01T00:00:00</code>, 
			because <code>24:00:00</code> is an alternative representation of <code>00:00:00</code> (the lexical value 
			<code>"24:00:00"</code> is
			converted to the time components {0,0,0} before the missing components are filled
			in). This has the consequence that when ordering <code>xs:time</code> values, 
			<code>24:00:00</code> is
			considered to be earlier than <code>23:59:59</code>. However, when ordering 
			<code>xs:dateTime</code>
			values, a time component of <code>24:00:00</code> is considered equivalent to <code>00:00:00</code> on the
			following day.</p><p>Note that the reference <code>xs:dateTime</code> does not have a timezone.  The <code>timezone</code> component 
			is never filled in from the reference <code>xs:dateTime</code>.  In some cases, if the date/time value does not 
			have a timezone, the implicit timezone from the dynamic context is used as the timezone.</p><note><p>This specification uses the reference <code>xs:dateTime 1972-01-01T00:00:00</code> in the description of the 
			   comparison operators.  Implementations may use other reference <code>xs:dateTime</code> values 
			   as long as they yield the same results.  The reference <code>xs:dateTime</code> used must meet the following 
			   constraints:  when it is used to supply components into <code>xs:gMonthDay</code> values, the year must allow 
			   for February 29 and so must be a leap year; when it is used to supply missing components into <code>xs:gDay</code> 
			   values, the month must allow for 31 days.  Different reference <code>xs:dateTime</code> values may be used for 
			   different operators.</p></note><div3 id="func-dateTime-equal"><head>op:dateTime-equal</head><glist><gitem><label>Summary</label><def><p>Returns true if the two supplied <code>xs:dateTime</code> values refer to the same
            instant in time.</p></def></gitem><gitem><label>Operator Mapping</label><def><p>Defines the
         semantics of the "eq" operator when applied to two <code>xs:dateTime</code> values. Also
         used in the definition of the "ne", "le" and "ge" operators.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="dateTime-equal" return-type="xs:boolean" isOp="yes" prefix="op" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg1" type="xs:dateTime"/><arg name="arg2" type="xs:dateTime"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-dependent">context-dependent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>.  It depends on 
		implicit timezone.
	</p></def></gitem><gitem><label>Rules</label><def><p>If either <code>$arg1</code> or <code>$arg2</code> has no timezone component, the
            effective value of the argument is obtained by substituting the implicit timezone from
            the dynamic evaluation context.</p><p>The function then returns <code>true</code> if and only if the effective value of
               <code>$arg1</code> is equal to the effective value of <code>$arg2</code> according to
            the algorithm defined in section 3.2.7.4 of <bibref ref="xmlschema-2"/>
            <quote>Order relation on dateTime</quote> for <code>xs:dateTime</code> values with
            timezones. Otherwise the function returns <code>false</code>.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>Assume that the dynamic context provides an implicit timezone value of
                  <code>-05:00</code></p><p>The expression <code>op:dateTime-equal(xs:dateTime("2002-04-02T12:00:00-01:00"),
                  xs:dateTime("2002-04-02T17:00:00+04:00"))</code> returns <code>true()</code>.</p><p>The expression <code>op:dateTime-equal(xs:dateTime("2002-04-02T12:00:00"),
                  xs:dateTime("2002-04-02T23:00:00+06:00"))</code> returns <code>true()</code>.</p><p>The expression <code>op:dateTime-equal(xs:dateTime("2002-04-02T12:00:00"),
                  xs:dateTime("2002-04-02T17:00:00"))</code> returns <code>false()</code>.</p><p>The expression <code>op:dateTime-equal(xs:dateTime("2002-04-02T12:00:00"),
                  xs:dateTime("2002-04-02T12:00:00"))</code> returns <code>true()</code>.</p><p>The expression <code>op:dateTime-equal(xs:dateTime("2002-04-02T23:00:00-04:00"),
                  xs:dateTime("2002-04-03T02:00:00-01:00"))</code> returns <code>true()</code>.</p><p>The expression <code>op:dateTime-equal(xs:dateTime("1999-12-31T24:00:00"),
                  xs:dateTime("2000-01-01T00:00:00"))</code> returns <code>true()</code>.</p><p>The expression <code>op:dateTime-equal(xs:dateTime("2005-04-04T24:00:00"),
                  xs:dateTime("2005-04-04T00:00:00"))</code> returns <code>false()</code>.</p></def></gitem></glist></div3><div3 id="func-dateTime-less-than"><head>op:dateTime-less-than</head><glist><gitem><label>Summary</label><def><p>Returns <code>true</code> if the first argument represents an earlier instant in time
            than the second argument.</p></def></gitem><gitem><label>Operator Mapping</label><def><p>Defines the
         semantics of the "lt" operator when applied to two <code>xs:dateTime</code> values. Also
         used in the definition of the "ge" operator.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="dateTime-less-than" return-type="xs:boolean" isOp="yes" prefix="op" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg1" type="xs:dateTime"/><arg name="arg2" type="xs:dateTime"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-dependent">context-dependent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>.  It depends on 
		implicit timezone.
	</p></def></gitem><gitem><label>Rules</label><def><p>If either <code>$arg1</code> or <code>$arg2</code> has no timezone component, the
            effective value of the argument is obtained by substituting the implicit timezone from
            the dynamic evaluation context.</p><p>The function then returns <code>true</code> if and only if the effective value of
               <code>$arg1</code> is less than the effective value of <code>$arg2</code> according
            to the algorithm defined in section 3.2.7.4 of <bibref ref="xmlschema-2"/>
            <quote>Order relation on dateTime</quote> for <code>xs:dateTime</code> values with
            timezones. Otherwise the function returns <code>false</code>.</p></def></gitem></glist></div3><div3 id="func-dateTime-greater-than"><head>op:dateTime-greater-than</head><glist><gitem><label>Summary</label><def><p>Returns <code>true</code> if the first argument represents a later instant in time than
            the second argument.</p></def></gitem><gitem><label>Operator Mapping</label><def><p>Defines the
         semantics of the "gt" operator when applied to two <code>xs:dateTime</code> values. Also
         used in the definition of the "le" operator.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="dateTime-greater-than" return-type="xs:boolean" isOp="yes" prefix="op" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg1" type="xs:dateTime"/><arg name="arg2" type="xs:dateTime"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-dependent">context-dependent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>.  It depends on 
		implicit timezone.
	</p></def></gitem><gitem><label>Rules</label><def><p>The function call <code>op:dateTime-greater-than($A, $B)</code> is defined to return the
            same result as <code>op:dateTime-less-than($B, $A)</code></p></def></gitem></glist></div3><div3 id="func-date-equal"><head>op:date-equal</head><glist><gitem><label>Summary</label><def><p>Returns <code>true</code> if and only if the starting instants of the two supplied
               <code>xs:date</code> values are the same.</p></def></gitem><gitem><label>Operator Mapping</label><def><p>Defines the
         semantics of the "eq" operator when applied to two <code>xs:date</code> values. Also used
         in the definition of the "ne", "le" and "ge" operators.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="date-equal" return-type="xs:boolean" isOp="yes" prefix="op" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg1" type="xs:date"/><arg name="arg2" type="xs:date"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-dependent">context-dependent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>.  It depends on 
		implicit timezone.
	</p></def></gitem><gitem><label>Rules</label><def><p>The starting instant of an <code>xs:date</code> is the <code>xs:dateTime</code> at time
               <code>00:00:00</code> on that date.</p><p>The function returns the result of the expression:</p><eg xml:space="preserve">op:dateTime-equal(xs:dateTime($arg1), xs:dateTime($arg2))</eg></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>op:date-equal(xs:date("2004-12-25Z"),
                  xs:date("2004-12-25+07:00"))</code> returns <code>false()</code>. <emph>(The starting instants are
                     <code>xs:dateTime("2004-12-25T00:00:00Z")</code> and
                     <code>xs:dateTime("2004-12-25T00:00:00+07:00")</code>. These are normalized to
                     <code>xs:dateTime("2004-12-25T00:00:00Z")</code> and
                     <code>xs:dateTime("2004-12-24T17:00:00Z")</code>. ).</emph></p><p>The expression <code>op:date-equal(xs:date("2004-12-25-12:00"),
                  xs:date("2004-12-26+12:00"))</code> returns <code>true()</code>.</p></def></gitem></glist></div3><div3 id="func-date-less-than"><head>op:date-less-than</head><glist><gitem><label>Summary</label><def><p>Returns <code>true</code> if and only if the starting instant of <code>$arg1</code> is
            less than the starting instant of <code>$arg2</code>. Returns <code>false</code>
            otherwise.</p></def></gitem><gitem><label>Operator Mapping</label><def><p>Defines the semantics
         of the "lt" operator when applied to two <code>xs:date</code> values. Also used in the
         definition of the "ge" operator.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="date-less-than" return-type="xs:boolean" isOp="yes" prefix="op" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg1" type="xs:date"/><arg name="arg2" type="xs:date"/></proto></example></def></gitem><gitem><label>Rules</label><def><p>The starting instant of an <code>xs:date</code> is the <code>xs:dateTime</code> at time
               <code>00:00:00</code> on that date.</p><p>The function returns the result of the expression:</p><eg xml:space="preserve">op:dateTime-less-than(xs:dateTime($arg1), xs:dateTime($arg2))</eg></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>op:date-less-than(xs:date("2004-12-25Z"),
                  xs:date("2004-12-25-05:00"))</code> returns <code>true()</code>.</p><p>The expression <code>op:date-less-than(xs:date("2004-12-25-12:00"),
                  xs:date("2004-12-26+12:00"))</code> returns <code>false()</code>.</p></def></gitem></glist></div3><div3 id="func-date-greater-than"><head>op:date-greater-than</head><glist><gitem><label>Summary</label><def><p>Returns <code>true</code> if and only if the starting instant of <code>$arg1</code> is
            greater than the starting instant of <code>$arg2</code>. Returns <code>false</code>
            otherwise.</p></def></gitem><gitem><label>Operator Mapping</label><def><p>Defines the semantics
         of the "gt" operator when applied to two <code>xs:date</code> values. Also used in the
         definition of the "le" operator.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="date-greater-than" return-type="xs:boolean" isOp="yes" prefix="op" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg1" type="xs:date"/><arg name="arg2" type="xs:date"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-dependent">context-dependent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>.  It depends on 
		implicit timezone.
	</p></def></gitem><gitem><label>Rules</label><def><p>The function call <code>op:date-greater-than($A, $B)</code> is defined to return the
            same result as <code>op:date-less-than($B, $A)</code></p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>op:date-greater-than(xs:date("2004-12-25Z"),
                  xs:date("2004-12-25+07:00"))</code> returns <code>true()</code>.</p><p>The expression <code>op:date-greater-than(xs:date("2004-12-25-12:00"),
                  xs:date("2004-12-26+12:00"))</code> returns <code>false()</code>.</p></def></gitem></glist></div3><div3 id="func-time-equal"><head>op:time-equal</head><glist><gitem><label>Summary</label><def><p>Returns <code>true</code> if the two <code>xs:time</code> values represent the same
            instant in time, when treated as being times on the same date, before adjusting the
            timezone.</p></def></gitem><gitem><label>Operator Mapping</label><def><p>Defines the
         semantics of the "eq" operator when applied to two <code>xs:time</code> values. Also used
         in the definition of the "ne", "le" and "ge" operators.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="time-equal" return-type="xs:boolean" isOp="yes" prefix="op" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg1" type="xs:time"/><arg name="arg2" type="xs:time"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-dependent">context-dependent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>.  It depends on 
		implicit timezone.
	</p></def></gitem><gitem><label>Rules</label><def><p>Each of the supplied <code>xs:time</code> values is expanded to an
               <code>xs:dateTime</code> value by associating the time with an arbitrary date. The
            function returns the result of comparing these two <code>xs:dateTime</code> values using
               <code>op:dateTime-equal</code>.</p><p>The result of the function is thus the same as the value of the expression:</p><eg xml:space="preserve">op:dateTime-equal(
        fn:dateTime(xs:date('1972-12-31'), $arg1), 
        fn:dateTime(xs:date('1972-12-31'), $arg2))</eg></def></gitem><gitem><label>Examples</label><def role="example"><p>Assume that the date components from the reference <code>xs:dateTime</code>
               correspond to <code>1972-12-31</code>.</p><p>The expression <code>op:time-equal(xs:time("08:00:00+09:00"),
                  xs:time("17:00:00-06:00"))</code> returns <code>false()</code>. <emph>(The <code>xs:dateTime</code>s calculated using the reference date
                  components are <code>1972-12-31T08:00:00+09:00</code> and
                     <code>1972-12-31T17:00:00-06:00</code>. These normalize to
                     <code>1972-12-30T23:00:00Z</code> and <code>1972-12-31T23:00:00Z</code>.
               ).</emph></p><p>The expression <code>op:time-equal(xs:time("21:30:00+10:30"),
                  xs:time("06:00:00-05:00"))</code> returns <code>true()</code>.</p><p>The expression <code>op:time-equal(xs:time("24:00:00+01:00"),
                  xs:time("00:00:00+01:00"))</code> returns <code>true()</code>. <emph>(This not the result one might expect. For <code>xs:dateTime</code>
                  values, a time of <code>24:00:00</code> is equivalent to <code>00:00:00</code> on
                  the following day. For <code>xs:time</code>, the normalization from
                     <code>24:00:00</code> to <code>00:00:00</code> happens before the
                     <code>xs:time</code> is converted into an <code>xs:dateTime</code> for the
                  purpose of the equality comparison. For <code>xs:time</code>, any operation on
                     <code>24:00:00</code> produces the same result as the same operation on
                     <code>00:00:00</code> because these are two different lexical representations
                  of the same value. ).</emph></p></def></gitem></glist></div3><div3 id="func-time-less-than"><head>op:time-less-than</head><glist><gitem><label>Summary</label><def><p>Returns <code>true</code> if the first <code>xs:time</code> value represents an earlier
            instant in time than the second, when both are treated as being times on the same date,
            before adjusting the timezone.</p></def></gitem><gitem><label>Operator Mapping</label><def><p>Defines the semantics
         of the "lt" operator when applied to two <code>xs:time</code> values. Also used in the
         definition of the "ge" operator.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="time-less-than" return-type="xs:boolean" isOp="yes" prefix="op" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg1" type="xs:time"/><arg name="arg2" type="xs:time"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-dependent">context-dependent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>.  It depends on 
		implicit timezone.
	</p></def></gitem><gitem><label>Rules</label><def><p>Each of the supplied <code>xs:time</code> values is expanded to an
               <code>xs:dateTime</code> value by associating the time with an arbitrary date. The
            function returns the result of comparing these two <code>xs:dateTime</code> values using
               <code>op:dateTime-less-than</code>.</p><p>The result of the function is thus the same as the value of the expression:</p><eg xml:space="preserve">op:dateTime-less-than(
        fn:dateTime(xs:date('1972-12-31'), $arg1), 
        fn:dateTime(xs:date('1972-12-31'), $arg2))</eg></def></gitem><gitem><label>Examples</label><def role="example"><p>Assume that the dynamic context provides an implicit timezone value of
                  <code>-05:00</code>.</p><p>The expression <code>op:time-less-than(xs:time("12:00:00"),
                  xs:time("23:00:00+06:00"))</code> returns <code>false()</code>.</p><p>The expression <code>op:time-less-than(xs:time("11:00:00"),
                  xs:time("17:00:00Z"))</code> returns <code>true()</code>.</p><p>The expression <code>op:time-less-than(xs:time("23:59:59"),
                  xs:time("24:00:00"))</code> returns <code>false()</code>.</p></def></gitem></glist></div3><div3 id="func-time-greater-than"><head>op:time-greater-than</head><glist><gitem><label>Summary</label><def><p>Returns <code>true</code> if the first <code>xs:time</code> value represents a later
            instant in time than the second, when both are treated as being times on the same date,
            before adjusting the timezone.</p></def></gitem><gitem><label>Operator Mapping</label><def><p>Defines the semantics
         of the "gt" operator when applied to two <code>xs:time</code> values. Also used in the
         definition of the "le" operator.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="time-greater-than" return-type="xs:boolean" isOp="yes" prefix="op" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg1" type="xs:time"/><arg name="arg2" type="xs:time"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-dependent">context-dependent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>.  It depends on 
		implicit timezone.
	</p></def></gitem><gitem><label>Rules</label><def><p>The function call <code>op:time-greater-than($A, $B)</code> is defined to return the
            same result as <code>op:time-less-than($B, $A)</code></p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>op:time-greater-than(xs:time("08:00:00+09:00"),
                  xs:time("17:00:00-06:00"))</code> returns <code>false()</code>.</p></def></gitem></glist></div3><div3 id="func-gYearMonth-equal"><head>op:gYearMonth-equal</head><glist><gitem><label>Summary</label><def><p>Returns true if the two <code>xs:gYearMonth</code> values have the same starting
            instant.</p></def></gitem><gitem><label>Operator Mapping</label><def><p>Defines the
         semantics of the "eq" operator when applied to two <code>xs:gYearMonth</code> values. Also
         used in the definition of the "ne" operator.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="gYearMonth-equal" return-type="xs:boolean" isOp="yes" prefix="op" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg1" type="xs:gYearMonth"/><arg name="arg2" type="xs:gYearMonth"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-dependent">context-dependent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>.  It depends on 
		implicit timezone.
	</p></def></gitem><gitem><label>Rules</label><def><p>The starting instants of <code>$arg1</code> and <code>$arg2</code> are calculated by
            supplying the missing components of <code>$arg1</code> and <code>$arg2</code> from the
               <code>xs:dateTime</code> template <code>xxxx-xx-01T00:00:00</code>. The function
            returns the result of comparing these two starting instants using
               <code>op:dateTime-equal</code>.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>Assume that the dynamic context provides an implicit timezone value of
                  <code>-05:00</code>.</p><p><code>op:gYearMonth-equal(xs:gYearMonth("1986-02"), xs:gYearMonth("1986-03"))</code>
               returns <code>false()</code>. The starting instants are
                  <code>1986-02-01T00:00:00-05:00</code> and <code>1986-03-01T00:00:00</code>,
               respectively.</p><p><code>op:gYearMonth-equal(xs:gYearMonth("1978-03"), xs:gYearMonth("1986-03Z"))</code>
               returns <code>false()</code>. The starting instants are
                  <code>1978-03-01T00:00:00-05:00</code> and <code>1986-03-01T00:00:00Z</code>,
               respectively.</p></def></gitem></glist></div3><div3 id="func-gYear-equal"><head>op:gYear-equal</head><glist><gitem><label>Summary</label><def><p>Returns true if the two <code>xs:gYear</code> values have the same starting instant.</p></def></gitem><gitem><label>Operator Mapping</label><def><p>Defines the semantics
         of the "eq" operator when applied to two <code>xs:gYear</code> values. Also used in the
         definition of the "ne" operator.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="gYear-equal" return-type="xs:boolean" isOp="yes" prefix="op" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg1" type="xs:gYear"/><arg name="arg2" type="xs:gYear"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-dependent">context-dependent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>.  It depends on 
		implicit timezone.
	</p></def></gitem><gitem><label>Rules</label><def><p>The starting instants of <code>$arg1</code> and <code>$arg2</code> are calculated by
            supplying the missing components of <code>$arg1</code> and <code>$arg2</code> from the
               <code>xs:dateTime</code> template <code>xxxx-01-01T00:00:00</code>. The function
            returns the result of comparing these two starting instants using
               <code>op:dateTime-equal</code>.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>Assume that the dynamic context provides an implicit timezone value of
                  <code>-05:00</code>. Assume, also, that the <code>xs:dateTime</code> template is
                  <code>xxxx-01-01T00:00:00</code>. </p><p><code>op:gYear-equal(xs:gYear("2005-12:00"), xs:gYear("2005+12:00"))</code> returns
                  <code>false()</code>. The starting instants are
                  <code>2005-01-01T00:00:00-12:00</code> and <code>2005-01-01T00:00:00+12:00</code>,
               respectively, and normalize to <code>2005-01-01T12:00:00Z</code> and
                  <code>2004-12-31T12:00:00Z</code>.</p><p>The expression <code>op:gYear-equal(xs:gYear("1976-05:00"),
                  xs:gYear("1976"))</code> returns <code>true()</code>.</p></def></gitem></glist></div3><div3 id="func-gMonthDay-equal"><head>op:gMonthDay-equal</head><glist><gitem><label>Summary</label><def><p>Returns true if the two <code>xs:gMonthDay</code> values have the same starting instant,
            when considered as days in the same year.</p></def></gitem><gitem><label>Operator Mapping</label><def><p>Defines the
         semantics of the "eq" operator when applied to two <code>xs:gMonthDay</code> values. Also
         used in the definition of the "ne" operator.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="gMonthDay-equal" return-type="xs:boolean" isOp="yes" prefix="op" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg1" type="xs:gMonthDay"/><arg name="arg2" type="xs:gMonthDay"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-dependent">context-dependent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>.  It depends on 
		implicit timezone.
	</p></def></gitem><gitem><label>Rules</label><def><p>The starting instants of <code>$arg1</code> and <code>$arg2</code> are calculated by
            supplying the missing components of <code>$arg1</code> and <code>$arg2</code> from the
               <code>xs:dateTime</code> template <code>1972-xx-xxT00:00:00</code> or an equivalent.
            The function returns the result of comparing these two starting instants using
               <code>op:dateTime-equal</code>.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>Assume that the dynamic context provides an implicit timezone value of
                  <code>-05:00</code>. Assume for the purposes of illustration that the
                  <code>xs:dateTime</code> template used is <code>1972-xx-xxT00:00:00</code> (this
               does not affect the result). </p><p>The expression <code>op:gMonthDay-equal(xs:gMonthDay("--12-25-14:00"),
                  xs:gMonthDay("--12-26+10:00"))</code> returns <code>true()</code>. <emph>( The starting instants are <code>1972-12-25T00:00:00-14:00</code> and
                     <code>1972-12-26T00:00:00+10:00</code>, respectively, and normalize to
                     <code>1972-12-25T14:00:00Z</code> and <code>1972-12-25T14:00:00Z</code>.
               ).</emph></p><p>The expression <code>op:gMonthDay-equal(xs:gMonthDay("--12-25"),
                  xs:gMonthDay("--12-26Z"))</code> returns <code>false()</code>.</p></def></gitem></glist></div3><div3 id="func-gMonth-equal"><head>op:gMonth-equal</head><glist><gitem><label>Summary</label><def><p>Returns true if the two <code>xs:gMonth</code> values have the same starting instant,
            when considered as months in the same year.</p></def></gitem><gitem><label>Operator Mapping</label><def><p>Defines the
         semantics of the "eq" operator when applied to two <code>xs:gMonth</code> values. Also used
         in the definition of the "ne" operator.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="gMonth-equal" return-type="xs:boolean" isOp="yes" prefix="op" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg1" type="xs:gMonth"/><arg name="arg2" type="xs:gMonth"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-dependent">context-dependent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>.  It depends on 
		implicit timezone.
	</p></def></gitem><gitem><label>Rules</label><def><p>The starting instants of <code>$arg1</code> and <code>$arg2</code> are calculated by
            supplying the missing components of <code>$arg1</code> and <code>$arg2</code> from the
               <code>xs:dateTime</code> template <code>1972-xx-01T00:00:00</code> or an equivalent.
            The function returns the result of comparing these two starting instants using
               <code>op:dateTime-equal</code>.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>Assume that the dynamic context provides an implicit timezone value of
                  <code>-05:00</code>. Assume, also, that the <code>xs:dateTime</code> template
               chosen is <code>1972-xx-01T00:00:00</code>. </p><p>The expression <code>op:gMonth-equal(xs:gMonth("--12-14:00"),
                  xs:gMonth("--12+10:00"))</code> returns <code>false()</code>. <emph>( The starting instants are <code>1972-12-01T00:00:00-14:00</code> and
                     <code>1972-12-01T00:00:00+10:00</code>, respectively, and normalize to
                     <code>1972-11-30T14:00:00Z</code> and <code>1972-12-01T14:00:00Z</code>.
               ).</emph></p><p>The expression <code>op:gMonth-equal(xs:gMonth("--12"),
                  xs:gMonth("--12Z"))</code> returns <code>false()</code>.</p></def></gitem></glist></div3><div3 id="func-gDay-equal"><head>op:gDay-equal</head><glist><gitem><label>Summary</label><def><p>Returns true if the two <code>xs:gDay</code> values have the same starting instant, when
            considered as days in the same month of the same year.</p></def></gitem><gitem><label>Operator Mapping</label><def><p>Defines the semantics
         of the "eq" operator when applied to two <code>xs:gDay</code> values. Also used in the
         definition of the "ne" operator.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="gDay-equal" return-type="xs:boolean" isOp="yes" prefix="op" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg1" type="xs:gDay"/><arg name="arg2" type="xs:gDay"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-dependent">context-dependent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>.  It depends on 
		implicit timezone.
	</p></def></gitem><gitem><label>Rules</label><def><p>The starting instants of <code>$arg1</code> and <code>$arg2</code> are calculated by
            supplying the missing components of <code>$arg1</code> and <code>$arg2</code> from the
               <code>xs:dateTime</code> template <code>1972-12-xxT00:00:00</code> or an equivalent.
            The function returns the result of comparing these two starting instants using
               <code>op:dateTime-equal</code>.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>Assume that the dynamic context provides an implicit timezone value of
                  <code>-05:00</code>. Assume, also, that the <code>xs:dateTime</code> template is
                  <code>1972-12-xxT00:00:00</code>. </p><p>The expression <code>op:gDay-equal(xs:gDay("---25-14:00"),
                  xs:gDay("---25+10:00"))</code> returns <code>false()</code>. <emph>( The starting instants are <code>1972-12-25T00:00:00-14:00</code> and
                     <code>1972-12-25T00:00:00+10:00</code>, respectively, and normalize to
                     <code>1972-12-25T14:00:00Z</code> and <code>1972-12-24T14:00:00Z</code>.
               ).</emph></p><p>The expression <code>op:gDay-equal(xs:gDay("---12"), xs:gDay("---12Z"))</code> returns <code>false()</code>.</p></def></gitem></glist></div3></div2><div2 id="component-extraction-dateTime"><head>Component extraction functions on dates and times</head><p>The date and time datatypes may be considered to be composite datatypes
                    in that they contain distinct properties or components. The extraction functions specified
                    below extract a single component from a date or time value. In all cases 
					the local value (that is, the original value as written, 
					without any timezone adjustment) is used. </p><note><p>A time written as <code>24:00:00</code> is treated as <code>00:00:00</code> on the
			following day.</p></note><table class="index"><thead><tr><th rowspan="1" colspan="1">Function</th><th rowspan="1" colspan="1">Meaning</th></tr></thead><tbody><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:year-from-dateTime</code></td><td rowspan="1" colspan="1">Returns the year component of an <code>xs:dateTime</code>.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:month-from-dateTime</code></td><td rowspan="1" colspan="1">Returns the month component of an <code>xs:dateTime</code>.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:day-from-dateTime</code></td><td rowspan="1" colspan="1">Returns the day component of an <code>xs:dateTime</code>.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:hours-from-dateTime</code></td><td rowspan="1" colspan="1">Returns the hours component of an <code>xs:dateTime</code>.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:minutes-from-dateTime</code></td><td rowspan="1" colspan="1">Returns the minute component of an <code>xs:dateTime</code>.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:seconds-from-dateTime</code></td><td rowspan="1" colspan="1">Returns the seconds component of an <code>xs:dateTime</code>.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:timezone-from-dateTime</code></td><td rowspan="1" colspan="1">Returns the timezone component of an <code>xs:dateTime</code>.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:year-from-date</code></td><td rowspan="1" colspan="1">Returns the year component of an <code>xs:date</code>.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:month-from-date</code></td><td rowspan="1" colspan="1">Returns the month component of an <code>xs:date</code>.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:day-from-date</code></td><td rowspan="1" colspan="1">Returns the day component of an <code>xs:date</code>.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:timezone-from-date</code></td><td rowspan="1" colspan="1">Returns the timezone component of an <code>xs:date</code>.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:hours-from-time</code></td><td rowspan="1" colspan="1">Returns the hours component of an <code>xs:time</code>.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:minutes-from-time</code></td><td rowspan="1" colspan="1">Returns the minutes component of an <code>xs:time</code>.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:seconds-from-time</code></td><td rowspan="1" colspan="1">Returns the seconds component of an <code>xs:time</code>.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:timezone-from-time</code></td><td rowspan="1" colspan="1">Returns the timezone component of an <code>xs:time</code>.</td></tr></tbody></table><div3 id="func-year-from-dateTime"><head>fn:year-from-dateTime</head><glist><gitem><label>Summary</label><def><p>Returns the year component of an <code>xs:dateTime</code>.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="year-from-dateTime" return-type="xs:integer?" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg" type="xs:dateTime?"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>If <code>$arg</code> is the empty sequence, the function returns the empty sequence.</p><p>Otherwise, the function returns an <code>xs:integer</code> representing the year
            component in the local value of <code>$arg</code>. The result may be negative.</p></def></gitem><gitem><label>Notes</label><def><p role="note">Ignoring complications that arise with midnight on the last day
            of the year, the year returned is the same numeric value that appears in the lexical
         representation, which for negative years means the meaning may vary depending on whether
         XSD 1.0 or XSD 1.1 conventions are in use.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>fn:year-from-dateTime(xs:dateTime("1999-05-31T13:20:00-05:00"))</code> returns <code>1999</code>.</p><p>The expression <code>fn:year-from-dateTime(xs:dateTime("1999-05-31T21:30:00-05:00"))</code> returns <code>1999</code>.</p><p>The expression <code>fn:year-from-dateTime(xs:dateTime("1999-12-31T19:20:00"))</code> returns <code>1999</code>.</p><p>The expression <code>fn:year-from-dateTime(xs:dateTime("1999-12-31T24:00:00"))</code> returns <code>2000</code>.</p><p>The expression <code>fn:year-from-dateTime(xs:dateTime("-0002-06-06T00:00:00"))</code> returns <code>-2</code>. <emph>(The result is the same whether XSD 1.0 or 1.1 is in use, despite
                  the absence of a year 0 in the XSD 1.0 value space.)</emph></p></def></gitem></glist></div3><div3 id="func-month-from-dateTime"><head>fn:month-from-dateTime</head><glist><gitem><label>Summary</label><def><p>Returns the month component of an <code>xs:dateTime</code>.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="month-from-dateTime" return-type="xs:integer?" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg" type="xs:dateTime?"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>If <code>$arg</code> is the empty sequence, the function returns the empty sequence.</p><p>Otherwise, the function returns an <code>xs:integer</code> between 1 and 12, both
            inclusive, representing the month component in the local value of <code>$arg</code>.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>fn:month-from-dateTime(xs:dateTime("1999-05-31T13:20:00-05:00"))</code> returns <code>5</code>.</p><p>The expression <code>fn:month-from-dateTime(xs:dateTime("1999-12-31T19:20:00-05:00"))</code> returns <code>12</code>.</p><p>The expression <code>fn:month-from-dateTime(fn:adjust-dateTime-to-timezone(xs:dateTime("1999-12-31T19:20:00-05:00"),
                  xs:dayTimeDuration("PT0S")))</code> returns <code>1</code>.</p></def></gitem></glist></div3><div3 id="func-day-from-dateTime"><head>fn:day-from-dateTime</head><glist><gitem><label>Summary</label><def><p>Returns the day component of an <code>xs:dateTime</code>.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="day-from-dateTime" return-type="xs:integer?" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg" type="xs:dateTime?"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>If <code>$arg</code> is the empty sequence, the function returns the empty sequence.</p><p>Otherwise, the function returns an <code>xs:integer</code> between 1 and 31, both
            inclusive, representing the day component in the local value of <code>$arg</code>.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>fn:day-from-dateTime(xs:dateTime("1999-05-31T13:20:00-05:00"))</code> returns <code>31</code>.</p><p>The expression <code>fn:day-from-dateTime(xs:dateTime("1999-12-31T20:00:00-05:00"))</code> returns <code>31</code>.</p><p>The expression <code>fn:day-from-dateTime(fn:adjust-dateTime-to-timezone(xs:dateTime("1999-12-31T19:20:00-05:00"),
                  xs:dayTimeDuration("PT0S")))</code> returns <code>1</code>.</p></def></gitem></glist></div3><div3 id="func-hours-from-dateTime"><head>fn:hours-from-dateTime</head><glist><gitem><label>Summary</label><def><p>Returns the hours component of an <code>xs:dateTime</code>.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="hours-from-dateTime" return-type="xs:integer?" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg" type="xs:dateTime?"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>If <code>$arg</code> is the empty sequence, the function returns the empty sequence.</p><p>Otherwise, the function returns an <code>xs:integer</code> between 0 and 23, both
            inclusive, representing the hours component in the local value of <code>$arg</code>.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>fn:hours-from-dateTime(xs:dateTime("1999-05-31T08:20:00-05:00"))</code> returns <code>8</code>.</p><p>The expression <code>fn:hours-from-dateTime(xs:dateTime("1999-12-31T21:20:00-05:00"))</code> returns <code>21</code>.</p><p>The expression <code>fn:hours-from-dateTime(fn:adjust-dateTime-to-timezone(xs:dateTime("1999-12-31T21:20:00-05:00"),
                  xs:dayTimeDuration("PT0S")))</code> returns <code>2</code>.</p><p>The expression <code>fn:hours-from-dateTime(xs:dateTime("1999-12-31T12:00:00"))</code> returns <code>12</code>.</p><p>The expression <code>fn:hours-from-dateTime(xs:dateTime("1999-12-31T24:00:00"))</code> returns <code>0</code>.</p></def></gitem></glist></div3><div3 id="func-minutes-from-dateTime"><head>fn:minutes-from-dateTime</head><glist><gitem><label>Summary</label><def><p>Returns the minute component of an <code>xs:dateTime</code>.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="minutes-from-dateTime" return-type="xs:integer?" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg" type="xs:dateTime?"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>If <code>$arg</code> is the empty sequence, the function returns the empty sequence.</p><p>Otherwise, the function returns an <code>xs:integer</code> value between 0 and 59, both
            inclusive, representing the minute component in the local value of
            <code>$arg</code>.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>fn:minutes-from-dateTime(xs:dateTime("1999-05-31T13:20:00-05:00"))</code> returns <code>20</code>.</p><p>The expression <code>fn:minutes-from-dateTime(xs:dateTime("1999-05-31T13:30:00+05:30"))</code> returns <code>30</code>.</p></def></gitem></glist></div3><div3 id="func-seconds-from-dateTime"><head>fn:seconds-from-dateTime</head><glist><gitem><label>Summary</label><def><p>Returns the seconds component of an <code>xs:dateTime</code>.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="seconds-from-dateTime" return-type="xs:decimal?" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg" type="xs:dateTime?"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>If <code>$arg</code> is the empty sequence, the function returns the empty sequence.</p><p>Otherwise, the function returns an <code>xs:decimal</code> value greater than or equal
            to zero and less than 60, representing the seconds and fractional seconds in the local
            value of <code>$arg</code>.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>fn:seconds-from-dateTime(xs:dateTime("1999-05-31T13:20:00-05:00"))</code> returns <code>0</code>.</p></def></gitem></glist></div3><div3 id="func-timezone-from-dateTime"><head>fn:timezone-from-dateTime</head><glist><gitem><label>Summary</label><def><p>Returns the timezone component of an <code>xs:dateTime</code>.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="timezone-from-dateTime" return-type="xs:dayTimeDuration?" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg" type="xs:dateTime?"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>If <code>$arg</code> is the empty sequence, the function returns the empty sequence.</p><p>Otherwise, the function returns the timezone component of <code>$arg</code>, if any. If
               <code>$arg</code> has a timezone component, then the result is an
               <code>xs:dayTimeDuration</code> that indicates deviation from UTC; its value may
            range from +14:00 to -14:00 hours, both inclusive. If <code>$arg</code> has no timezone
            component, the result is the empty sequence.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>fn:timezone-from-dateTime(xs:dateTime("1999-05-31T13:20:00-05:00"))</code> returns <code>xs:dayTimeDuration("-PT5H")</code>.</p><p>The expression <code>fn:timezone-from-dateTime(xs:dateTime("2000-06-12T13:20:00Z"))</code> returns <code>xs:dayTimeDuration("PT0S")</code>.</p><p>The expression <code>fn:timezone-from-dateTime(xs:dateTime("2004-08-27T00:00:00"))</code> returns <code>()</code>.</p></def></gitem></glist></div3><div3 id="func-year-from-date"><head>fn:year-from-date</head><glist><gitem><label>Summary</label><def><p>Returns the year component of an <code>xs:date</code>.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="year-from-date" return-type="xs:integer?" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg" type="xs:date?"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>If <code>$arg</code> is the empty sequence, the function returns the empty sequence.</p><p>Otherwise, the function returns an <code>xs:integer</code> representing the year in the
            local value of <code>$arg</code>. The value may be negative. </p></def></gitem><gitem><label>Notes</label><def><p role="note">The year returned is the same numeric value that appears in the lexical
            representation, which for negative years means the meaning may vary depending on whether
            XSD 1.0 or XSD 1.1 conventions are in use.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>fn:year-from-date(xs:date("1999-05-31"))</code> returns <code>1999</code>.</p><p>The expression <code>fn:year-from-date(xs:date("2000-01-01+05:00"))</code> returns <code>2000</code>.</p><p>The expression <code>fn:year-from-date(xs:date("-0002-06-01"))</code> returns <code>-2</code>. <emph>(The result is the same whether XSD 1.0 or 1.1 is in use, despite
               the absence of a year 0 in the XSD 1.0 value space.)</emph></p></def></gitem></glist></div3><div3 id="func-month-from-date"><head>fn:month-from-date</head><glist><gitem><label>Summary</label><def><p>Returns the month component of an <code>xs:date</code>.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="month-from-date" return-type="xs:integer?" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg" type="xs:date?"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>If <code>$arg</code> is the empty sequence, the function returns the empty sequence.</p><p>Otherwise, the function returns an <code>xs:integer</code> between 1 and 12, both
            inclusive, representing the month component in the local value of <code>$arg</code>.
         </p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>fn:month-from-date(xs:date("1999-05-31-05:00"))</code> returns <code>5</code>.</p><p>The expression <code>fn:month-from-date(xs:date("2000-01-01+05:00"))</code> returns <code>1</code>.</p></def></gitem></glist></div3><div3 id="func-day-from-date"><head>fn:day-from-date</head><glist><gitem><label>Summary</label><def><p>Returns the day component of an <code>xs:date</code>.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="day-from-date" return-type="xs:integer?" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg" type="xs:date?"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>If <code>$arg</code> is the empty sequence, the function returns the empty sequence.</p><p>Otherwise, the function returns an <code>xs:integer</code> between 1 and 31, both
            inclusive, representing the day component in the localized value of
            <code>$arg</code>.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>fn:day-from-date(xs:date("1999-05-31-05:00"))</code> returns <code>31</code>.</p><p>The expression <code>fn:day-from-date(xs:date("2000-01-01+05:00"))</code> returns <code>1</code>.</p></def></gitem></glist></div3><div3 id="func-timezone-from-date"><head>fn:timezone-from-date</head><glist><gitem><label>Summary</label><def><p>Returns the timezone component of an <code>xs:date</code>.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="timezone-from-date" return-type="xs:dayTimeDuration?" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg" type="xs:date?"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>If <code>$arg</code> is the empty sequence, the function returns the empty sequence.</p><p>Otherwise, the function returns the timezone component of <code>$arg</code>, if any. If
               <code>$arg</code> has a timezone component, then the result is an
               <code>xs:dayTimeDuration</code> that indicates deviation from UTC; its value may
            range from +14:00 to -14:00 hours, both inclusive. If <code>$arg</code> has no timezone
            component, the result is the empty sequence.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>fn:timezone-from-date(xs:date("1999-05-31-05:00"))</code> returns <code>xs:dayTimeDuration("-PT5H")</code>.</p><p>The expression <code>fn:timezone-from-date(xs:date("2000-06-12Z"))</code> returns <code>xs:dayTimeDuration("PT0S")</code>.</p></def></gitem></glist></div3><div3 id="func-hours-from-time"><head>fn:hours-from-time</head><glist><gitem><label>Summary</label><def><p>Returns the hours component of an <code>xs:time</code>.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="hours-from-time" return-type="xs:integer?" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg" type="xs:time?"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>If <code>$arg</code> is the empty sequence, the function returns the empty sequence.</p><p>Otherwise, the function returns an <code>xs:integer</code> between 0 and 23, both
            inclusive, representing the value of the hours component in the local value of
               <code>$arg</code>.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>Assume that the dynamic context provides an implicit timezone value of
                  <code>-05:00</code>. </p><p>The expression <code>fn:hours-from-time(xs:time("11:23:00"))</code> returns <code>11</code>.</p><p>The expression <code>fn:hours-from-time(xs:time("21:23:00"))</code> returns <code>21</code>.</p><p>The expression <code>fn:hours-from-time(xs:time("01:23:00+05:00"))</code> returns <code>1</code>.</p><p>The expression <code>fn:hours-from-time(fn:adjust-time-to-timezone(xs:time("01:23:00+05:00"),
                  xs:dayTimeDuration("PT0S")))</code> returns <code>20</code>.</p><p>The expression <code>fn:hours-from-time(xs:time("24:00:00"))</code> returns <code>0</code>.</p></def></gitem></glist></div3><div3 id="func-minutes-from-time"><head>fn:minutes-from-time</head><glist><gitem><label>Summary</label><def><p>Returns the minutes component of an <code>xs:time</code>.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="minutes-from-time" return-type="xs:integer?" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg" type="xs:time?"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>If <code>$arg</code> is the empty sequence, the function returns the empty sequence.</p><p>Otherwise, the function returns an <code>xs:integer</code> value between 0 and 59, both
            inclusive, representing the value of the minutes component in the local value of
               <code>$arg</code>.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>fn:minutes-from-time(xs:time("13:00:00Z"))</code> returns <code>0</code>.</p></def></gitem></glist></div3><div3 id="func-seconds-from-time"><head>fn:seconds-from-time</head><glist><gitem><label>Summary</label><def><p>Returns the seconds component of an <code>xs:time</code>.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="seconds-from-time" return-type="xs:decimal?" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg" type="xs:time?"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>If <code>$arg</code> is the empty sequence, the function returns the empty sequence.</p><p>Otherwise, the function returns an <code>xs:decimal</code> value greater than or equal
            to zero and less than 60, representing the seconds and fractional seconds in the local
            value of <code>$arg</code>.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>fn:seconds-from-time(xs:time("13:20:10.5"))</code> returns <code>10.5</code>.</p></def></gitem></glist></div3><div3 id="func-timezone-from-time"><head>fn:timezone-from-time</head><glist><gitem><label>Summary</label><def><p>Returns the timezone component of an <code>xs:time</code>.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="timezone-from-time" return-type="xs:dayTimeDuration?" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg" type="xs:time?"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>If <code>$arg</code> is the empty sequence, the function returns the empty sequence.</p><p>Otherwise, the function returns the timezone component of <code>$arg</code>, if any. If
               <code>$arg</code> has a timezone component, then the result is an
               <code>xs:dayTimeDuration</code> that indicates deviation from UTC; its value may
            range from +14:00 to -14:00 hours, both inclusive. If <code>$arg</code> has no timezone
            component, the result is the empty sequence.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>fn:timezone-from-time(xs:time("13:20:00-05:00"))</code> returns <code>xs:dayTimeDuration("-PT5H")</code>.</p><p>The expression <code>fn:timezone-from-time(xs:time("13:20:00"))</code> returns <code>()</code>.</p></def></gitem></glist></div3></div2><div2 id="timezone.functions"><head>Timezone adjustment functions on dates and time values</head><table class="index"><thead><tr><th rowspan="1" colspan="1">Function</th><th rowspan="1" colspan="1">Meaning</th></tr></thead><tbody><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:adjust-dateTime-to-timezone</code></td><td rowspan="1" colspan="1">Adjusts an <code>xs:dateTime</code> value to a specific timezone, or to no timezone at
            all.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:adjust-date-to-timezone</code></td><td rowspan="1" colspan="1">Adjusts an <code>xs:date</code> value to a specific timezone, or to no timezone at all;
            the result is the date in the target timezone that contains the starting instant of the
            supplied date.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:adjust-time-to-timezone</code></td><td rowspan="1" colspan="1">Adjusts an <code>xs:time</code> value to a specific timezone, or to no timezone at
            all.</td></tr></tbody></table><p>These functions adjust the timezone component of an <code>xs:dateTime</code>, <code>xs:date</code> or
                    <code>xs:time</code> value.  The <code>$timezone</code> argument to these functions is defined as an 
					<code>xs:dayTimeDuration</code> but must be a valid timezone value.</p><div3 id="func-adjust-dateTime-to-timezone"><head>fn:adjust-dateTime-to-timezone</head><glist><gitem><label>Summary</label><def><p>Adjusts an <code>xs:dateTime</code> value to a specific timezone, or to no timezone at
            all.</p></def></gitem><gitem><label>Signatures</label><def><example role="signature"><proto name="adjust-dateTime-to-timezone" return-type="xs:dateTime?" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg" type="xs:dateTime?"/></proto></example><example role="signature"><proto name="adjust-dateTime-to-timezone" return-type="xs:dateTime?" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg" type="xs:dateTime?"/><arg name="timezone" type="xs:dayTimeDuration?"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>The one-argument form of this function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-dependent">context-dependent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>.  It depends on 
		implicit timezone.
	</p><p>The two-argument form of this function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p> If <code>$timezone</code> is not specified, then the effective value of
               <code>$timezone</code> is the value of the implicit timezone in the dynamic
            context.</p><p> If <code>$arg</code> is the empty sequence, then the function returns the empty
            sequence.</p><p> If <code>$arg</code> does not have a timezone component and <code>$timezone</code> is
            the empty sequence, then the result is <code>$arg</code>.</p><p> If <code>$arg</code> does not have a timezone component and <code>$timezone</code> is
            not the empty sequence, then the result is <code>$arg</code> with <code>$timezone</code>
            as the timezone component.</p><p> If <code>$arg</code> has a timezone component and <code>$timezone</code> is the empty
            sequence, then the result is the local value of <code>$arg</code> without its timezone
            component.</p><p> If <code>$arg</code> has a timezone component and <code>$timezone</code> is not the
            empty sequence, then the result is the <code>xs:dateTime</code> value that is equal to
               <code>$arg</code> and that has a timezone component equal to
            <code>$timezone</code>.</p></def></gitem><gitem><label>Error Conditions</label><def><p> A dynamic error is raised <errorref class="DT" code="0003"/> if <code>$timezone</code>
            is less than <code>-PT14H</code> or greater than <code>PT14H</code> or is not an
            integral number of minutes.</p></def></gitem><gitem><label>Examples</label><def role="example"><p> Assume the dynamic context provides an implicit timezone of <code>-05:00
                  (-PT5H0M)</code>.</p><eg xml:space="preserve">let $tz-10 := xs:dayTimeDuration("-PT10H")</eg><p>The expression <code>fn:adjust-dateTime-to-timezone(xs:dateTime('2002-03-07T10:00:00'))</code> returns <code>xs:dateTime('2002-03-07T10:00:00-05:00')</code>.</p><p>The expression <code>fn:adjust-dateTime-to-timezone(xs:dateTime('2002-03-07T10:00:00-07:00'))</code> returns <code>xs:dateTime('2002-03-07T12:00:00-05:00')</code>.</p><p>The expression <code>fn:adjust-dateTime-to-timezone(xs:dateTime('2002-03-07T10:00:00'),
                  $tz-10)</code> returns <code>xs:dateTime('2002-03-07T10:00:00-10:00')</code>.</p><p>The expression <code>fn:adjust-dateTime-to-timezone(xs:dateTime('2002-03-07T10:00:00-07:00'),
                  $tz-10)</code> returns <code>xs:dateTime('2002-03-07T07:00:00-10:00')</code>.</p><p>The expression <code>fn:adjust-dateTime-to-timezone(xs:dateTime('2002-03-07T10:00:00-07:00'),
                  xs:dayTimeDuration("PT10H"))</code> returns <code>xs:dateTime('2002-03-08T03:00:00+10:00')</code>.</p><p>The expression <code>fn:adjust-dateTime-to-timezone(xs:dateTime('2002-03-07T00:00:00+01:00'),
                  xs:dayTimeDuration("-PT8H"))</code> returns <code>xs:dateTime('2002-03-06T15:00:00-08:00')</code>.</p><p>The expression <code>fn:adjust-dateTime-to-timezone(xs:dateTime('2002-03-07T10:00:00'),
                  ())</code> returns <code>xs:dateTime('2002-03-07T10:00:00')</code>.</p><p>The expression <code>fn:adjust-dateTime-to-timezone(xs:dateTime('2002-03-07T10:00:00-07:00'),
                  ())</code> returns <code>xs:dateTime('2002-03-07T10:00:00')</code>.</p></def></gitem></glist></div3><div3 id="func-adjust-date-to-timezone"><head>fn:adjust-date-to-timezone</head><glist><gitem><label>Summary</label><def><p>Adjusts an <code>xs:date</code> value to a specific timezone, or to no timezone at all;
            the result is the date in the target timezone that contains the starting instant of the
            supplied date.</p></def></gitem><gitem><label>Signatures</label><def><example role="signature"><proto name="adjust-date-to-timezone" return-type="xs:date?" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg" type="xs:date?"/></proto></example><example role="signature"><proto name="adjust-date-to-timezone" return-type="xs:date?" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg" type="xs:date?"/><arg name="timezone" type="xs:dayTimeDuration?"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>The one-argument form of this function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-dependent">context-dependent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>.  It depends on 
		implicit timezone.
	</p><p>The two-argument form of this function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p> If <code>$timezone</code> is not specified, then the effective value of
               <code>$timezone</code> is the value of the implicit timezone in the dynamic
            context.</p><p> If <code>$arg</code> is the empty sequence, then the function returns the empty
            sequence.</p><p> If <code>$arg</code> does not have a timezone component and <code>$timezone</code> is
            the empty sequence, then the result is the value of <code>$arg</code>.</p><p> If <code>$arg</code> does not have a timezone component and <code>$timezone</code> is
            not the empty sequence, then the result is <code>$arg</code> with <code>$timezone</code>
            as the timezone component.</p><p> If <code>$arg</code> has a timezone component and <code>$timezone</code> is the empty
            sequence, then the result is the local value of <code>$arg</code> without its timezone
            component.</p><p> If <code>$arg</code> has a timezone component and <code>$timezone</code> is not the
            empty sequence, then the function returns the value of the expression:</p><ulist><item><p>Let <code>$dt</code> be the value of <code>fn:dateTime($arg,
                     xs:time('00:00:00'))</code>.</p></item><item><p>Let <code>$adt</code> be the value of <code>fn:adjust-dateTime-to-timezone($dt,
                     $timezone)</code></p></item><item><p>The function returns the value of <code>xs:date($adt)</code></p></item></ulist></def></gitem><gitem><label>Error Conditions</label><def><p>A dynamic error is raised <errorref class="DT" code="0003"/> if <code>$timezone</code>
            is less than <code>-PT14H</code> or greater than <code>PT14H</code> or is not an
            integral number of minutes.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>Assume the dynamic context provides an implicit timezone of <code>-05:00
                  (-PT5H0M)</code>.</p><eg xml:space="preserve">let $tz-10 := xs:dayTimeDuration("-PT10H")</eg><p>The expression <code>fn:adjust-date-to-timezone(xs:date("2002-03-07"))</code> returns <code>xs:date("2002-03-07-05:00")</code>.</p><p>The expression <code>fn:adjust-date-to-timezone(xs:date("2002-03-07-07:00"))</code> returns <code>xs:date("2002-03-07-05:00")</code>. <emph>(<code>$arg</code> is converted to
                     <code>xs:dateTime("2002-03-07T00:00:00-07:00")</code>. This is adjusted to the
                  implicit timezone, giving <code>"2002-03-07T02:00:00-05:00"</code>.
               ).</emph></p><p>The expression <code>fn:adjust-date-to-timezone(xs:date("2002-03-07"),
                  $tz-10)</code> returns <code>xs:date("2002-03-07-10:00")</code>.</p><p>The expression <code>fn:adjust-date-to-timezone(xs:date("2002-03-07-07:00"),
                  $tz-10)</code> returns <code>xs:date("2002-03-06-10:00")</code>. <emph>(<code>$arg</code> is converted to the <code>xs:dateTime
                     "2002-03-07T00:00:00-07:00"</code>. This is adjusted to the given timezone,
                  giving <code>"2002-03-06T21:00:00-10:00"</code>. ).</emph></p><p>The expression <code>fn:adjust-date-to-timezone(xs:date("2002-03-07"),
                  ())</code> returns <code>xs:date("2002-03-07")</code>.</p><p>The expression <code>fn:adjust-date-to-timezone(xs:date("2002-03-07-07:00"),
                  ())</code> returns <code>xs:date("2002-03-07")</code>.</p></def></gitem></glist></div3><div3 id="func-adjust-time-to-timezone"><head>fn:adjust-time-to-timezone</head><glist><gitem><label>Summary</label><def><p>Adjusts an <code>xs:time</code> value to a specific timezone, or to no timezone at
            all.</p></def></gitem><gitem><label>Signatures</label><def><example role="signature"><proto name="adjust-time-to-timezone" return-type="xs:time?" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg" type="xs:time?"/></proto></example><example role="signature"><proto name="adjust-time-to-timezone" return-type="xs:time?" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg" type="xs:time?"/><arg name="timezone" type="xs:dayTimeDuration?"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>The one-argument form of this function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-dependent">context-dependent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>.  It depends on 
		implicit timezone.
	</p><p>The two-argument form of this function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p> If <code>$timezone</code> is not specified, then the effective value of
               <code>$timezone</code> is the value of the implicit timezone in the dynamic
            context.</p><p> If <code>$arg</code> is the empty sequence, then the function returns the empty
            sequence.</p><p> If <code>$arg</code> does not have a timezone component and <code>$timezone</code> is
            the empty sequence, then the result is <code>$arg</code>.</p><p> If <code>$arg</code> does not have a timezone component and <code>$timezone</code> is
            not the empty sequence, then the result is <code>$arg</code> with <code>$timezone</code>
            as the timezone component.</p><p> If <code>$arg</code> has a timezone component and <code>$timezone</code> is the empty
            sequence, then the result is the localized value of <code>$arg</code> without its
            timezone component.</p><p> If <code>$arg</code> has a timezone component and <code>$timezone</code> is not the
            empty sequence, then:</p><ulist><item><p>Let <code>$dt</code> be the <code>xs:dateTime</code> value
                     <code>fn:dateTime(xs:date('1972-12-31'), $arg)</code>.</p></item><item><p>Let <code>$adt</code> be the value of <code>fn:adjust-dateTime-to-timezone($dt,
                     $timezone)</code>
               </p></item><item><p>The function returns the <code>xs:time</code> value
                  <code>xs:time($adt)</code>.</p></item></ulist></def></gitem><gitem><label>Error Conditions</label><def><p>A dynamic error is raised <errorref class="DT" code="0003"/> if <code>$timezone</code>
            is less than <code>-PT14H</code> or greater than <code>PT14H</code> or if does not
            contain an integral number of minutes.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>Assume the dynamic context provides an implicit timezone of <code>-05:00
                  (-PT5H0M)</code>.</p><eg xml:space="preserve">let $tz-10 := xs:dayTimeDuration("-PT10H")</eg><p>The expression <code>fn:adjust-time-to-timezone(xs:time("10:00:00"))</code> returns <code>xs:time("10:00:00-05:00")</code>.</p><p>The expression <code>fn:adjust-time-to-timezone(xs:time("10:00:00-07:00"))</code> returns <code>xs:time("12:00:00-05:00")</code>.</p><p>The expression <code>fn:adjust-time-to-timezone(xs:time("10:00:00"),
                  $tz-10)</code> returns <code>xs:time("10:00:00-10:00")</code>.</p><p>The expression <code>fn:adjust-time-to-timezone(xs:time("10:00:00-07:00"),
                  $tz-10)</code> returns <code>xs:time("07:00:00-10:00")</code>.</p><p>The expression <code>fn:adjust-time-to-timezone(xs:time("10:00:00"), ())</code> returns <code>xs:time("10:00:00")</code>.</p><p>The expression <code>fn:adjust-time-to-timezone(xs:time("10:00:00-07:00"),
                  ())</code> returns <code>xs:time("10:00:00")</code>.</p><p>The expression <code>fn:adjust-time-to-timezone(xs:time("10:00:00-07:00"),
                  xs:dayTimeDuration("PT10H"))</code> returns <code>xs:time("03:00:00+10:00")</code>.</p></def></gitem></glist></div3></div2><div2 id="dateTime-arithmetic"><head>Arithmetic operators on durations, dates and times</head><p>These functions support adding or subtracting a duration value to or from an
                    <code>xs:dateTime</code>, an <code>xs:date</code> or an <code>xs:time</code>
                    value. Appendix E of <bibref ref="xmlschema-2"/> describes an algorithm for
                    performing such operations.</p><table class="index"><thead><tr><th rowspan="1" colspan="1">Function</th><th rowspan="1" colspan="1">Meaning</th></tr></thead><tbody><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">op:subtract-dateTimes</code></td><td rowspan="1" colspan="1">Returns an <code>xs:dayTimeDuration</code> representing the amount of elapsed time
            between the instants <code>arg2</code> and <code>arg1</code>.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">op:subtract-dates</code></td><td rowspan="1" colspan="1">Returns the <code>xs:dayTimeDuration</code> that corresponds to the elapsed time between
            the starting instant of <code>$arg2</code> and the starting instant of
               <code>$arg2</code>.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">op:subtract-times</code></td><td rowspan="1" colspan="1">Returns the <code>xs:dayTimeDuration</code> that corresponds to the elapsed time between
            the values of <code>$arg2</code> and <code>$arg1</code> treated as times on the same
            date.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">op:add-yearMonthDuration-to-dateTime</code></td><td rowspan="1" colspan="1">Returns the <code>xs:dateTime</code> that is a given duration after a specified
               <code>xs:dateTime</code> (or before, if the duration is negative).</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">op:add-dayTimeDuration-to-dateTime</code></td><td rowspan="1" colspan="1">Returns the <code>xs:dateTime</code> that is a given duration after a specified
               <code>xs:dateTime</code> (or before, if the duration is negative).</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">op:subtract-yearMonthDuration-from-dateTime</code></td><td rowspan="1" colspan="1">Returns the <code>xs:dateTime</code> that is a given duration before a specified
               <code>xs:dateTime</code> (or after, if the duration is negative).</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">op:subtract-dayTimeDuration-from-dateTime</code></td><td rowspan="1" colspan="1">Returns the <code>xs:dateTime</code> that is a given duration before a specified
               <code>xs:dateTime</code> (or after, if the duration is negative).</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">op:add-yearMonthDuration-to-date</code></td><td rowspan="1" colspan="1">Returns the <code>xs:date</code> that is a given duration after a specified
               <code>xs:date</code> (or before, if the duration is negative).</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">op:add-dayTimeDuration-to-date</code></td><td rowspan="1" colspan="1">Returns the <code>xs:date</code> that is a given duration after a specified
               <code>xs:date</code> (or before, if the duration is negative).</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">op:subtract-yearMonthDuration-from-date</code></td><td rowspan="1" colspan="1">Returns the <code>xs:date</code> that is a given duration before a specified
               <code>xs:date</code> (or after, if the duration is negative).</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">op:subtract-dayTimeDuration-from-date</code></td><td rowspan="1" colspan="1">Returns the <code>xs:date</code> that is a given duration before a specified
               <code>xs:date</code> (or after, if the duration is negative).</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">op:add-dayTimeDuration-to-time</code></td><td rowspan="1" colspan="1">Returns the <code>xs:time</code> value that is a given duration after a specified
               <code>xs:time</code> (or before, if the duration is negative or causes wrap-around
            past midnight)</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">op:subtract-dayTimeDuration-from-time</code></td><td rowspan="1" colspan="1">Returns the <code>xs:time</code> value that is a given duration before a specified
               <code>xs:time</code> (or after, if the duration is negative or causes wrap-around
            past midnight)</td></tr></tbody></table><div3 id="duration-limits"><head>Limits and precision</head><p>A processor that limits the number of digits in date and time datatype
                  representations may encounter overflow and underflow conditions when it
                  tries to execute the functions in this section. In
                  these situations, the processor <rfc2119>must</rfc2119> return P0M or PT0S in
                  case of duration underflow and 00:00:00 in case of time underflow.
                  It <rfc2119>must</rfc2119> raise a dynamic error
                  <errorref class="DT" code="0001"/> in case of overflow.</p><p>The value spaces of the two totally ordered subtypes of
                  <code>xs:duration</code> described in <specref ref="duration-subtypes"/> are
                  <code>xs:integer</code> months for <code>xs:yearMonthDuration</code>
                  and <code>xs:decimal</code> seconds for <code>xs:dayTimeDuration</code>. If
                  a processor limits the number of digits allowed in the representation of
                  <code>xs:integer</code> and <code>xs:decimal</code> then overflow and
                  underflow situations can arise when it tries to execute the functions in
                  <specref ref="duration-arithmetic"/>. In these situations the processor
                  <rfc2119>must</rfc2119> return zero in case of numeric underflow and P0M
                  or PT0S in case of duration underflow. It <rfc2119>must</rfc2119> raise a
                  dynamic error <errorref class="DT" code="0002"/> in case of overflow.</p></div3><div3 id="func-subtract-dateTimes"><head>op:subtract-dateTimes</head><glist><gitem><label>Summary</label><def><p>Returns an <code>xs:dayTimeDuration</code> representing the amount of elapsed time
            between the instants <code>arg2</code> and <code>arg1</code>.</p></def></gitem><gitem><label>Operator Mapping</label><def><p>Defines the semantics of the "-"
         operator when applied to two <code>xs:dateTime</code> values.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="subtract-dateTimes" return-type="xs:dayTimeDuration" isOp="yes" prefix="op" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg1" type="xs:dateTime"/><arg name="arg2" type="xs:dateTime"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-dependent">context-dependent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>.  It depends on 
		implicit timezone.
	</p></def></gitem><gitem><label>Rules</label><def><p>If either <code>$arg1</code> or <code>$arg2</code> do not contain an explicit timezone
            then, for the purpose of the operation, the implicit timezone provided by the dynamic
            context (See <xspecref spec="XP31" ref="id-xp-evaluation-context-components"/>.) is
            assumed to be present as part of the value.</p><p>The function returns the elapsed time between the date/time instant <code>arg2</code>
            and the date/time instant <code>arg1</code>, computed according to the algorithm given
            in Appendix E of <bibref ref="xmlschema-2"/>, and expressed as a
               <code>xs:dayTimeDuration</code>.</p><p>If the normalized value of <code>$arg1</code> precedes in time the normalized value of
               <code>$arg2</code>, then the returned value is a negative duration.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>Assume that the dynamic context provides an implicit timezone value of
                  <code>-05:00</code>.</p><p>The expression <code>op:subtract-dateTimes(xs:dateTime("2000-10-30T06:12:00"),
                  xs:dateTime("1999-11-28T09:00:00Z"))</code> returns <code>xs:dayTimeDuration("P337DT2H12M")</code>.</p></def></gitem></glist></div3><div3 id="func-subtract-dates"><head>op:subtract-dates</head><glist><gitem><label>Summary</label><def><p>Returns the <code>xs:dayTimeDuration</code> that corresponds to the elapsed time between
            the starting instant of <code>$arg2</code> and the starting instant of
               <code>$arg2</code>.</p></def></gitem><gitem><label>Operator Mapping</label><def><p>Defines the semantics of the "-" operator
         when applied to two <code>xs:date</code> values.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="subtract-dates" return-type="xs:dayTimeDuration" isOp="yes" prefix="op" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg1" type="xs:date"/><arg name="arg2" type="xs:date"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-dependent">context-dependent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>.  It depends on 
		implicit timezone.
	</p></def></gitem><gitem><label>Rules</label><def><p>If either <code>$arg1</code> or <code>$arg2</code> do not contain an explicit timezone
            then, for the purpose of the operation, the implicit timezone provided by the dynamic
            context (See <xspecref spec="XP31" ref="id-xp-evaluation-context-components"/>.) is
            assumed to be present as part of the value.</p><p>The starting instant of an <code>xs:date</code> is the <code>xs:dateTime</code> at
               <code>00:00:00</code> on that date. </p><p>The function returns the result of subtracting the two starting instants using
               <code>op:subtract-dateTimes</code>.</p><p>If the starting instant of <code>$arg1</code> precedes in time the starting instant of
               <code>$arg2</code>, then the returned value is a negative duration.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>Assume that the dynamic context provides an implicit timezone value of
               <code>Z</code>. </p><p>The expression <code>op:subtract-dates(xs:date("2000-10-30"),
                  xs:date("1999-11-28"))</code> returns <code>xs:dayTimeDuration("P337D")</code>. <emph>(The normalized values of the two starting instants are <code>{2000,
                     10, 30, 0, 0, 0, PT0S}</code> and <code>{1999, 11, 28, 0, 0, 0,
                  PT0S}</code>.)</emph></p><p>Now assume that the dynamic context provides an implicit timezone value of
                  <code>+05:00</code>.</p><p>The expression <code>op:subtract-dates(xs:date("2000-10-30"),
                  xs:date("1999-11-28Z"))</code> returns <code>xs:dayTimeDuration("P336DT19H")</code>. <emph>( The normalized values of the two starting instants are <code>{2000,
                     10, 29, 19, 0, 0, PT0S}</code> and <code>{1999, 11, 28, 0, 0, 0,
                  PT0S}</code>.)</emph></p><p>The expression <code>op:subtract-dates(xs:date("2000-10-15-05:00"),
                  xs:date("2000-10-10+02:00"))</code> returns <code>xs:dayTimeDuration("P5DT7H")</code>.</p></def></gitem></glist></div3><div3 id="func-subtract-times"><head>op:subtract-times</head><glist><gitem><label>Summary</label><def><p>Returns the <code>xs:dayTimeDuration</code> that corresponds to the elapsed time between
            the values of <code>$arg2</code> and <code>$arg1</code> treated as times on the same
            date.</p></def></gitem><gitem><label>Operator Mapping</label><def><p>Defines the semantics of the "-" operator
         when applied to two <code>xs:time</code> values.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="subtract-times" return-type="xs:dayTimeDuration" isOp="yes" prefix="op" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg1" type="xs:time"/><arg name="arg2" type="xs:time"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-dependent">context-dependent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>.  It depends on 
		implicit timezone.
	</p></def></gitem><gitem><label>Rules</label><def><p>The function returns the result of the expression:</p><eg xml:space="preserve">op-subtract-dateTimes(
        fn:dateTime(xs:date('1972-12-31'), $arg1),
        fn:dateTime(xs:date('1972-12-31'), $arg2))</eg></def></gitem><gitem><label>Notes</label><def><p role="note">Any other reference date would work equally well.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>Assume that the dynamic context provides an implicit timezone value of
                  <code>-05:00</code>. Assume, also, that the date components of the reference
                  <code>xs:dateTime</code> correspond to <code>"1972-12-31"</code>.</p><p>The expression <code>op:subtract-times(xs:time("11:12:00Z"),
                  xs:time("04:00:00"))</code> returns <code>xs:dayTimeDuration("PT2H12M")</code>. <emph>(This is obtained by subtracting from the <code>xs:dateTime</code>
                  value <code>{1972, 12, 31, 11, 12, 0, PT0S}</code> the <code>xs:dateTime</code>
                  value <code>{1972, 12, 31, 9, 0, 0, PT0S}</code>.)</emph></p><p>The expression <code>op:subtract-times(xs:time("11:00:00-05:00"),
                  xs:time("21:30:00+05:30"))</code> returns <code>xs:dayTimeDuration("PT0S")</code>. <emph>(The two <code>xs:dateTime</code> values are <code>{1972, 12, 31, 11,
                     0, 0, -PT5H}</code> and <code>{1972, 12, 31, 21, 30, 0, PT5H30M}</code>. These
                  normalize to <code>{1972, 12, 31, 16, 0, 0, PT0S}</code> and <code>{1972, 12, 31,
                     16, 0, 0, PT0S}</code>. ).</emph></p><p>The expression <code>op:subtract-times(xs:time("17:00:00-06:00"),
                  xs:time("08:00:00+09:00"))</code> returns <code>xs:dayTimeDuration("P1D")</code>. <emph>(The two normalized <code>xs:dateTime</code> values are <code>{1972,
                     12, 31, 23, 0, 0, PT0S}</code> and <code>{1972, 12, 30, 23, 0, 0,
                  PT0S}</code>.)</emph></p><p>The expression <code>op:subtract-times(xs:time("24:00:00"),
                  xs:time("23:59:59"))</code> returns <code>xs:dayTimeDuration("-PT23H59M59S")</code>. <emph>(The two normalized <code>xs:dateTime</code> values are <code>{1972,
                     12, 31, 0, 0, 0, ()}</code> and <code>{1972, 12, 31, 23, 59, 59.0,
                  ()}</code>.)</emph></p></def></gitem></glist></div3><div3 id="func-add-yearMonthDuration-to-dateTime"><head>op:add-yearMonthDuration-to-dateTime</head><glist><gitem><label>Summary</label><def><p>Returns the <code>xs:dateTime</code> that is a given duration after a specified
               <code>xs:dateTime</code> (or before, if the duration is negative).</p></def></gitem><gitem><label>Operator Mapping</label><def><p>Defines the
         semantics of the "+" operator when applied to an <code>xs:dateTime</code> and an
            <code>xs:yearMonthDuration</code> value. </p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="add-yearMonthDuration-to-dateTime" return-type="xs:dateTime" isOp="yes" prefix="op" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg1" type="xs:dateTime"/><arg name="arg2" type="xs:yearMonthDuration"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>The function returns the result of adding <code>$arg2</code> to the value of
               <code>$arg1</code> using the algorithm described in Appendix E of <bibref ref="xmlschema-2"/>, disregarding the rule about leap seconds. If <code>$arg2</code>
            is negative, then the result <code>xs:dateTime</code> precedes <code>$arg1</code>.</p><p>The result has the same timezone as <code>$arg1</code>. If <code>$arg1</code> has no
            timezone, the result has no timezone. </p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>op:add-yearMonthDuration-to-dateTime(xs:dateTime("2000-10-30T11:12:00"),
                  xs:yearMonthDuration("P1Y2M"))</code> returns <code>xs:dateTime("2001-12-30T11:12:00")</code>.</p></def></gitem></glist></div3><div3 id="func-add-dayTimeDuration-to-dateTime"><head>op:add-dayTimeDuration-to-dateTime</head><glist><gitem><label>Summary</label><def><p>Returns the <code>xs:dateTime</code> that is a given duration after a specified
               <code>xs:dateTime</code> (or before, if the duration is negative).</p></def></gitem><gitem><label>Operator Mapping</label><def><p>Defines the semantics
         of the "+" operator when applied to an <code>xs:dateTime</code> and an
            <code>xs:dayTimeDuration</code> value. </p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="add-dayTimeDuration-to-dateTime" return-type="xs:dateTime" isOp="yes" prefix="op" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg1" type="xs:dateTime"/><arg name="arg2" type="xs:dayTimeDuration"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>The function returns the result of adding <code>$arg2</code> to the value of
               <code>$arg1</code> using the algorithm described in Appendix E of <bibref ref="xmlschema-2"/>, disregarding the rule about leap seconds. If <code>$arg2</code>
            is negative, then the result <code>xs:dateTime</code> precedes <code>$arg1</code>.</p><p>The result has the same timezone as <code>$arg1</code>. If <code>$arg1</code> has no
            timezone, the result has no timezone. </p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>op:add-dayTimeDuration-to-dateTime(xs:dateTime("2000-10-30T11:12:00"),
                  xs:dayTimeDuration("P3DT1H15M"))</code> returns <code>xs:dateTime("2000-11-02T12:27:00")</code>.</p></def></gitem></glist></div3><div3 id="func-subtract-yearMonthDuration-from-dateTime"><head>op:subtract-yearMonthDuration-from-dateTime</head><glist><gitem><label>Summary</label><def><p>Returns the <code>xs:dateTime</code> that is a given duration before a specified
               <code>xs:dateTime</code> (or after, if the duration is negative).</p></def></gitem><gitem><label>Operator Mapping</label><def><p>Defines the
         semantics of the "-" operator when applied to an <code>xs:dateTime</code> and an
            <code>xs:yearMonthDuration</code> value. </p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="subtract-yearMonthDuration-from-dateTime" return-type="xs:dateTime" isOp="yes" prefix="op" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg1" type="xs:dateTime"/><arg name="arg2" type="xs:yearMonthDuration"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>The function returns the <code>xs:dateTime</code> computed by negating
               <code>$arg2</code> and adding the result to the value of <code>$arg1</code> using the
            function <code>op:add-yearMonthDuration-to-dateTime</code>.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>op:subtract-yearMonthDuration-from-dateTime(xs:dateTime("2000-10-30T11:12:00"),
                  xs:yearMonthDuration("P1Y2M"))</code> returns <code>xs:dateTime("1999-08-30T11:12:00")</code>.</p></def></gitem></glist></div3><div3 id="func-subtract-dayTimeDuration-from-dateTime"><head>op:subtract-dayTimeDuration-from-dateTime</head><glist><gitem><label>Summary</label><def><p>Returns the <code>xs:dateTime</code> that is a given duration before a specified
               <code>xs:dateTime</code> (or after, if the duration is negative).</p></def></gitem><gitem><label>Operator Mapping</label><def><p>Defines the semantics
         of the "-" operator when applied to an <code>xs:dateTime</code> an and
            <code>xs:dayTimeDuration</code> values</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="subtract-dayTimeDuration-from-dateTime" return-type="xs:dateTime" isOp="yes" prefix="op" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg1" type="xs:dateTime"/><arg name="arg2" type="xs:dayTimeDuration"/></proto></example></def></gitem><gitem><label>Rules</label><def><p>The function returns the <code>xs:dateTime</code> computed by negating
               <code>$arg2</code> and adding the result to the value of <code>$arg1</code> using the
            function <code>op:add-dayTimeDuration-to-dateTime</code>.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>op:subtract-dayTimeDuration-from-dateTime(xs:dateTime("2000-10-30T11:12:00"),
                  xs:dayTimeDuration("P3DT1H15M"))</code> returns <code>xs:dateTime("2000-10-27T09:57:00")</code>.</p></def></gitem></glist></div3><div3 id="func-add-yearMonthDuration-to-date"><head>op:add-yearMonthDuration-to-date</head><glist><gitem><label>Summary</label><def><p>Returns the <code>xs:date</code> that is a given duration after a specified
               <code>xs:date</code> (or before, if the duration is negative).</p></def></gitem><gitem><label>Operator Mapping</label><def><p>Defines the semantics
         of the "+" operator when applied to an <code>xs:date</code> and an
            <code>xs:yearMonthDuration</code> value. </p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="add-yearMonthDuration-to-date" return-type="xs:date" isOp="yes" prefix="op" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg1" type="xs:date"/><arg name="arg2" type="xs:yearMonthDuration"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>The function returns the result of casting <code>$arg1</code> to an
               <code>xs:dateTime</code>, adding <code>$arg2</code> using the function
               <code>op:add-yearMonthDuration-to-dateTime</code>, and casting the result back to an
               <code>xs:date</code>.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>op:add-yearMonthDuration-to-date(xs:date("2000-10-30"),
                  xs:yearMonthDuration("P1Y2M"))</code> returns <code>xs:date("2001-12-30")</code>.</p></def></gitem></glist></div3><div3 id="func-add-dayTimeDuration-to-date"><head>op:add-dayTimeDuration-to-date</head><glist><gitem><label>Summary</label><def><p>Returns the <code>xs:date</code> that is a given duration after a specified
               <code>xs:date</code> (or before, if the duration is negative).</p></def></gitem><gitem><label>Operator Mapping</label><def><p>Defines the semantics of
         the "+" operator when applied to an <code>xs:date</code> and an
            <code>xs:dayTimeDuration</code> value. </p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="add-dayTimeDuration-to-date" return-type="xs:date" isOp="yes" prefix="op" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg1" type="xs:date"/><arg name="arg2" type="xs:dayTimeDuration"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>The function returns the result of casting <code>$arg1</code> to an
               <code>xs:dateTime</code>, adding <code>$arg2</code> using the function
               <code>op:add-dayTimeDuration-to-dateTime</code>, and casting the result back to an
               <code>xs:date</code>.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>op:add-dayTimeDuration-to-date(xs:date("2004-10-30Z"),
                  xs:dayTimeDuration("P2DT2H30M0S"))</code> returns <code>xs:date("2004-11-01Z")</code>. <emph>( The starting instant of the first argument is the
                     <code>xs:dateTime</code> value <code>{2004, 10, 30, 0, 0, 0, PT0S}</code>.
                  Adding the second argument to this gives the <code>xs:dateTime</code> value
                     <code>{2004, 11, 1, 2, 30, 0, PT0S}</code>. The time components are then
                  discarded. ).</emph></p></def></gitem></glist></div3><div3 id="func-subtract-yearMonthDuration-from-date"><head>op:subtract-yearMonthDuration-from-date</head><glist><gitem><label>Summary</label><def><p>Returns the <code>xs:date</code> that is a given duration before a specified
               <code>xs:date</code> (or after, if the duration is negative).</p></def></gitem><gitem><label>Operator Mapping</label><def><p>Defines the semantics
         of the "-" operator when applied to an <code>xs:date</code> and an
            <code>xs:yearMonthDuration</code> value. </p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="subtract-yearMonthDuration-from-date" return-type="xs:date" isOp="yes" prefix="op" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg1" type="xs:date"/><arg name="arg2" type="xs:yearMonthDuration"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>Returns the <code>xs:date</code> computed by negating <code>$arg2</code> and adding the
            result to <code>$arg1</code> using the function
               <code>op:add-yearMonthDuration-to-date</code>.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>op:subtract-yearMonthDuration-from-date(xs:date("2000-10-30"),
                  xs:yearMonthDuration("P1Y2M"))</code> returns <code>xs:date("1999-08-30")</code>.</p><p>The expression <code>op:subtract-yearMonthDuration-from-date(xs:date("2000-02-29Z"),
                  xs:yearMonthDuration("P1Y"))</code> returns <code>xs:date("1999-02-28Z")</code>.</p><p>The expression <code>op:subtract-yearMonthDuration-from-date(xs:date("2000-10-31-05:00"),
                  xs:yearMonthDuration("P1Y1M"))</code> returns <code>xs:date("1999-09-30-05:00")</code>.</p></def></gitem></glist></div3><div3 id="func-subtract-dayTimeDuration-from-date"><head>op:subtract-dayTimeDuration-from-date</head><glist><gitem><label>Summary</label><def><p>Returns the <code>xs:date</code> that is a given duration before a specified
               <code>xs:date</code> (or after, if the duration is negative).</p></def></gitem><gitem><label>Operator Mapping</label><def><p>Defines the semantics of
         the "-" operator when applied to an <code>xs:date</code> and an
            <code>xs:dayTimeDuration</code>. </p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="subtract-dayTimeDuration-from-date" return-type="xs:date" isOp="yes" prefix="op" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg1" type="xs:date"/><arg name="arg2" type="xs:dayTimeDuration"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>Returns the <code>xs:date</code> computed by negating <code>$arg2</code> and adding the
            result to <code>$arg1</code> using the function
               <code>op:add-dayTimeDuration-to-date</code>.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>op:subtract-dayTimeDuration-from-date(xs:date("2000-10-30"),
                  xs:dayTimeDuration("P3DT1H15M"))</code> returns <code>xs:date("2000-10-26")</code>.</p></def></gitem></glist></div3><div3 id="func-add-dayTimeDuration-to-time"><head>op:add-dayTimeDuration-to-time</head><glist><gitem><label>Summary</label><def><p>Returns the <code>xs:time</code> value that is a given duration after a specified
               <code>xs:time</code> (or before, if the duration is negative or causes wrap-around
            past midnight)</p></def></gitem><gitem><label>Operator Mapping</label><def><p>Defines the semantics of
         the "+" operator when applied to an <code>xs:time</code> and an
            <code>xs:dayTimeDuration</code> value.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="add-dayTimeDuration-to-time" return-type="xs:time" isOp="yes" prefix="op" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg1" type="xs:time"/><arg name="arg2" type="xs:dayTimeDuration"/></proto></example></def></gitem><gitem><label>Rules</label><def><p>First, the days component in the canonical lexical representation of <code>$arg2</code>
            is set to zero (0) and the value of the resulting <code>xs:dayTimeDuration</code> is
            calculated. Alternatively, the value of <code>$arg2</code> modulus 86,400 is used as the
            second argument. This value is added to the value of <code>$arg1</code> converted to an
               <code>xs:dateTime</code> using a reference date such as <code>1972-12-31</code>, and
            the time component of the result is returned. Note that the <code>xs:time</code>
            returned may occur in a following or preceding day and may be less than
               <code>$arg1</code>.</p><p>The result has the same timezone as <code>$arg1</code>. If <code>$arg1</code> has no
            timezone, the result has no timezone.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>op:add-dayTimeDuration-to-time(xs:time("11:12:00"),
                  xs:dayTimeDuration("P3DT1H15M"))</code> returns <code>xs:time("12:27:00")</code>.</p><p>The expression <code>op:add-dayTimeDuration-to-time(xs:time("23:12:00+03:00"),
                  xs:dayTimeDuration("P1DT3H15M"))</code> returns <code>xs:time("02:27:00+03:00")</code>. <emph>(That is, <code>{0, 0, 0, 2, 27, 0, PT3H}</code>).</emph></p></def></gitem></glist></div3><div3 id="func-subtract-dayTimeDuration-from-time"><head>op:subtract-dayTimeDuration-from-time</head><glist><gitem><label>Summary</label><def><p>Returns the <code>xs:time</code> value that is a given duration before a specified
               <code>xs:time</code> (or after, if the duration is negative or causes wrap-around
            past midnight)</p></def></gitem><gitem><label>Operator Mapping</label><def><p>Defines the semantics of
         the "-" operator when applied to an <code>xs:time</code> and an
            <code>xs:dayTimeDuration</code> value. </p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="subtract-dayTimeDuration-from-time" return-type="xs:time" isOp="yes" prefix="op" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg1" type="xs:time"/><arg name="arg2" type="xs:dayTimeDuration"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>The function returns the result of negating <code>$arg2</code> and adding the result to
               <code>$arg1</code> using the function <code>op:add-dayTimeDuration-to-time</code>.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>op:subtract-dayTimeDuration-from-time(xs:time("11:12:00"),
                  xs:dayTimeDuration("P3DT1H15M"))</code> returns <code>xs:time("09:57:00")</code>.</p><p>The expression <code>op:subtract-dayTimeDuration-from-time(xs:time("08:20:00-05:00"),
                  xs:dayTimeDuration("P23DT10H10M"))</code> returns <code>xs:time("22:10:00-05:00")</code>.</p></def></gitem></glist></div3></div2><div2 id="formatting-dates-and-times"><head>Formatting dates and times</head><table class="index"><thead><tr><th rowspan="1" colspan="1">Function</th><th rowspan="1" colspan="1">Meaning</th></tr></thead><tbody><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:format-dateTime</code></td><td rowspan="1" colspan="1">Returns a string containing an <code>xs:dateTime</code> value formatted for display.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:format-date</code></td><td rowspan="1" colspan="1">Returns a string containing an <code>xs:date</code> value formatted for display.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:format-time</code></td><td rowspan="1" colspan="1">Returns a string containing an <code>xs:time</code> value formatted for display.</td></tr></tbody></table><p>Three functions are provided to represent dates and times as a string, using the conventions of a selected calendar,
 language, and country. The signatures are presented first, followed by the rules which apply to each of the functions.</p><div3 id="func-format-dateTime"><head>fn:format-dateTime</head><glist><gitem><label>Summary</label><def><p>Returns a string containing an <code>xs:dateTime</code> value formatted for display.</p></def></gitem><gitem><label>Signatures</label><def><example role="signature"><proto name="format-dateTime" return-type="xs:string?" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="value" type="xs:dateTime?"/><arg name="picture" type="xs:string"/></proto></example><example role="signature"><proto name="format-dateTime" return-type="xs:string?" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="value" type="xs:dateTime?"/><arg name="picture" type="xs:string"/><arg name="language" type="xs:string?"/><arg name="calendar" type="xs:string?"/><arg name="place" type="xs:string?"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>The two-argument form of this function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-dependent">context-dependent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>.  It depends on 
		default calendar, and default language, and default place, and implicit timezone.
	</p><p>The five-argument form of this function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-dependent">context-dependent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>.  It depends on 
		implicit timezone, and namespaces.
	</p></def></gitem><gitem><label>Rules</label><def><p>See <specref ref="rules-for-datetime-formatting"/>.</p></def></gitem></glist></div3><div3 id="func-format-date"><head>fn:format-date</head><glist><gitem><label>Summary</label><def><p>Returns a string containing an <code>xs:date</code> value formatted for display.</p></def></gitem><gitem><label>Signatures</label><def><example role="signature"><proto name="format-date" return-type="xs:string?" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="value" type="xs:date?"/><arg name="picture" type="xs:string"/></proto></example><example role="signature"><proto name="format-date" return-type="xs:string?" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="value" type="xs:date?"/><arg name="picture" type="xs:string"/><arg name="language" type="xs:string?"/><arg name="calendar" type="xs:string?"/><arg name="place" type="xs:string?"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>The two-argument form of this function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-dependent">context-dependent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>.  It depends on 
		default calendar, and default language, and default place, and implicit timezone.
	</p><p>The five-argument form of this function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-dependent">context-dependent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>.  It depends on 
		implicit timezone, and namespaces.
	</p></def></gitem><gitem><label>Rules</label><def><p>See <specref ref="rules-for-datetime-formatting"/>.</p></def></gitem></glist></div3><div3 id="func-format-time"><head>fn:format-time</head><glist><gitem><label>Summary</label><def><p>Returns a string containing an <code>xs:time</code> value formatted for display.</p></def></gitem><gitem><label>Signatures</label><def><example role="signature"><proto name="format-time" return-type="xs:string?" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="value" type="xs:time?"/><arg name="picture" type="xs:string"/></proto></example><example role="signature"><proto name="format-time" return-type="xs:string?" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="value" type="xs:time?"/><arg name="picture" type="xs:string"/><arg name="language" type="xs:string?"/><arg name="calendar" type="xs:string?"/><arg name="place" type="xs:string?"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>The two-argument form of this function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-dependent">context-dependent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>.  It depends on 
		default calendar, and default language, and default place, and implicit timezone.
	</p><p>The five-argument form of this function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-dependent">context-dependent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>.  It depends on 
		implicit timezone, and namespaces.
	</p></def></gitem><gitem><label>Rules</label><def><p>See <specref ref="rules-for-datetime-formatting"/>.</p></def></gitem></glist></div3><div3 id="rules-for-datetime-formatting"><head>The date/time formatting functions</head><p>The <code>fn:format-dateTime</code>, <code>fn:format-date</code>, 
and <code>fn:format-time</code> 
functions format <code>$value</code> as a string using 
the picture string specified by the <code>$picture</code> argument,
the calendar specified by the <code>$calendar</code> argument,
the language specified by the <code>$language</code> argument, 
and the country or other place name specified by the <code>$place</code> argument.
The result of the function is the formatted string representation of the supplied
  <code>xs:dateTime</code>, <code>xs:date</code>, or <code>xs:time</code> value.</p><p>
               <termdef id="dt-date-formatting-function" term="date formatting function">The three 
                  functions <code>fn:format-dateTime</code>, <code>fn:format-date</code>, 
                  and <code>fn:format-time</code> are referred to collectively as the
                   <term>date formatting functions</term>.</termdef>
            </p><p>If <code>$value</code> is the empty sequence, the function returns the empty sequence.</p><p>Calling the two-argument form of each of the three functions is equivalent
to calling the five-argument form with each of the last three arguments set to an empty sequence.</p><p>For details of the <code>$language</code>, <code>$calendar</code>, and
<code>$place</code> arguments, see <specref ref="lang-cal-place"/>.</p><p>In general, the use of an invalid <code>$picture</code>, 
<code>$language</code>, <code>$calendar</code>, or
               <code>$place</code> argument results in a dynamic error <errorref class="FD" code="1340"/>. By contrast,
use of an option in any of these arguments that is valid but not supported by the implementation is
not an error, and in these cases the implementation is required to output the value in a fallback
representation. More detailed rules are given below.</p><div4 id="date-picture-string"><head>The picture string</head><p>The picture consists of a sequence of variable markers and literal substrings.
A substring enclosed in square brackets is interpreted as a variable marker; substrings
not enclosed in square brackets are taken as literal substrings. 
The literal substrings are optional and if present are rendered unchanged, including any whitespace. 
If an opening or closing square bracket 
is required within a literal substring, it <rfc2119>must</rfc2119> be doubled.
The variable markers are replaced in the result by strings representing 
aspects of the date and/or time to be formatted. These are described in detail below.</p><p>A variable marker consists of a component specifier followed optionally 
by one or two presentation modifiers and/or optionally by a width modifier.
Whitespace within a variable marker is ignored.</p><p>The variable marker may be separated into its components
               by applying the following rules:</p><olist><item><p>The component specifier is always present and is always a
                  single letter.</p></item><item><p>The width modifier may be recognized by the presence of a comma.</p></item><item><p>The substring between the component specifier and the comma (if present)
                     or the end of the string (if there is no comma) contains the first and
                     second presentation modifiers, both of which are optional. If this substring
                  contains a single character, this is interpreted as the first presentation modifier.
                  If it contains more than one character, the last character is examined: if it is valid
                  as a second presentation modifier then it is treated as such, and the preceding part
                  of the substring constitutes the first presentation modifier. Otherwise, the second
                  presentation modifier is presumed absent and the whole substring is interpreted as the
                  first presentation modifier.</p></item></olist><p>The <emph>component specifier</emph> indicates the component of the date or
time that is required, and takes the following values:</p><table role="data"><thead><tr><th align="left" rowspan="1" colspan="1">Specifier</th><th align="left" rowspan="1" colspan="1">Meaning</th><th align="left" rowspan="1" colspan="1">Default Presentation Modifier</th></tr></thead><tbody><tr><td rowspan="1" colspan="1">Y</td><td rowspan="1" colspan="1">year (absolute value)</td><td rowspan="1" colspan="1">1</td></tr><tr><td rowspan="1" colspan="1">M</td><td rowspan="1" colspan="1">month in year</td><td rowspan="1" colspan="1">1</td></tr><tr><td rowspan="1" colspan="1">D</td><td rowspan="1" colspan="1">day in month</td><td rowspan="1" colspan="1">1</td></tr><tr><td rowspan="1" colspan="1">d</td><td rowspan="1" colspan="1">day in year</td><td rowspan="1" colspan="1">1</td></tr><tr><td rowspan="1" colspan="1">F</td><td rowspan="1" colspan="1">day of week</td><td rowspan="1" colspan="1">n</td></tr><tr><td rowspan="1" colspan="1">W</td><td rowspan="1" colspan="1">week in year</td><td rowspan="1" colspan="1">1</td></tr><tr><td rowspan="1" colspan="1">w</td><td rowspan="1" colspan="1">week in month</td><td rowspan="1" colspan="1">1</td></tr><tr><td rowspan="1" colspan="1">H</td><td rowspan="1" colspan="1">hour in day (24 hours)</td><td rowspan="1" colspan="1">1</td></tr><tr><td rowspan="1" colspan="1">h</td><td rowspan="1" colspan="1">hour in half-day (12 hours)</td><td rowspan="1" colspan="1">1</td></tr><tr><td rowspan="1" colspan="1">P</td><td rowspan="1" colspan="1">am/pm marker</td><td rowspan="1" colspan="1">n</td></tr><tr><td rowspan="1" colspan="1">m</td><td rowspan="1" colspan="1">minute in hour</td><td rowspan="1" colspan="1">01</td></tr><tr><td rowspan="1" colspan="1">s</td><td rowspan="1" colspan="1">second in minute</td><td rowspan="1" colspan="1">01</td></tr><tr><td rowspan="1" colspan="1">f</td><td rowspan="1" colspan="1">fractional seconds</td><td rowspan="1" colspan="1">1</td></tr><tr><td rowspan="1" colspan="1">Z</td><td rowspan="1" colspan="1">timezone</td><td rowspan="1" colspan="1">01:01</td></tr><tr><td rowspan="1" colspan="1">z</td><td rowspan="1" colspan="1">timezone (same as Z, but modified where appropriate to include a prefix
                           as a time offset using GMT, for example GMT+1 or GMT-05:00. For this component there is a fixed
prefix of <code>GMT</code>, or a localized
variation thereof for the chosen language, and the remainder of the value is formatted as for specifier <code>Z</code>.
                        </td><td rowspan="1" colspan="1">01:01</td></tr><tr><td rowspan="1" colspan="1">C</td><td rowspan="1" colspan="1">calendar: the name or abbreviation of a calendar name</td><td rowspan="1" colspan="1">n</td></tr><tr><td rowspan="1" colspan="1">E</td><td rowspan="1" colspan="1">era: the name of a baseline for the numbering of years, for example
                  the reign of a monarch</td><td rowspan="1" colspan="1">n</td></tr></tbody></table><p>A dynamic error is reported <errorref class="FD" code="1340"/>
 if the syntax of the picture is incorrect.</p><p>A dynamic error is reported <errorref class="FD" code="1350"/>
 if a component specifier within the picture 
 refers to components that are not available in the given type of <code>$value</code>,
 for example if the picture supplied to the <code>fn:format-time</code> refers
 to the year, month, or day component.</p><p>It is not an error to include a timezone component when the supplied
 value has no timezone. In these circumstances the timezone component will be ignored.</p><p>The first <emph>presentation modifier</emph> indicates the style in which the
value of a component is to be represented. Its value may be
either:</p><ulist><item><p>any format token permitted as a primary format token in the second argument 
of the <code>fn:format-integer</code> function, indicating
that the value of the component is to be output numerically using the specified number format (for example,
<code>1</code>, <code>01</code>, <code>i</code>, <code>I</code>, <code>w</code>, <code>W</code>,
or <code>Ww</code>) or </p></item><item><p>the format token <code>n</code>, <code>N</code>,
or <code>Nn</code>, indicating that the value of the component is to be output by name,
in lower-case, upper-case, or title-case respectively. Components that can be output by name
include (but are not limited to) months, days of the week, timezones, and eras. 
If the processor cannot output these components by name for the chosen calendar and language 
then it must use an <termref def="implementation-defined"/> fallback representation.</p></item></ulist><p>If a comma is to be used as a grouping separator within the format token, then there must be a width
			   specifier. More specifically: if a variable marker
			   contains one or more commas, then the last comma is treated as introducing the width modifier, and all others
			   are treated as grouping separators. So <code>[Y9,999,*]</code> will output the year as <code>2,008</code>.</p><p>It is not possible to use a closing square bracket as a grouping separator within the format token.</p><p>If the implementation does not support the use of the requested format token, it <rfc2119>must</rfc2119>
use the default presentation modifier for that component.</p><p>If the first presentation modifier is present, then it may optionally be followed by
a second presentation modifier as follows:</p><table role="longlastcol"><thead><tr><th align="left" rowspan="1" colspan="1">Modifier</th><th align="left" rowspan="1" colspan="1">Meaning</th></tr></thead><tbody><tr><td rowspan="1" colspan="1">either <code>a</code> or <code>t</code></td><td rowspan="1" colspan="1">indicates alphabetic or traditional numbering respectively,
                           the default being <termref def="implementation-defined"/>. 
                           This has the same meaning as in the second argument of <code>fn:format-integer</code>.</td></tr><tr><td rowspan="1" colspan="1">either <code>c</code> or <code>o</code></td><td rowspan="1" colspan="1">indicates cardinal or ordinal numbering respectively, for example
                           <code>7</code> or <code>seven</code> for a cardinal number, or <code>7th</code>,
                           <code>seventh</code>, or <code>7º</code>
                           for an ordinal number.
						This has the same meaning as
in the second argument of <code>fn:format-integer</code>. 
The actual representation of the ordinal form of a number
may depend not only on the language, but also on the grammatical context (for example,
in some languages it must agree in gender).</td></tr></tbody></table><note><p>Although the formatting rules are expressed in terms of the rules
for format tokens in <code>fn:format-integer</code>, the formats actually used may be specialized
to the numbering of date components where appropriate. For example, in Italian, it is conventional to
use an ordinal number (<code>primo</code>) for the first day of the month, and cardinal numbers
(<code>due, tre, quattro ...</code>) for the remaining days. A processor may therefore use
this convention to number days of the month, ignoring the presence or absence of the ordinal
presentation modifier.</p></note></div4><div4 id="width-modifier"><head>The Width Modifier</head><p>Whether or not a presentation modifier is included, a width modifier may be supplied. This
indicates the number of characters to be included in the representation of the value.</p><p>The width modifier, if present, is introduced by a comma<phrase diff="del" at="D"> or semicolon</phrase>. It takes the form:</p><p>
                  <code>   ","  min-width ("-" max-width)?</code>
               </p><p>where <code>min-width</code> is either an unsigned integer indicating the minimum number of characters to
be output, or <code>*</code> indicating that there is no explicit minimum, and 
<code>max-width</code> is either an unsigned integer indicating the maximum number of characters to
be output, or <code>*</code> indicating that there is no explicit maximum; if <code>max-width</code>
is omitted then <code>*</code> is assumed.</p><p diff="add" at="E">A dynamic error (<errorref class="FD" code="1340"/>) is raised if 
      <code>min-width</code> is present and less than one, or if
      <code>max-width</code> is present and less than one or less than <code>min-width</code>. 
   </p><p>A format token containing more than one digit, such as <code>001</code> or <code>9999</code>, sets the
minimum and maximum width to the number of digits appearing in the format token; if a width
modifier is also present, then the width modifier takes precedence.</p></div4><div4 diff="add" at="E" id="formatting-integer-valued-components"><head>Formatting Integer-Valued Date/Time Components</head><p>The rules in this section apply to the majority of integer-valued components: specifically <code>M D d F W w H h m s</code>.</p><p>In the rules below, the term <term>decimal digit pattern</term> has the meaning given in <specref ref="func-format-integer"/>.</p><olist><item><p>If the first presentation modifier takes the form of a <term>decimal digit pattern</term>:</p><olist><item><p>If there is no width modifier, then the value is formatted according to 
		                      the rules of the <code>format-integer</code> function.</p></item><item><p>If there is a width modifier, then the first presentation modifier 
		                      is adjusted as follows:</p><olist><item><p>If the decimal digit pattern includes a grouping separator, the output is 
		                         implementation-defined (but this is not an error).
		                      </p><note><p>Use of a width modifier together with grouping separators is inadvisable 
		                            for this reason. It is never necessary to use a width modifier with a decimal 
		                            digit pattern, since the same effect can be achieved by use of optional digit signs.</p></note></item><item><p>Otherwise, the number of mandatory-digit-sign characters in the presentation 
		                         modifier is increased if necessary. This is done first by replacing optional-digit-signs 
		                         with mandatory-digit-signs, starting from the right, and then prepending mandatory-digit-signs 
		                         to the presentation modifier, until the number of mandatory-digit-signs is equal to the 
		                         minimum width. Any mandatory-digit-signs that are added by this process must use the 
		                         same decimal digit family as existing mandatory-digit-signs in the presentation modifier 
		                         if there are any, or ASCII digits otherwise.
		                      </p></item><item><p>The maximum width, if specified, is ignored.
		                      </p></item><item><p>The output is then as defined using the <code>format-integer</code> function with this adjusted decimal digit pattern.
		                      </p></item></olist></item></olist></item><item><p>If the first presentation modifiers is one of <code>N</code>, <code>n</code>, or <code>Nn</code>:</p><olist><item><p>Let <var>FN</var> be the full name of the component, that is, the form of the name 
		                     that would be used in the absence of any width modifier.</p></item><item><p>If <var>FN</var> is shorter than the minimum width, then it is padded by appending spaces to the end of the name.
		                  </p></item><item><p>If <var>FN</var> is longer than the maximum width, then it is abbreviated, either 
		                     by choosing a conventional abbreviation that fits within the maximum width (for example, 
		                     "Wednesday" might be abbreviated to "Weds"), or by removing characters from the end 
		                     of <var>FN</var> until it fits within the maximum width.
		                  </p></item></olist></item><item><p>For other presentation modifiers:</p><olist><item><p>Any adjustment of the value to fit within the requested width range is implementation-defined. </p></item><item><p>The value should not be truncated if this results in output that will not be meaningful to users (for example, 
		                     there is no sensible way to truncate Roman numerals).</p></item><item><p>If shorter than the minimum width, the value should be padded to the minimum width, either by appending spaces, 
		                     or in some other way appropriate to the numbering scheme.</p></item></olist></item></olist></div4><div4 diff="add" at="E" id="formatting-year-component"><head>Formatting the Year Component</head><p>The rules for the year component (Y) are the same as those in <specref ref="formatting-integer-valued-components"/>, 
		            except that the value of the year as output is the value of the year component of the supplied value modulo ten to the power 
		            <var>N</var> where <var>N</var> is determined as follows: 
		         </p><olist><item><p>If the width modifier is present and <phrase diff="chg" at="E">defines a finite maximum width</phrase>, then that maximum width.
		            </p></item><item><p>Otherwise, if the first presentation modifier takes the form of a decimal-digit-pattern, 
		               then:</p><olist><item><p>Let <var>W</var> be the number of optional-digit-signs and mandatory-digit-signs in that decimal-digit-pattern.</p></item><item><p>If <var>W</var> is 2 or more, then <var>W</var>.</p></item></olist></item><item><p>Otherwise, <var>N</var> is infinity (that is, the year is output in full).</p></item></olist></div4><div4 diff="add" at="E" id="formatting-fractional-seconds"><head>Formatting Fractional Seconds</head><p>The output for the fractional seconds component (<code>f</code>) is equivalent to the result of the following algorithm: </p><olist><item><p>If the first presentation modifier contains no Unicode digit, then the output is implementation-defined.
		            </p></item><item><p>Otherwise, the value of the fractional seconds is output as follows:</p><olist><item><p>If there is no width modifier and the first presentation modifier comprises in its
		                  entirety a single mandatory-digit-sign (for example the default <code>1</code>), then
		                  the presentation modifier is extended on the right with as many optional-digit-signs as
		                  are needed to accommodate the actual fractional seconds precision encountered in the
		                  value to be formatted.
		               </p></item><item><p>If there is a width modifier, then the first presentation modifier 
		                  is adjusted as follows:</p><olist><item><p><phrase diff="chg" at="E">If a minimum width is specified, and if this exceeds the number of mandatory-digit-sign characters 
		                        in the first presentation modifier, then the first presentation modifier is adjusted.</phrase> 
		                        This is done first by replacing optional-digit-signs 
		                        with mandatory-digit-signs, starting from the left, and then appending mandatory-digit-signs 
		                        to the presentation modifier, until the number of mandatory-digit-signs is equal to the 
		                        minimum width. Any mandatory-digit-signs that are added by this process must use the 
		                        same decimal digit family as existing mandatory-digit-signs in the presentation modifier.
		                     </p></item><item><p>If a maximum width is specified, the first presentation modifier is extended on the right
		                        with as many optional-digit-signs as are needed to ensure that the number of mandatory-digit-signs
		                        and optional-digit-signs is at least equal to the maximum width.
		                     </p></item></olist></item><item><p>The sequence of characters in the (adjusted) first presentation modifier is reversed (for example, 
		                  <code>999'###</code> becomes <code>###'999</code>). 
		                  If the result is not a valid <term>decimal digit pattern</term>, then the output is 
		                  <termref def="implementation-defined">implementation-defined</termref>.
		               </p></item><item><p>The sequence of digits in the conventional decimal representation of the fractional seconds component 
		                  is reversed, with insignificant zeroes removed, and the result is treated as an integer. For example, if the 
		                  seconds value is <code>25.8235</code>, the reversed fractional seconds value is <code>5328</code>.
		               </p></item><item><p>The reversed fractional seconds value is formatted using the reversed decimal digit pattern according to the 
		                  rules of the <code>fn:format-integer</code> function. Given the examples above, the result is <code>5'328</code>
		               </p></item><item><p>The resulting string is reversed. In our example, the result is <code>823'5</code>.</p></item><item><p>If the result contains more digits than the number of mandatory-digit-signs and optional-digit-signs in the 
		                  decimal digit pattern, then excess digits 
		                  are removed from the right hand end (that is, the value is truncated towards zero rather than being rounded). 
		                  Any grouping separator that immediately precedes a removed digit 
		                  is also removed.</p></item></olist></item></olist><note><p>The reason for presenting the algorithm in this way is that it enables maximum re-use of the rules defined for
		            <code>fn:format-integer</code>. Since the fractional seconds value is not properly an integer, the rules do not
		            work if used directly: for example, the positions of grouping separators need to be counted from the left rather
		            than from the right. Implementations, as always, are free to use a different algorithm that yields the same result.</p></note><note><p>A format token consisting of a single digit,
		            such as <code>1</code>, does not constrain the number of digits in the output. 
		            In the case of fractional seconds in particular, <code>[f001]</code> requests three decimal digits,
		            <code>[f01]</code> requests two digits, but <code>[f1]</code> will retain all digits in the
		            supplied date/time value (the maximum number of digits is implementation-defined). 
		            If exactly one digit is required, this can be achieved using the component specifier 
		            <code>[f1,1-1]</code>.</p></note></div4><div4 id="formatting-timezones"><head>Formatting timezones</head><p>Special rules apply to the formatting of timezones. When the component specifiers <code>Z</code>
		      or <code>z</code> are used, the rules in this section override any rules given elsewhere in the case of
		      discrepancies.</p><p>If the date/time value to be formatted does not include a timezone offset, then the timezone component
		      specifier is generally ignored (results in no output). The exception is where military timezones are used
		      (format ZZ) in which case the string "J" is output, indicating local time.</p><ulist><item><p>When the component specifier is <code>z</code>, the output is the same as for component specifier
		      <code>Z</code>, except that it is prefixed by the characters <code>GMT</code> or some localized
		      equivalent. The prefix is omitted, however, in cases where the timezone is identified by name rather than by
		      a numeric offset from UTC.</p></item><item><p>If the first <var>presentation modifier</var> is numeric and comprises one or two digits 
		         with no <var>grouping-separator</var> (for example <code>1</code>
		      or <code>01</code>), then the timezone is formatted as a displacement from UTC in hours, preceded by a plus or minus
		      sign: for example <code>-5</code> or <code>+03</code>. If the actual timezone offset is not an integral number of hours,
		      then the minutes part of the offset is appended, separated by a colon: for example <code>+10:30</code> or 
		         <code>-1:15</code>.</p></item><item><p>If the first <var>presentation modifier</var> is numeric with a <var>grouping-separator</var> (for example <code>1:01</code>
		         or <code>01.01</code>), then the timezone offset is output in hours and minutes, separated by the grouping separator,
		      even if the number of minutes is zero: for example <code>+5:00</code> or <code>+10.30</code>.</p></item><item><p>If the first <var>presentation modifier</var> is numeric and comprises three or four digits with no
		      <var>grouping-separator</var>, for example <code>001</code> or <code>0001</code>, then the timezone offset
		      is shown in hours and minutes with no separator, for example <code>-0500</code> or <code>+1030</code>.
		      </p></item><item><p>If the first <var>presentation modifier</var> is numeric, in any of the above formats, and the second
		      <var>presentation modifier</var> is <code>t</code>, then a zero timezone offset (that is, UTC) is output as <code>Z</code> instead
		      of a signed numeric value. In this presentation modifier is absent or if the timezone offset is non-zero, 
		      then the displayed timezone offset is preceded by a "-" sign for negative offsets
		      or a "+" sign for non-negative offsets.</p></item><item><p>If the first <var>presentation modifier</var> is <code>Z</code>, then the timezone is formatted
		         as a military timezone letter, using the convention Z = +00:00, A = +01:00, B = +02:00, ..., M = +12:00, 
		         N = -01:00, O = -02:00, ... Y = -12:00. The letter J (meaning local time) is used in the case of a 
		         value that does not specify a timezone offset. Timezone offsets that have no representation in this system
		         (for example Indian Standard Time, +05:30) are output as if the format <code>01:01</code> had been requested.</p></item><item><p>If the first <var>presentation modifier</var> is <code>N</code>, then the timezone is output
		      (where possible) as a timezone name, for example <code>EST</code> or <code>CET</code>. The same timezone
		      offset has different names in different places; it is therefore <rfc2119>recommended</rfc2119> that this option
		      should be used only if a country code (see <bibref ref="ISO3166"/>) or <phrase diff="chg" at="E">IANA</phrase> timezone name (see <bibref ref="olson"/>) is supplied in the <code>$place</code> argument.
		      In the absence of this information, the implementation may apply a default, for example by using the timezone
		      names that are conventional in North America. If no timezone name can be identified, the timezone offset is
		      output using the fallback format <code>+01:01</code>.</p></item></ulist><p>The following examples illustrate options for timezone formatting.</p><table role="small complex data"><thead><tr><th rowspan="1" colspan="1">Variable marker</th><th rowspan="1" colspan="1"><code>$place</code></th><th colspan="5" rowspan="1">Timezone offsets (with time = 12:00:00)</th></tr><tr><th rowspan="1" colspan="1"> </th><th rowspan="1" colspan="1"> </th><th rowspan="1" colspan="1">-10:00</th><th rowspan="1" colspan="1">-05:00</th><th rowspan="1" colspan="1">+00:00</th><th rowspan="1" colspan="1">+05:30</th><th rowspan="1" colspan="1">+13:00</th></tr></thead><tbody><tr><td rowspan="1" colspan="1">[Z]</td><td rowspan="1" colspan="1">()</td><td rowspan="1" colspan="1">-10:00</td><td rowspan="1" colspan="1">-05:00</td><td rowspan="1" colspan="1">+00:00</td><td rowspan="1" colspan="1">+05:30</td><td rowspan="1" colspan="1">+13:00</td></tr><tr><td rowspan="1" colspan="1">[Z0]</td><td rowspan="1" colspan="1">()</td><td rowspan="1" colspan="1">-10</td><td rowspan="1" colspan="1">-5</td><td rowspan="1" colspan="1">+0</td><td rowspan="1" colspan="1">+5:30</td><td rowspan="1" colspan="1">+13</td></tr><tr><td rowspan="1" colspan="1">[Z0:00]</td><td rowspan="1" colspan="1">()</td><td rowspan="1" colspan="1">-10:00</td><td rowspan="1" colspan="1">-5:00</td><td rowspan="1" colspan="1">+0:00</td><td rowspan="1" colspan="1">+5:30</td><td rowspan="1" colspan="1">+13:00</td></tr><tr><td rowspan="1" colspan="1">[Z00:00]</td><td rowspan="1" colspan="1">()</td><td rowspan="1" colspan="1">-10:00</td><td rowspan="1" colspan="1">-05:00</td><td rowspan="1" colspan="1">+00:00</td><td rowspan="1" colspan="1">+05:30</td><td rowspan="1" colspan="1">+13:00</td></tr><tr><td rowspan="1" colspan="1">[Z0000]</td><td rowspan="1" colspan="1">()</td><td rowspan="1" colspan="1">-1000</td><td rowspan="1" colspan="1">-0500</td><td rowspan="1" colspan="1">+0000</td><td rowspan="1" colspan="1">+0530</td><td rowspan="1" colspan="1">+1300</td></tr><tr><td rowspan="1" colspan="1">[Z00:00t]</td><td rowspan="1" colspan="1">()</td><td rowspan="1" colspan="1">-10:00</td><td rowspan="1" colspan="1">-05:00</td><td rowspan="1" colspan="1">Z</td><td rowspan="1" colspan="1">+05:30</td><td rowspan="1" colspan="1">+13:00</td></tr><tr><td rowspan="1" colspan="1">[z]</td><td rowspan="1" colspan="1">()</td><td rowspan="1" colspan="1">GMT‑10:00</td><td rowspan="1" colspan="1">GMT‑05:00</td><td rowspan="1" colspan="1">GMT+00:00</td><td rowspan="1" colspan="1">GMT+05:30</td><td rowspan="1" colspan="1">GMT+13:00</td></tr><tr><td rowspan="1" colspan="1">[ZZ]</td><td rowspan="1" colspan="1">()</td><td rowspan="1" colspan="1">W</td><td rowspan="1" colspan="1">R</td><td rowspan="1" colspan="1">Z</td><td rowspan="1" colspan="1">+05:30</td><td rowspan="1" colspan="1">+13:00</td></tr><tr><td rowspan="1" colspan="1">[ZN]</td><td rowspan="1" colspan="1">"us"</td><td rowspan="1" colspan="1">HST</td><td rowspan="1" colspan="1">EST</td><td rowspan="1" colspan="1">GMT</td><td rowspan="1" colspan="1">IST</td><td rowspan="1" colspan="1">+13:00</td></tr><tr><td rowspan="1" colspan="1">[H00]:[M00] [ZN]</td><td rowspan="1" colspan="1">"America/New_York"</td><td rowspan="1" colspan="1">06:00 EST</td><td rowspan="1" colspan="1">12:00 EST</td><td rowspan="1" colspan="1">07:00 EST</td><td rowspan="1" colspan="1">01:30 EST</td><td rowspan="1" colspan="1">18:00 EST</td></tr></tbody></table><p diff="add" at="E">If a width specifier is present when formatting a timezone, then the representation as defined in this section is padded to the minimum
		      width as described in <specref ref="width-modifier"/>, but it is never shortened.</p></div4><div4 id="formatting-other-components"><head>Formatting Other Components</head><p>This section applies to the remaining components: <code>P</code> (am/pm marker), <code>C</code> (calendar),
		      and <code>E</code> (era).</p><p>The output for these components is entirely <termref def="implementation-defined">implementation-defined</termref>.
		      The default presentation modifier for these components is <code>n</code>, indicating that they are output as names (or
		      conventional abbreviations), and the chosen names will in many cases depend on the chosen language: see <specref ref="lang-cal-place"/>.</p></div4><div4 id="lang-cal-place"><head>The language, calendar, and place arguments</head><p>The set of languages, calendars, and places that are supported in the 
<termref def="dt-date-formatting-function">date formatting functions</termref> is
<termref def="implementation-defined">implementation-defined</termref>. When
any of these arguments is omitted or is an empty sequence, an <termref def="implementation-defined">implementation-defined</termref>
default value is used.</p><imp-def-feature>The set of languages, calendars, and places that are supported in the 
<termref def="dt-date-formatting-function">date formatting functions</termref> is
implementation-defined. If any of these arguments is omitted or set to an empty sequence, 
the default is implementation-defined.</imp-def-feature><p>If the fallback representation uses a different calendar from that requested,
the output string <rfc2119>must</rfc2119> identify the calendar actually used, for example by
prefixing the string with <code>[Calendar: X]</code> (where X is the calendar actually used),
localized as appropriate to the
requested language. If the fallback representation uses a different language
from that requested, the output string <rfc2119>must</rfc2119> identify the language actually
used, for example by prefixing the string with <code>[Language: Y]</code> (where Y is the language
actually used) localized in an
implementation-dependent way. If a particular component of the value cannot be output in
the requested format, it <rfc2119>should</rfc2119> be output in the default format for
that component.</p><p>The <code>$language</code> argument specifies the language to be used for the result string 
of the function. The value of the argument <rfc2119>should</rfc2119> be either the empty sequence
or a value that would be valid for the <code>xml:lang</code> attribute (see [XML]).
Note that this permits the identification of sublanguages
based on country codes (from <bibref ref="ISO3166"/>) as well as identification of dialects
and of regions within a country.</p><p>If the <code>$language</code> 
argument is omitted or is set to an empty sequence, or if it is set to an invalid value or a
value that the implementation does not recognize, 
then the processor uses the default language defined in the dynamic context.</p><p>The language is used to select the appropriate language-dependent forms of:</p><ulist><item><p>names (for example, of months)</p></item><item><p>numbers expressed as words or as ordinals (<code>twenty, 20th, twentieth</code>)</p></item><item><p>hour convention (0-23 vs 1-24, 0-11 vs 1-12)</p></item><item><p>first day of week, first week of year</p></item></ulist><p>Where appropriate this choice may also take into account the value of the
<code>$place</code> argument, though this <rfc2119>should</rfc2119> not be used to override the
language or any sublanguage that is specified as part of the <code>language</code>
argument.</p><p>The choice of the names and abbreviations used in any given language is 
<termref def="implementation-defined">implementation-defined</termref>. For example,
one implementation might abbreviate July as <code>Jul</code> while another uses <code>Jly</code>. In German,
one implementation might represent Saturday as <code>Samstag</code> while another
uses <code>Sonnabend</code>. Implementations <rfc2119>may</rfc2119> provide mechanisms allowing users to
control such choices.</p><imp-def-feature>The choice of the names and abbreviations used in any given language for
calendar units such as days of the week and months of the year is 
<termref def="implementation-defined">implementation-defined</termref>.</imp-def-feature><p>Where ordinal numbers are used, the selection of the correct representation of the 
ordinal (for example, the linguistic gender) <rfc2119>may</rfc2119> depend on the component being formatted and on its
textual context in the picture string.</p><p>The <code>calendar</code> attribute specifies that the <code>dateTime</code>, <code>date</code>,
or <code>time</code> supplied in the <code>$value</code> argument <rfc2119>must</rfc2119> be 
converted to a value in the specified calendar and then converted to a string using the 
conventions of that calendar.</p><p>The calendar value if present <rfc2119>must</rfc2119> be a valid <code>EQName</code> 
                  (dynamic error: <errorref class="FD" code="1340"/>).
                  If it is a lexical <code>QName</code> then it is expanded into an expanded QName 
                     using the statically known namespaces; if it has no prefix then it represents an expanded-QName in no namespace.
                  If the expanded QName is in no namespace, 
                  then it <rfc2119>must</rfc2119> identify a calendar with a designator specified below 
                  (dynamic error: <errorref class="FD" code="1340"/>). 
If the expanded QName is in a namespace then it identifies the calendar in an <termref def="implementation-defined">implementation-defined</termref> way.</p><p>If the <code>$calendar</code> argument is omitted or is set to an empty sequence
                  then the default calendar defined in the dynamic context is used.</p><note><p>The calendars listed below were known to be in use during the 
last hundred years. Many other calendars have been used in the past.</p><p>This specification does not define any of these calendars, nor the way that they
map to the value space of the <code>xs:date</code> datatype in <bibref ref="xmlschema-2"/>.
There may be ambiguities when dates are recorded using different calendars. 
For example, the start of a new day is not simultaneous in different calendars, 
and may also vary geographically (for example, based on the time of sunrise or sunset).
Translation of dates is therefore more reliable when the time of day is also known, and
when the geographic location is known. 
When translating dates between
one calendar and another, the processor may take account of the values
of the <code>$place</code> and/or <code>$language</code> arguments, with the 
                     <code>$place</code>
argument taking precedence.</p><p>Information about some of these calendars, and algorithms for converting between them, may
be found in <bibref ref="CALCALC"/>.</p></note><table role="data"><thead><tr><th rowspan="1" colspan="1">Designator</th><th rowspan="1" colspan="1">Calendar</th></tr></thead><tbody><tr><td rowspan="1" colspan="1">AD</td><td rowspan="1" colspan="1">Anno Domini (Christian Era)</td></tr><tr><td rowspan="1" colspan="1">AH</td><td rowspan="1" colspan="1">Anno Hegirae (Muhammedan Era)</td></tr><tr><td rowspan="1" colspan="1">AME</td><td rowspan="1" colspan="1">Mauludi Era (solar years since Mohammed's birth)</td></tr><tr><td rowspan="1" colspan="1">AM</td><td rowspan="1" colspan="1">Anno Mundi (Jewish Calendar)</td></tr><tr><td rowspan="1" colspan="1">AP</td><td rowspan="1" colspan="1">Anno Persici</td></tr><tr><td rowspan="1" colspan="1">AS</td><td rowspan="1" colspan="1">Aji Saka Era (Java)</td></tr><tr><td rowspan="1" colspan="1">BE</td><td rowspan="1" colspan="1">Buddhist Era</td></tr><tr><td rowspan="1" colspan="1">CB</td><td rowspan="1" colspan="1">Cooch Behar Era</td></tr><tr><td rowspan="1" colspan="1">CE</td><td rowspan="1" colspan="1">Common Era</td></tr><tr><td rowspan="1" colspan="1">CL</td><td rowspan="1" colspan="1">Chinese Lunar Era</td></tr><tr><td rowspan="1" colspan="1">CS</td><td rowspan="1" colspan="1">Chula Sakarat Era</td></tr><tr><td rowspan="1" colspan="1">EE</td><td rowspan="1" colspan="1">Ethiopian Era</td></tr><tr><td rowspan="1" colspan="1">FE</td><td rowspan="1" colspan="1">Fasli Era</td></tr><tr><td rowspan="1" colspan="1">ISO</td><td rowspan="1" colspan="1">ISO 8601 calendar</td></tr><tr><td rowspan="1" colspan="1">JE</td><td rowspan="1" colspan="1">Japanese Calendar</td></tr><tr><td rowspan="1" colspan="1">KE</td><td rowspan="1" colspan="1">Khalsa Era (Sikh calendar)</td></tr><tr><td rowspan="1" colspan="1">KY</td><td rowspan="1" colspan="1">Kali Yuga</td></tr><tr><td rowspan="1" colspan="1">ME</td><td rowspan="1" colspan="1">Malabar Era</td></tr><tr><td rowspan="1" colspan="1">MS</td><td rowspan="1" colspan="1">Monarchic Solar Era</td></tr><tr><td rowspan="1" colspan="1">NS</td><td rowspan="1" colspan="1">Nepal Samwat Era</td></tr><tr><td rowspan="1" colspan="1">OS</td><td rowspan="1" colspan="1">Old Style (Julian Calendar)</td></tr><tr><td rowspan="1" colspan="1">RS</td><td rowspan="1" colspan="1">Rattanakosin (Bangkok) Era</td></tr><tr><td rowspan="1" colspan="1">SE</td><td rowspan="1" colspan="1">Saka Era</td></tr><tr><td rowspan="1" colspan="1">SH</td><td rowspan="1" colspan="1">Mohammedan Solar Era (Iran)</td></tr><tr><td rowspan="1" colspan="1">SS</td><td rowspan="1" colspan="1">Saka Samvat</td></tr><tr><td rowspan="1" colspan="1">TE</td><td rowspan="1" colspan="1">Tripurabda Era</td></tr><tr><td rowspan="1" colspan="1">VE</td><td rowspan="1" colspan="1">Vikrama Era</td></tr><tr><td rowspan="1" colspan="1">VS</td><td rowspan="1" colspan="1">Vikrama Samvat Era</td></tr></tbody></table><p>At least one of the above calendars <rfc2119>must</rfc2119> be supported. It is 
<termref def="implementation-defined">implementation-defined</termref> which
calendars are supported.</p><p>The ISO 8601 calendar (<bibref ref="ISO8601"/>), 
which is included in the above list and designated <code>ISO</code>, 
is very similar to the Gregorian calendar designated <code>AD</code>, but it
differs in several ways. The ISO calendar
    is intended to ensure that date and time formats can be read
    easily by other software, as well as being legible for human
    users. The ISO calendar
prescribes the use of particular numbering conventions as defined in
ISO 8601, rather than allowing these to be localized on a per-language basis. 
In particular it
    provides a numeric 'week date' format which identifies dates by
    year, week of the year, and day in the week; 
in the ISO calendar the days of the week are numbered from 1 (Monday) to 7 (Sunday), and
week 1 in any calendar year is the week (from Monday to Sunday) that includes the first Thursday
of that year. The numeric values of the components year, month, day, hour, minute, and second
are the same in the ISO calendar as the values used in the lexical representation of the date and
time as defined in <bibref ref="xmlschema-2"/>. The era ("E" component)
with this calendar is either a minus sign (for negative years) or a zero-length string (for positive years).
For dates before 1 January, AD 1, year numbers in
    the ISO and AD calendars are off by one from each other: ISO year
    0000 is 1 BC, -0001 is 2 BC, etc.</p><p>ISO 8601 does not define a numbering for weeks within a month. When the <code>w</code>
               component is used, the convention to be adopted is that each Monday-to-Sunday week is considered to
               fall within a particular month if its Thursday occurs in that month; the weeks that fall in a particular
               month under this definition are numbered starting from 1. Thus, for example, 
               29 January 2013 falls in week 5 because the Thursday of the week (31 January 2013) is the fifth Thursday
               in January, and 1 February 2013 is also in week 5 for the same reason.</p><note><p>The value space of the date and time datatypes, as defined in XML Schema, is based on
absolute points in time. The lexical space of these datatypes defines a 
representation of these absolute points in time using the proleptic Gregorian calendar,
that is, the modern Western calendar extrapolated into the past and the future; but the value space
is calendar-neutral. The
<termref def="dt-date-formatting-function">date formatting functions</termref> produce a representation
of this absolute point in time, but denoted in a possibly different calendar. So,
for example, the date whose lexical representation in XML Schema is <code>1502-01-11</code> 
(the day on which Pope Gregory XIII was born) might be
formatted using the Old Style (Julian) calendar as <code>1 January 1502</code>. This reflects the fact
that there was at that time a ten-day difference between the two calendars. It would be
incorrect, and would produce incorrect results, to represent this date in an element or attribute 
of type <code>xs:date</code> as <code>1502-01-01</code>, even though this might reflect the way 
the date was recorded in contemporary documents.</p><p>When referring to years occurring in antiquity, modern historians generally
use a numbering system in which there is no year zero (the year before 1 CE
is thus 1 BCE). This is the convention that <rfc2119>should</rfc2119> be used when the
requested calendar is OS (Julian) or AD (Gregorian). When the requested
calendar is ISO, however, the conventions of ISO 8601 <rfc2119>should</rfc2119> be followed:
here the year before +0001 is numbered zero. In <bibref ref="xmlschema-2"/> (version 1.0), 
the value space for <code>xs:date</code> and <code>xs:dateTime</code>
does not include a year zero: however, XSD 1.1 endorses the ISO 8601 convention. This means that the date on
which Julius Caesar was assassinated has the ISO 8601 lexical representation
-0043-03-13, but will be formatted as 15 March 44 BCE in the Julian calendar
or 13 March 44 BCE in the Gregorian calendar (dependant on the chosen
localization of the names of months and eras).</p></note><p>The intended use of the <code>$place</code> argument is to identify
 the place where an event
represented by the <code>dateTime</code>, <code>date</code>,
or <code>time</code> supplied in the <code>$value</code> argument took place or will take place.
                  If the <code>$place</code> argument is omitted or is set
                  to an empty sequence, then the default place defined in the dynamic context is used.
If the value is supplied, and is not the empty sequence, then it <rfc2119>should</rfc2119> 
                  either be a country code or an <phrase diff="chg" at="E">IANA</phrase> timezone name.
               If the value does not take this form, or if its value is not recognized
               by the implementation, then the default place defined in the dynamic context is used.</p><ulist><item><p>Country codes are defined in <bibref ref="ISO3166"/>. Examples are "de" for Germany
      and "jp" for Japan. Implementations <rfc2119>may</rfc2119> also allow the use
of codes representing subdivisions of a country from ISO 3166-2, or codes representing formerly used names of
countries from ISO 3166-3</p></item><item><p><phrase diff="chg" at="E">IANA</phrase> timezone names are defined in the <phrase diff="chg" at="E">IANA</phrase> timezone database <bibref ref="olson"/>.
   Examples are "America/New_York" and "Europe/Rome".</p></item></ulist><p>This argument is not intended to identify the location of the user 
for whom the date or time is being formatted;
that should be done by means of the <code>$language</code> attribute. 
This information 
<rfc2119>may</rfc2119> be used to provide additional information when converting dates between
calendars or when deciding how individual components of the date and time are to be formatted. 
For example, different countries using the Old Style (Julian) calendar started the new year on different
days, and some countries used variants of the calendar that were out of synchronization as a result of
differences in calculating leap years.</p><p>The geographical area identified by a country code is defined by the
  boundaries as they existed at the time of the date to be formatted,
  or the present-day boundaries for dates in the future.</p><p>If the <code>$place</code> argument is supplied in the form
                  of an <phrase diff="chg" at="E">IANA</phrase> timezone name that is recognized by the implementation, then the date or
               time being formatted is adjusted to the timezone offset applicable in that timezone.
               For example, if the <code>xs:dateTime</code> value <code>2010-02-15T12:00:00Z</code>
                  is formatted with the <code>$place</code> argument set to
                  <code>America/New_York</code>, then the output will be as if the value
                  <code>2010-02-15T07:00:00-05:00</code> had been supplied. This adjustment takes daylight
                  savings time into account where possible; if the date in question falls during
                  daylight savings time in New York, then it is adjusted to timezone offset <code>-PT4H</code>
                  rather than <code>-PT5H</code>. Adjustment using daylight savings time is only possible
                  where the value includes a date, and where the date is within the range covered
                  by the timezone database.</p></div4></div3><div3 id="date-time-examples"><head>Examples of date and time formatting</head><p>The following examples show a selection of dates and times and the way they might
be formatted. These examples assume the use of the Gregorian calendar as the default calendar.</p><table role="data"><thead><tr><th rowspan="1" colspan="1">Required Output</th><th rowspan="1" colspan="1">Expression</th></tr></thead><tbody><tr><td rowspan="1" colspan="1">
                              <code>2002-12-31</code>
                           </td><td rowspan="1" colspan="1">
                              <code>format-date($d, "[Y0001]-[M01]-[D01]")</code>
                           </td></tr><tr><td rowspan="1" colspan="1">
                              <code>12-31-2002</code>
                           </td><td rowspan="1" colspan="1">
                              <code>format-date($d, "[M]-[D]-[Y]")</code>
                           </td></tr><tr><td rowspan="1" colspan="1"> 
                              <code>31-12-2002</code>
                           </td><td rowspan="1" colspan="1">
                              <code>format-date($d, "[D]-[M]-[Y]")</code>
                           </td></tr><tr><td rowspan="1" colspan="1">
                              <code>31 XII 2002</code>
                           </td><td rowspan="1" colspan="1">
                              <code>format-date($d, "[D1] [MI] [Y]")</code>
                           </td></tr><tr><td rowspan="1" colspan="1">
                              <code>31st December, 2002</code>
                           </td><td rowspan="1" colspan="1">
                              <code>format-date($d, "[D1o] [MNn], [Y]", "en", (), ())</code>
                           </td></tr><tr><td rowspan="1" colspan="1">
                              <code>31 DEC 2002</code>
                           </td><td rowspan="1" colspan="1">
                              <code>format-date($d, "[D01] [MN,*-3] [Y0001]", "en", (), ())</code>
                           </td></tr><tr><td rowspan="1" colspan="1">
                              <code>December 31, 2002</code>
                           </td><td rowspan="1" colspan="1">
                              <code>format-date($d, "[MNn] [D], [Y]", "en", (), ())</code>
                           </td></tr><tr><td rowspan="1" colspan="1">
                              <code>31 Dezember, 2002</code>
                           </td><td rowspan="1" colspan="1">
                              <code>format-date($d, "[D] [MNn], [Y]", "de", (), ())</code>
                           </td></tr><tr><td rowspan="1" colspan="1">
                              <code>Tisdag 31 December 2002</code>
                           </td><td rowspan="1" colspan="1">
                              <code>format-date($d, "[FNn] [D] [MNn] [Y]", "sv", (), ())</code>
                           </td></tr><tr><td rowspan="1" colspan="1">
                              <code>[2002-12-31]</code>
                           </td><td rowspan="1" colspan="1">
                              <code>format-date($d, "[[[Y0001]-[M01]-[D01]]]")</code>
                           </td></tr><tr><td rowspan="1" colspan="1">
                              <code>Two Thousand and Three</code>
                           </td><td rowspan="1" colspan="1">
                              <code>format-date($d, "[YWw]", "en", (), ())</code>
                           </td></tr><tr><td rowspan="1" colspan="1">
                              <code>einunddreißigste Dezember</code>
                           </td><td rowspan="1" colspan="1">
                              <code>format-date($d, "[Dwo] [MNn]", "de", (), ())</code>
                           </td></tr><tr><td rowspan="1" colspan="1">
                              <code>3:58 PM</code>
                           </td><td rowspan="1" colspan="1">
                              <code>format-time($t, "[h]:[m01] [PN]", "en", (), ())</code>
                           </td></tr><tr><td rowspan="1" colspan="1">
                              <code>3:58:45 pm</code>
                           </td><td rowspan="1" colspan="1">
                              <code>format-time($t, "[h]:[m01]:[s01] [Pn]", "en", (), ())</code>
                           </td></tr><tr><td rowspan="1" colspan="1">
                              <code>3:58:45 PM PDT</code>
                           </td><td rowspan="1" colspan="1">
                              <code>format-time($t, "[h]:[m01]:[s01] [PN] [ZN,*-3]", "en", (), ())</code>
                           </td></tr><tr><td rowspan="1" colspan="1">
                              <code>3:58:45 o'clock PM PDT</code>
                           </td><td rowspan="1" colspan="1">
                              <code>format-time($t, "[h]:[m01]:[s01] o'clock [PN] [ZN,*-3]", "en", (), ())</code>
                           </td></tr><tr><td rowspan="1" colspan="1">
                              <code>15:58</code>
                           </td><td rowspan="1" colspan="1">
                              <code>format-time($t,"[H01]:[m01]")</code>
                           </td></tr><tr><td rowspan="1" colspan="1">
                              <code>15:58:45.762</code>
                           </td><td rowspan="1" colspan="1">
                              <code>format-time($t,"[H01]:[m01]:[s01].[f001]")</code>
                           </td></tr><tr><td rowspan="1" colspan="1">
                              <code>15:58:45 GMT+02:00</code>
                           </td><td rowspan="1" colspan="1">
                              <code>format-time($t,"[H01]:[m01]:[s01] [z,6-6]", "en", (), ())</code>
                           </td></tr><tr><td rowspan="1" colspan="1">
                              <code>15.58 Uhr GMT+2</code>
                           </td><td rowspan="1" colspan="1">
                              <code>format-time($t,"[H01]:[m01] Uhr [z]", "de", (), ())</code>
                           </td></tr><tr><td rowspan="1" colspan="1">
                              <code>3.58pm on Tuesday, 31st December</code>
                           </td><td rowspan="1" colspan="1">
                              <code>format-dateTime($dt, "[h].[m01][Pn] on [FNn], [D1o] [MNn]")</code>
                           </td></tr><tr><td rowspan="1" colspan="1">
                              <code>12/31/2002 at 15:58:45</code>
                           </td><td rowspan="1" colspan="1">
                              <code>format-dateTime($dt, "[M01]/[D01]/[Y0001] at [H01]:[m01]:[s01]")</code>
                           </td></tr></tbody></table><p>The following examples use calendars other than the Gregorian calendar.</p><table role="data"><thead><tr><th rowspan="1" colspan="1">Description</th><th rowspan="1" colspan="1">Request</th><th rowspan="1" colspan="1">Result</th></tr></thead><tbody><tr><td rowspan="1" colspan="1">Islamic</td><td rowspan="1" colspan="1">
                              <code>format-date($d, "[D&amp;#x0661;] [Mn] [Y&amp;#x0661;]", "ar", "AH", ())</code>
                           </td><td rowspan="1" colspan="1">٢٦ ﺸﻭّﺍﻝ ١٤٢٣</td></tr><tr><td rowspan="1" colspan="1">Jewish (with Western numbering)</td><td rowspan="1" colspan="1">
                              <code>format-date($d, "[D] [Mn] [Y]", "he", "AM", ())</code>
                           </td><td rowspan="1" colspan="1">‏26 טבת 5763</td></tr><tr><td rowspan="1" colspan="1">Jewish (with traditional numbering)</td><td rowspan="1" colspan="1">
                              <code>format-date($d, "[D&amp;#x05D0;t] [Mn] [Y&amp;#x05D0;t]", "he", "AM", ())</code>
                           </td><td rowspan="1" colspan="1">כ״ו טבת תשס״ג</td></tr><tr><td rowspan="1" colspan="1">Julian (Old Style)</td><td rowspan="1" colspan="1">
                              <code>format-date($d, "[D] [MNn] [Y]", "en", "OS", ())</code>
                           </td><td rowspan="1" colspan="1">18 December 2002</td></tr><tr><td rowspan="1" colspan="1">Thai</td><td rowspan="1" colspan="1">
                              <code>format-date($d, "[D&amp;#x0E51;] [Mn] [Y&amp;#x0E51;]", "th", "BE", ())</code>
                           </td><td rowspan="1" colspan="1">๓๑ ธันวาคม 
๒๕๔๕</td></tr></tbody></table></div3></div2><div2 id="parsing-dates-and-times" diff="add" at="A"><head>Parsing dates and times</head><table class="index"><thead><tr><th rowspan="1" colspan="1">Function</th><th rowspan="1" colspan="1">Meaning</th></tr></thead><tbody><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:parse-ietf-date</code></td><td rowspan="1" colspan="1">Parses a string containing the date and time in IETF format, returning the corresponding
               <code>xs:dateTime</code> value.</td></tr></tbody></table><p>A function is provided to parse dates and times expressed using syntax that is commonly encountered
            in internet protocols.</p><div3 id="func-parse-ietf-date"><head>fn:parse-ietf-date</head><glist><gitem><label>Summary</label><def><p>Parses a string containing the date and time in IETF format, returning the corresponding
               <code>xs:dateTime</code> value.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="parse-ietf-date" return-type="xs:dateTime?" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="value" type="xs:string?"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>The function accepts a string matching the production <code>input</code> in the
            following grammar:</p><table role="scrap"><tr><td rowspan="1" colspan="1">
                  <code>input</code>
               </td><td rowspan="1" colspan="1"><code>::=</code></td><td diff="chg" at="B" rowspan="1" colspan="1">
                  <code>S? (dayname ","? S)? ((datespec S time) | asctime) S?</code>
               </td></tr><tr><td rowspan="1" colspan="1">
                  <code>dayname</code>
               </td><td rowspan="1" colspan="1"><code>::=</code></td><td rowspan="1" colspan="1">
                  <code>"Mon" | "Tue" | "Wed" | "Thu" | "Fri" | "Sat" | "Sun" | "Monday | "Tuesday"
                     | "Wednesday" | "Thursday" | "Friday" | "Saturday" | "Sunday"</code>
               </td></tr><tr><td rowspan="1" colspan="1">
                  <code>datespec</code>
               </td><td rowspan="1" colspan="1"><code>::=</code></td><td rowspan="1" colspan="1">
                  <code>daynum dsep monthname dsep year</code>
               </td></tr><tr><td rowspan="1" colspan="1">
                  <code>asctime</code>
               </td><td rowspan="1" colspan="1"><code>::=</code></td><td rowspan="1" colspan="1">
                  <code>monthname dsep daynum S time S year</code>
               </td></tr><tr><td rowspan="1" colspan="1">
                  <code>dsep</code>
               </td><td rowspan="1" colspan="1"><code>::=</code></td><td rowspan="1" colspan="1">
                  <code>S | (S? "-" S?)</code>
               </td></tr><tr><td rowspan="1" colspan="1">
                  <code>daynum</code>
               </td><td rowspan="1" colspan="1"><code>::=</code></td><td rowspan="1" colspan="1">
                  <code>digit digit?</code>
               </td></tr><tr><td rowspan="1" colspan="1">
                  <code>year</code>
               </td><td rowspan="1" colspan="1"><code>::=</code></td><td rowspan="1" colspan="1">
                  <code>digit digit (digit digit)?</code>
               </td></tr><tr><td rowspan="1" colspan="1">
                  <code>digit</code>
               </td><td rowspan="1" colspan="1"><code>::=</code></td><td rowspan="1" colspan="1">
                  <code>[0-9]</code>
               </td></tr><tr><td rowspan="1" colspan="1">
                  <code>monthname</code>
               </td><td rowspan="1" colspan="1"><code>::=</code></td><td rowspan="1" colspan="1">
                  <code>"Jan" | "Feb" | "Mar" | "Apr" | "May" | "Jun" | "Jul" | "Aug" | "Sep" |
                     "Oct" | "Nov" | "Dec"</code>
               </td></tr><tr><td rowspan="1" colspan="1">
                  <code>time</code>
               </td><td rowspan="1" colspan="1"><code>::=</code></td><td rowspan="1" colspan="1">
                  <code>hours ":" minutes (":" seconds)? (S? timezone)?</code>
               </td></tr><tr><td rowspan="1" colspan="1">
                  <code>hours</code>
               </td><td rowspan="1" colspan="1"><code>::=</code></td><td rowspan="1" colspan="1">
                  <phrase diff="chg" at="E"><code>digit digit?</code></phrase>
               </td></tr><tr><td rowspan="1" colspan="1">
                  <code>minutes</code>
               </td><td rowspan="1" colspan="1"><code>::=</code></td><td rowspan="1" colspan="1">
                  <code>digit digit</code>
               </td></tr><tr><td rowspan="1" colspan="1">
                  <code>seconds</code>
               </td><td rowspan="1" colspan="1"><code>::=</code></td><td rowspan="1" colspan="1">
                  <code>digit digit ("." digit+)?</code>
               </td></tr><tr><td rowspan="1" colspan="1">
                  <code>timezone</code>
               </td><td rowspan="1" colspan="1"><code>::=</code></td><td rowspan="1" colspan="1">
                  <code>tzname | tzoffset (S? "(" S? tzname S? ")")?</code>
               </td></tr><tr><td rowspan="1" colspan="1">
                  <code>tzname</code>
               </td><td rowspan="1" colspan="1"><code>::=</code></td><td rowspan="1" colspan="1">
                  <code>"UT" | "UTC" | "GMT" | "EST" | "EDT" | "CST" | "CDT" | "MST" | "MDT" | "PST"
                     | "PDT" </code>
               </td></tr><tr><td rowspan="1" colspan="1">
                  <code>tzoffset</code>
               </td><td rowspan="1" colspan="1"><code>::=</code></td><td rowspan="1" colspan="1">
                  <phrase diff="chg" at="E"><code>("+"|"-") hours ":"? minutes?</code></phrase>
               </td></tr><tr><td rowspan="1" colspan="1">
                  <code>S</code>
               </td><td rowspan="1" colspan="1"><code>::=</code></td><td rowspan="1" colspan="1">
                  <code diff="chg" at="C">( x09 | x0A | x0D | x20 )+</code>
               </td></tr></table><p>The input is case-insensitive: upper-case and lower-case distinctions in the above
            grammar show the conventional usage, but otherwise have no significance.</p><p diff="add" at="D">If the input is an empty sequence, the result is an empty sequence.</p><p>The <code>dayname</code>, if present, is ignored.</p><p>The <code>daynum</code>, <code>monthname</code>, and <code>year</code> supply the day,
            month, and year of the resulting <code>xs:dateTime</code> value. A two-digit year
               <rfc2119>must</rfc2119> have 1900 added to it. A year such as 0070 is to be treated
            as given; negative years are not permitted.</p><p>The <code>hours</code>, <code>minutes</code>, and <code>seconds</code> (including
            fractional seconds) values supply the corresponding components of the resulting
               <code>xs:dateTime</code> value; if the <code>seconds</code> value 
            <phrase diff="add" at="E">or the fractional seconds value</phrase> is absent then zero
            is assumed.</p><p>If both a <code>tzoffset</code> and a <code>tzname</code> are supplied then the
               <code>tzname</code> is ignored.</p><p>If a <code>tzoffset</code> is supplied then this defines the hours and minutes parts of the timezone offset:</p><ulist diff="chg" at="E"><item><p>If it contains a colon, this separates the hours part from the minutes part.</p></item><item><p>Otherwise, the grammar allows a sequence of from one to four digits. These are interpreted
            as <code>H</code>, <code>HH</code>, <code>HMM</code>, or <code>HHMM</code> respectively, where <code>H</code>
            or <code>HH</code> is the hours part, and <code>MM</code> (if present) is the minutes part.</p></item><item>If the minutes part is absent it defaults to <code>00</code>.</item></ulist><p>If a <code>tzname</code> is supplied with no <code>tzoffset</code> then it is translated
            to a timezone offset as follows:</p><table class="data"><thead><tr><th rowspan="1" colspan="1">tzname</th><th rowspan="1" colspan="1">Offset</th></tr></thead><tbody><tr><td rowspan="1" colspan="1">UT, UTC, GMT</td><td rowspan="1" colspan="1">00:00</td></tr><tr><td rowspan="1" colspan="1">EST</td><td rowspan="1" colspan="1">-05:00</td></tr><tr><td rowspan="1" colspan="1">EDT</td><td rowspan="1" colspan="1">-04:00</td></tr><tr><td rowspan="1" colspan="1">CST</td><td rowspan="1" colspan="1">-06:00</td></tr><tr><td rowspan="1" colspan="1">CDT</td><td rowspan="1" colspan="1">-05:00</td></tr><tr><td rowspan="1" colspan="1">MST</td><td rowspan="1" colspan="1">-07:00</td></tr><tr><td rowspan="1" colspan="1">MDT</td><td rowspan="1" colspan="1">-06:00</td></tr><tr><td rowspan="1" colspan="1">PST</td><td rowspan="1" colspan="1">-08:00</td></tr><tr><td rowspan="1" colspan="1">PDT</td><td rowspan="1" colspan="1">-07:00</td></tr></tbody></table><p>If neither a <code>tzoffset</code> nor <code>tzname</code> is supplied, a timezone
            offset of <code>00:00</code> is assumed.</p></def></gitem><gitem><label>Error Conditions</label><def><p>A dynamic error is raised <errorref spec="FO" class="RG" code="0010"/> if the input does
            not match the grammar, or if the resulting date/time value is invalid (for example, 31
            February).</p></def></gitem><gitem><label>Notes</label><def><p role="note">The <code>parse-ietf-date</code> function attempts to interpret its input as a date
            in any of the three formats specified by HTTP <bibref ref="rfc2616"/>.</p><p role="note">These formats are used widely on the Internet to represent timestamps, and were
            specified in:</p><ulist role="note"><item><bibref ref="rfc822"/> (electronic mail), extended in <bibref ref="rfc1123"/> to allow four-digit years;</item><item><bibref ref="rfc850"/> (Usenet Messages), obsoleted by <bibref ref="rfc1036"/>;</item><item>POSIX <code>asctime()</code> format</item></ulist><p role="note"><bibref ref="rfc2616"/> (HTTP) officially uses a subset of those three formats restricted to GMT.</p><p role="note">The grammar for this function is slightly more liberal than the RFCs (reflecting the internet tradition of being liberal in what is accepted).
            For example the function:</p><olist role="note"><item><p>Accepts a single-digit value where appropriate in place of a two-digit value with a leading zero (so
                  "Wed 1 Jun" is acceptable in place of "Wed 01 Jun", <phrase diff="add" at="E">and the timezone offset "-5:00" is equivalent
                  to "-05:00")</phrase></p></item><item><p>Accepts one or more whitespace characters (x20, x09, x0A, x0D) wherever a single
                  space is required, and allows whitespace to be omitted where it is not required
                  for parsing</p></item><item><p>Accepts and ignores whitespace characters (x20, x09, x0A, x0D) at the start or end
                  of the string.</p></item></olist><p role="note">In new protocols IETF recommends the format of <bibref ref="rfc3339"/> which is based on a profile of
            ISO 8601 similar to that already used in XPath and XSD, but the "approximate" <bibref ref="rfc822"/>
            format described here is very widely used.</p><p role="note">An <bibref ref="rfc1123"/> date can be generated approximately using <code>fn:format-dateTime</code> with a picture
            string of <code>"[FNn3], [D01] [MNn3] [Y04] [H01]:[m01]:[s01] [Z0000]"</code>.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>fn:parse-ietf-date("Wed, 06 Jun 1994 07:29:35 GMT")</code> returns <code>xs:dateTime("1994-06-06T07:29:35Z")</code>.</p><p>The expression <code>fn:parse-ietf-date("Wed, 6 Jun 94 07:29:35 GMT")</code> returns <code>xs:dateTime("1994-06-06T07:29:35Z")</code>.</p><p>The expression <code>fn:parse-ietf-date("Wed Jun 06 11:54:45 EST 2013")</code> returns <code>xs:dateTime("2013-06-06T11:54:45-05:00")</code>.</p><p>The expression <code>fn:parse-ietf-date("Sunday, 06-Nov-94 08:49:37 GMT")</code> returns <code>xs:dateTime("1994-11-06T08:49:37Z")</code>.</p><p>The expression <code>fn:parse-ietf-date("Wed, 6 Jun 94 07:29:35 +0500")</code> returns <code>xs:dateTime("1994-06-06T07:29:35+05:00")</code>.</p></def></gitem></glist></div3></div2></div1><div1 id="QName-funcs"><head>Functions related to QNames</head><div2 id="QName-constructors"><head>Functions to create a QName</head><p>In addition to the <code>xs:QName</code> constructor function, QName values can
               be constructed by combining a namespace URI, prefix, and local name, or by resolving
               a lexical QName against the in-scope namespaces of an element node. This section
                    defines these functions. 
					Leading and trailing whitespace, if present, is stripped from
                    string arguments before the result is constructed.</p><table class="index"><thead><tr><th rowspan="1" colspan="1">Function</th><th rowspan="1" colspan="1">Meaning</th></tr></thead><tbody><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:resolve-QName</code></td><td rowspan="1" colspan="1">Returns an <code>xs:QName</code> value (that is, an expanded-QName) by taking an
               <code>xs:string</code> that has the lexical form of an <code>xs:QName</code> (a
            string in the form "prefix:local-name" or "local-name") and resolving it using the
            in-scope namespaces for a given element.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:QName</code></td><td rowspan="1" colspan="1">Returns an <code>xs:QName</code> value formed using a supplied namespace URI and lexical QName.</td></tr></tbody></table><div3 id="func-resolve-QName"><head>fn:resolve-QName</head><glist><gitem><label>Summary</label><def><p>Returns an <code>xs:QName</code> value (that is, an expanded-QName) by taking an
               <code>xs:string</code> that has the lexical form of an <code>xs:QName</code> (a
            string in the form "prefix:local-name" or "local-name") and resolving it using the
            in-scope namespaces for a given element.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="resolve-QName" return-type="xs:QName?" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="qname" type="xs:string?"/><arg name="element" type="element()"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>If <code>$qname</code> is the empty sequence, returns the empty sequence.</p><p>More specifically, the function searches the namespace bindings of <code>$element</code>
            for a binding whose name matches the prefix of <code>$qname</code>, or the zero-length
            string if it has no prefix, and returns an expanded-QName whose local name is taken
            from the supplied <code>$qname</code>, and whose namespace URI is taken from the string
            value of the namespace binding.</p><p>If the <code>$qname</code> has no prefix, and there is no namespace binding for
               <code>$element</code> corresponding to the default (unnamed) namespace, then the
            resulting expanded-QName has no namespace part.</p><p>The prefix (or absence of a prefix) in the supplied <code>$qname</code> argument is
            retained in the returned expanded-QName, as described in <xspecref spec="DM31" ref="terminology"/>.</p></def></gitem><gitem><label>Error Conditions</label><def><p>A dynamic error is raised <errorref class="CA" code="0002"/> if <code>$qname</code> does
            not have the correct lexical form for an instance of <code>xs:QName</code>.</p><p>A dynamic error is raised <errorref class="NS" code="0004"/> if <code>$qname</code> has
            a prefix and there is no namespace binding for <code>$element</code> that matches this
            prefix.</p></def></gitem><gitem><label>Notes</label><def><p role="note">Sometimes the requirement is to construct an <code>xs:QName</code> without using the
            default namespace. This can be achieved by writing:</p><eg role="note" xml:space="preserve"> if (contains($qname, ":")) then fn:resolve-QName($qname, $element) else
            fn:QName("", $qname)</eg><p role="note">If the requirement is to construct an <code>xs:QName</code> using the namespaces in the
            static context, then the <code>xs:QName</code> constructor should be used.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>Assume that the element bound to <code>$element</code> has a single namespace binding
               bound to the prefix <code>eg</code>.</p><p>
               <code>fn:resolve-QName("hello", $element)</code> returns a QName with local name
               "hello" that is in no namespace.</p><p>
               <code>fn:resolve-QName("eg:myFunc", $element)</code> returns an <code>xs:QName</code>
               whose namespace URI is specified by the namespace binding corresponding to the prefix
               "eg" and whose local name is "myFunc".</p></def></gitem></glist></div3><div3 id="func-QName"><head>fn:QName</head><glist><gitem><label>Summary</label><def><p diff="chg" at="C">Returns an <code>xs:QName</code> value formed using a supplied namespace URI and lexical QName.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="QName" return-type="xs:QName" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="paramURI" type="xs:string?"/><arg name="paramQName" type="xs:string"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>The namespace URI in the returned QName is taken from <code>$paramURI</code>. If
               <code>$paramURI</code> is the zero-length string or the empty sequence, it represents
            "no namespace".</p><p>The prefix (or absence of a prefix) in <code>$paramQName</code> is retained in the
            returned <code>xs:QName</code> value.</p><p>The local name in the result is taken from the local part of
            <code>$paramQName</code>.</p></def></gitem><gitem><label>Error Conditions</label><def><p>A dynamic error is raised <errorref class="CA" code="0002"/> if <code>$paramQName</code>
            does not have the correct lexical form for an instance of <code>xs:QName</code>.</p><p>A dynamic error is raised <errorref class="CA" code="0002"/> if <code>$paramURI</code>
            is the zero-length string or the empty sequence, and the value of
               <code>$paramQName</code> contains a colon (<code>:</code>).</p><p>A dynamic error <rfc2119>may</rfc2119> be raised <errorref class="CA" code="0002"/> if
               <code>$paramURI</code> is not a valid URI (XML Namespaces 1.0) or IRI (XML Namespaces
            1.1). </p></def></gitem><gitem><label>Examples</label><def role="example"><p>
               <code>fn:QName("http://www.example.com/example", "person")</code> returns an
                  <code>xs:QName</code> with namespace URI = "http://www.example.com/example", local
               name = "person" and prefix = "".</p><p>
               <code>fn:QName("http://www.example.com/example", "ht:person")</code> returns an
                  <code>xs:QName</code> with namespace URI = "http://www.example.com/example", local
               name = "person" and prefix = "ht".</p></def></gitem></glist></div3></div2><div2 id="QName-functions"><head>Functions and operators related to QNames</head><p>This section specifies functions on QNames as defined in <bibref ref="xmlschema-2"/>.</p><table class="index"><thead><tr><th rowspan="1" colspan="1">Function</th><th rowspan="1" colspan="1">Meaning</th></tr></thead><tbody><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">op:QName-equal</code></td><td rowspan="1" colspan="1">Returns <code>true</code> if two supplied QNames have the same namespace URI and the
            same local part.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:prefix-from-QName</code></td><td rowspan="1" colspan="1">Returns the prefix component of the supplied QName.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:local-name-from-QName</code></td><td rowspan="1" colspan="1">Returns the local part of the supplied QName.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:namespace-uri-from-QName</code></td><td rowspan="1" colspan="1">Returns the namespace URI part of the supplied QName.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:namespace-uri-for-prefix</code></td><td rowspan="1" colspan="1">Returns the namespace URI of one of the in-scope namespaces for <code>$element</code>,
            identified by its namespace prefix.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:in-scope-prefixes</code></td><td rowspan="1" colspan="1">Returns the prefixes of the in-scope namespaces for an element node.</td></tr></tbody></table><div3 id="func-QName-equal"><head>op:QName-equal</head><glist><gitem><label>Summary</label><def><p>Returns <code>true</code> if two supplied QNames have the same namespace URI and the
            same local part.</p></def></gitem><gitem><label>Operator Mapping</label><def><p>Defines the semantics
         of the "eq" and "ne" operators when applied to two values of type <code>xs:QName</code>. </p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="QName-equal" return-type="xs:boolean" isOp="yes" prefix="op" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg1" type="xs:QName"/><arg name="arg2" type="xs:QName"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>The function returns <code>true</code> if the namespace URIs of <code>$arg1</code> and
               <code>$arg2</code> are equal and the local names of <code>$arg1</code> and
               <code>$arg2</code> are equal.</p><p>Otherwise, the function returns <code>false</code>.</p><p>The namespace URI parts are considered equal if they are both <xtermref ref="dt-absent" spec="DM31">absent</xtermref>, or if they are both present and equal under the rules
            of the <code>fn:codepoint-equal</code> function.</p><p>The local parts are also compared under the rules of the <code>fn:codepoint-equal</code>
            function.</p></def></gitem><gitem><label>Notes</label><def><p role="note">The prefix parts of <code>$arg1</code> and <code>$arg2</code>, if any, are ignored.</p></def></gitem></glist></div3><div3 id="func-prefix-from-QName"><head>fn:prefix-from-QName</head><glist><gitem><label>Summary</label><def><p>Returns the prefix component of the supplied QName.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="prefix-from-QName" return-type="xs:NCName?" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg" type="xs:QName?"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>If <code>$arg</code> is the empty sequence the function returns the empty sequence.</p><p>If <code>$arg</code> has no prefix component the function returns the empty
            sequence.</p><p>Otherwise, the function returns an <code>xs:NCName</code> representing the prefix
            component of <code>$arg</code>.</p></def></gitem></glist></div3><div3 id="func-local-name-from-QName"><head>fn:local-name-from-QName</head><glist><gitem><label>Summary</label><def><p>Returns the local part of the supplied QName.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="local-name-from-QName" return-type="xs:NCName?" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg" type="xs:QName?"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>If <code>$arg</code> is the empty sequence the function returns the empty sequence.</p><p>Otherwise, the function returns an <code>xs:NCName</code> representing the local part of
               <code>$arg</code>.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>fn:local-name-from-QName(fn:QName("http://www.example.com/example",
                  "person"))</code> returns <code>"person"</code>.</p></def></gitem></glist></div3><div3 id="func-namespace-uri-from-QName"><head>fn:namespace-uri-from-QName</head><glist><gitem><label>Summary</label><def><p>Returns the namespace URI part of the supplied QName.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="namespace-uri-from-QName" return-type="xs:anyURI?" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg" type="xs:QName?"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>If <code>$arg</code> is the empty sequence the function returns the empty sequence.</p><p>Otherwise, the function returns an <code>xs:anyURI</code> representing the namespace URI
            part of <code>$arg</code>.</p><p>If <code>$arg</code> is in no namespace, the function returns the zero-length
               <code>xs:anyURI</code>.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>fn:namespace-uri-from-QName(fn:QName("http://www.example.com/example",
                  "person"))</code> returns <code>xs:anyURI("http://www.example.com/example")</code>.</p></def></gitem></glist></div3><div3 id="func-namespace-uri-for-prefix"><head>fn:namespace-uri-for-prefix</head><glist><gitem><label>Summary</label><def><p>Returns the namespace URI of one of the in-scope namespaces for <code>$element</code>,
            identified by its namespace prefix.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="namespace-uri-for-prefix" return-type="xs:anyURI?" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="prefix" type="xs:string?"/><arg name="element" type="element()"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>If <code>$element</code> has an in-scope namespace whose namespace prefix is equal to
               <code>$prefix</code>, the function returns the namespace URI of that namespace.</p><p>If <code>$element</code> has no in-scope namespace whose namespace prefix is equal to
               <code>$prefix</code>, the function returns the empty sequence.</p><p>If <code>$prefix</code> is the zero-length string or the empty sequence, then if
               <code>$element</code> has a default namespace (that is, a namespace node with no
            name), the function returns the namespace URI of the default namespace. If
               <code>$element</code> has no default namespace, the function returns the empty
            sequence.</p><p>Prefixes are equal only if their Unicode codepoints match exactly.</p></def></gitem><gitem><label>Examples</label><def role="example"><eg xml:space="preserve">let $e := 
&lt;z:a xmlns="http://example.org/one" xmlns:z="http://example.org/two"&gt;
  &lt;b xmlns=""/&gt;
&lt;/z:a&gt;</eg><p>The expression <code>fn:namespace-uri-for-prefix("z", $e)</code> returns <code>"http://example.org/two"</code>.</p><p>The expression <code>fn:namespace-uri-for-prefix("", $e)</code> returns <code>"http://example.org/one"</code>.</p><p>The expression <code>fn:namespace-uri-for-prefix((), $e)</code> returns <code>"http://example.org/one"</code>.</p><p>The expression <code>fn:namespace-uri-for-prefix("xml", $e)</code> returns <code>"http://www.w3.org/XML/1998/namespace"</code>.</p><p>The expression <code>fn:namespace-uri-for-prefix("xml", $e)</code> returns <code>"http://www.w3.org/XML/1998/namespace"</code>.</p></def></gitem></glist></div3><div3 id="func-in-scope-prefixes"><head>fn:in-scope-prefixes</head><glist><gitem><label>Summary</label><def><p>Returns the prefixes of the in-scope namespaces for an element node.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="in-scope-prefixes" return-type="xs:string*" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="element" type="element()"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-nondeterministic-wrt-ordering">nondeterministic-wrt-ordering</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>The function returns a sequence of strings representing the prefixes of the in-scope
            namespaces for <code>$element</code>.</p><p>For namespace bindings that have a prefix, the function returns the prefix as an
               <code>xs:NCName</code>. For the default namespace, which has no prefix, it returns
            the zero-length string. </p><p>The result sequence contains no duplicates.</p><p>The ordering of the result sequence is <termref def="implementation-dependent">implementation-dependent</termref>.</p></def></gitem><gitem><label>Notes</label><def><p role="note">The XML namespace is in scope for every element, so the result will always include the string "xml".</p></def></gitem></glist></div3></div2></div1><div1 id="binary-functions"><head>Operators on base64Binary and hexBinary</head><div2 id="binary-value-comparisons"><head>Comparisons of base64Binary and hexBinary values</head><p>The following comparison operators on <code>xs:base64Binary</code> and
                    <code>xs:hexBinary</code> values are defined. Comparisons take two operands of
                    the same type; that is, both operands must be <code>xs:base64Binary</code> or
                    both operands may be <code>xs:hexBinary</code>. Each returns a boolean value.</p><p>A value of type <code>xs:hexBinary</code> can be compared with a value of type
                    <code>xs:base64Binary</code> by casting one value to the other type. See
                        <specref ref="casting-to-binary"/>.</p><table class="index"><thead><tr><th rowspan="1" colspan="1">Function</th><th rowspan="1" colspan="1">Meaning</th></tr></thead><tbody><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">op:hexBinary-equal</code></td><td rowspan="1" colspan="1">Returns true if two <code>xs:hexBinary</code> values contain the same octet
            sequence.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">op:hexBinary-less-than</code></td><td rowspan="1" colspan="1">Returns true if the first argument is less than the second.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">op:hexBinary-greater-than</code></td><td rowspan="1" colspan="1">Returns true if the first argument is greater than the second.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">op:base64Binary-equal</code></td><td rowspan="1" colspan="1">Returns true if two <code>xs:base64Binary</code> values contain the same octet
            sequence.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">op:base64Binary-less-than</code></td><td rowspan="1" colspan="1">Returns true if the first argument is less than the second.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">op:base64Binary-greater-than</code></td><td rowspan="1" colspan="1">Returns true if the first argument is greater than the second.</td></tr></tbody></table><div3 id="func-hexBinary-equal"><head>op:hexBinary-equal</head><glist><gitem><label>Summary</label><def><p>Returns true if two <code>xs:hexBinary</code> values contain the same octet
            sequence.</p></def></gitem><gitem><label>Operator Mapping</label><def><p>Defines the semantics of
         the "eq" and "ne" operators when applied to two <code>xs:hexBinary</code>
         values.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="hexBinary-equal" return-type="xs:boolean" isOp="yes" prefix="op" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="value1" type="xs:hexBinary"/><arg name="value2" type="xs:hexBinary"/></proto></example></def></gitem><gitem><label>Rules</label><def><p>The function returns <code>true</code> if <code>$value1</code> and <code>$value2</code>
            are of the same length, measured in binary octets, and contain the same octets in the
            same order. Otherwise, it returns <code>false</code>. </p></def></gitem></glist></div3><div3 id="func-hexBinary-less-than" diff="add" at="A"><head>op:hexBinary-less-than</head><glist><gitem><label>Summary</label><def><p>Returns true if the first argument is less than the second.</p></def></gitem><gitem><label>Operator Mapping</label><def><p>Defines the semantics of
         the "lt" operator when applied to two <code>xs:hexBinary</code> values. Also used in the
         definition of the "ge" operator.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="hexBinary-less-than" return-type="xs:boolean" isOp="yes" prefix="op" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg1" type="xs:hexBinary"/><arg name="arg2" type="xs:hexBinary"/></proto></example></def></gitem><gitem><label>Rules</label><def><p>The function returns <code>true</code> if any of the following conditions is true:</p><olist><item><p><code>$arg1</code> is zero-length (contains no octets) and <code>$arg2</code> is
                  not zero-length.</p></item><item><p>Neither argument is zero-length, and the first octet of <code>$arg1</code> is less
                  than the first octet of <code>$arg2</code>, treating the value of the octet as an
                  unsigned integer in the range 0 to 255.</p></item><item><p>Neither argument is zero-length, the first octet of <code>$arg1</code> is equal to
                  the first octet of <code>$arg2</code>, and the <code>xs:hexBinary</code> value
                  formed by taking all octets of <code>arg1</code> after the first is less than the
                     <code>xs:hexBinary</code> value formed by taking all octets of
                     <code>arg2</code> after the first.</p></item></olist><p>Otherwise, the function returns <code>false</code>.</p></def></gitem></glist></div3><div3 id="func-hexBinary-greater-than" diff="add" at="A"><head>op:hexBinary-greater-than</head><glist><gitem><label>Summary</label><def><p>Returns true if the first argument is greater than the second.</p></def></gitem><gitem><label>Operator Mapping</label><def><p>Defines the semantics of
         the "gt" operator when applied to two <code>xs:hexBinary</code> values. Also used in the
         definition of the "le" operator.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="hexBinary-greater-than" return-type="xs:boolean" isOp="yes" prefix="op" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg1" type="xs:hexBinary"/><arg name="arg2" type="xs:hexBinary"/></proto></example></def></gitem><gitem><label>Rules</label><def><p>The function call <code>op:hexBinary-greater-than($A, $B)</code> is defined to return
            the same result as <code>op:hexBinary-less-than($B, $A)</code></p></def></gitem></glist></div3><div3 id="func-base64Binary-equal"><head>op:base64Binary-equal</head><glist><gitem><label>Summary</label><def><p>Returns true if two <code>xs:base64Binary</code> values contain the same octet
            sequence.</p></def></gitem><gitem><label>Operator Mapping</label><def><p>Defines the semantics
         of the "eq" and "ne" operators when applied to two <code>xs:base64Binary</code>
         values.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="base64Binary-equal" return-type="xs:boolean" isOp="yes" prefix="op" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="value1" type="xs:base64Binary"/><arg name="value2" type="xs:base64Binary"/></proto></example></def></gitem><gitem><label>Rules</label><def><p>The function returns <code>true</code> if <code>$value1</code> and <code>$value2</code>
            are of the same length, measured in binary octets, and contain the same octets in the
            same order. Otherwise, it returns <code>false</code>. </p></def></gitem></glist></div3><div3 id="func-base64Binary-less-than" diff="add" at="A"><head>op:base64Binary-less-than</head><glist><gitem><label>Summary</label><def><p>Returns true if the first argument is less than the second.</p></def></gitem><gitem><label>Operator Mapping</label><def><p>Defines the semantics
         of the "lt" operator when applied to two <code>xs:base64Binary</code> values. Also used in
         the definition of the "ge" operator.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="base64Binary-less-than" return-type="xs:boolean" isOp="yes" prefix="op" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg1" type="xs:base64Binary"/><arg name="arg2" type="xs:base64Binary"/></proto></example></def></gitem><gitem><label>Rules</label><def><p>The function returns <code>true</code> if any of the following conditions is true:</p><olist><item><p><code>$arg1</code> is zero-length (contains no octets) and <code>$arg2</code> is
                  not zero-length.</p></item><item><p>Neither argument is zero-length, and the first octet of <code>$arg1</code> is less
                  than the first octet of <code>$arg2</code>, treating the value of the octet as an
                  unsigned integer in the range 0 to 255.</p></item><item><p>Neither argument is zero-length, the first octet of <code>$arg1</code> is equal to
                  the first octet of <code>$arg2</code>, and the <code>xs:base64Binary</code> value
                  formed by taking all octets of <code>arg1</code> after the first is less than the
                     <code>xs:base64Binary</code> value formed by taking all octets of
                     <code>arg2</code> after the first.</p></item></olist><p>Otherwise, the function returns <code>false</code>.</p></def></gitem></glist></div3><div3 id="func-base64Binary-greater-than" diff="add" at="A"><head>op:base64Binary-greater-than</head><glist><gitem><label>Summary</label><def><p>Returns true if the first argument is greater than the second.</p></def></gitem><gitem><label>Operator Mapping</label><def><p>Defines the semantics
         of the "gt" operator when applied to two <code>xs:base64Binary</code> values. Also used in
         the definition of the "le" operator.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="base64Binary-greater-than" return-type="xs:boolean" isOp="yes" prefix="op" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg1" type="xs:base64Binary"/><arg name="arg2" type="xs:base64Binary"/></proto></example></def></gitem><gitem><label>Rules</label><def><p>The function call <code>op:base64Binary-greater-than($A, $B)</code> is defined to return
            the same result as <code>op:base64Binary-less-than($B, $A)</code></p></def></gitem></glist></div3></div2></div1><div1 id="NOTATION-functions"><head>Operators on NOTATION</head><p>This section specifies operators that take <code>xs:NOTATION</code> values as arguments.</p><table class="index"><thead><tr><th rowspan="1" colspan="1">Function</th><th rowspan="1" colspan="1">Meaning</th></tr></thead><tbody><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">op:NOTATION-equal</code></td><td rowspan="1" colspan="1">Returns <code>true</code> if the two <code>xs:NOTATION</code> values have the same
            namespace URI and the same local part.</td></tr></tbody></table><div2 id="func-NOTATION-equal"><head>op:NOTATION-equal</head><glist><gitem><label>Summary</label><def><p>Returns <code>true</code> if the two <code>xs:NOTATION</code> values have the same
            namespace URI and the same local part.</p></def></gitem><gitem><label>Operator Mapping</label><def><p>Defines the
         semantics of the "eq" and "ne" operators when applied to two values of type
            <code>xs:NOTATION</code>. </p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="NOTATION-equal" return-type="xs:boolean" isOp="yes" prefix="op" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg1" type="xs:NOTATION"/><arg name="arg2" type="xs:NOTATION"/></proto></example></def></gitem><gitem><label>Rules</label><def><p>The function returns <code>true</code> if the namespace URIs of <code>$arg1</code> and
               <code>$arg2</code> are equal and the local names of <code>$arg1</code> and
               <code>$arg2</code> are equal.</p><p>Otherwise, the function returns <code>false</code>.</p><p>The namespace URI parts are considered equal if they are both <xtermref ref="dt-absent" spec="DM31">absent</xtermref>, or if they are both present and equal under the rules
            of the <code>fn:codepoint-equal</code> function.</p><p>The local parts are also compared under the rules of the <code>fn:codepoint-equal</code>
            function.</p></def></gitem><gitem><label>Notes</label><def><p role="note">The prefix parts of <code>$arg1</code> and <code>$arg2</code>, if any, are ignored.</p></def></gitem></glist></div2></div1><div1 id="node-functions"><head>Functions and operators on nodes</head><p>This section specifies functions and operators on nodes. Nodes are formally defined
                in <xspecref spec="DM31" ref="Node"/>.</p><table class="index"><thead><tr><th rowspan="1" colspan="1">Function</th><th rowspan="1" colspan="1">Meaning</th></tr></thead><tbody><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:name</code></td><td rowspan="1" colspan="1">Returns the name of a node, as an <code>xs:string</code> that is either the zero-length
            string, or has the lexical form of an <code>xs:QName</code>. </td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:local-name</code></td><td rowspan="1" colspan="1">Returns the local part of the name of <code>$arg</code> as an <code>xs:string</code>
            that is either the zero-length string, or has the lexical form of an
               <code>xs:NCName</code>.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:namespace-uri</code></td><td rowspan="1" colspan="1">Returns the namespace URI part of the name of <code>$arg</code>, as an
               <code>xs:anyURI</code> value.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:lang</code></td><td rowspan="1" colspan="1">This function tests whether the language of <code>$node</code>, or the context item if
            the second argument is omitted, as specified by <code>xml:lang</code> attributes is the
            same as, or is a sublanguage of, the language specified by <code>$testlang</code>.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:root</code></td><td rowspan="1" colspan="1">Returns the root of the tree to which <code>$arg</code> belongs. This will usually, but
            not necessarily, be a document node.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:path</code></td><td rowspan="1" colspan="1">Returns a path expression that can be used to select the supplied node relative to the
            root of its containing document.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:has-children</code></td><td rowspan="1" colspan="1">Returns true if the supplied node has one or more child nodes (of any kind).</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:innermost</code></td><td rowspan="1" colspan="1">Returns every node within the input sequence that is not an ancestor of another member
            of the input sequence; the nodes are returned in document order with duplicates
            eliminated.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:outermost</code></td><td rowspan="1" colspan="1">Returns every node within the input sequence that has no ancestor that is itself a
            member of the input sequence; the nodes are returned in document order with duplicates
            eliminated.</td></tr></tbody></table><p>For the illustrative examples below assume an XQuery or transformation operating on a
                <code>PurchaseOrder</code> document containing a number of <code>line-item</code> elements. Each line-item has
                child elements called <code>description</code>, <code>price</code>, <code>quantity</code>, etc. whose content is different
                for each <code>line-item</code>. Quantity has simple content of type <code>xs:decimal</code>.
                Further assume that variables <code>$item1</code>, <code>$item2</code>, etc. are
                each bound to single line-item element nodes in the document in sequence and that
                the value of the quantity child of the first line-item is <code>5.0</code>.</p><eg xml:space="preserve" role="global-variable-binding">let $po :=
&lt;PurchaseOrder&gt;
  &lt;line-item&gt;
    &lt;description&gt;Large widget&lt;/description&gt;
    &lt;price&gt;8.95&lt;/price&gt;
    &lt;quantity&gt;5.0&lt;/quantity&gt;
  &lt;/line-item&gt;
  &lt;line-item&gt;
    &lt;description&gt;Small widget&lt;/description&gt;
    &lt;price&gt;3.99&lt;/price&gt;
    &lt;quantity&gt;2.0&lt;/quantity&gt;
  &lt;/line-item&gt;
  &lt;line-item&gt;
    &lt;description&gt;Tiny widget&lt;/description&gt;
    &lt;price&gt;1.49&lt;/price&gt;
    &lt;quantity&gt;805&lt;/quantity&gt;
  &lt;/line-item&gt;
&lt;/PurchaseOrder&gt;</eg><eg role="global-variable-binding" xml:space="preserve">let $item1 := $po/line-item[1]</eg><eg role="global-variable-binding" xml:space="preserve">let $item2 := $po/line-item[2]</eg><eg role="global-variable-binding" xml:space="preserve">let $item3 := $po/line-item[3]</eg><div2 id="func-name"><head>fn:name</head><glist><gitem><label>Summary</label><def><p>Returns the name of a node, as an <code>xs:string</code> that is either the zero-length
            string, or has the lexical form of an <code>xs:QName</code>. </p></def></gitem><gitem><label>Signatures</label><def><example role="signature"><proto name="name" return-type="xs:string" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"/></example><example role="signature"><proto name="name" return-type="xs:string" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg" type="node()?"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>The zero-argument form of this function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-dependent">context-dependent</termref>,  and <termref def="dt-focus-dependent">focus-dependent</termref>. </p><p>The one-argument form of this function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>If the argument is omitted, it defaults to the context item (<code>.</code>). The
            behavior of the function if the argument is omitted is exactly the same as if the
            context item had been passed as the argument.</p><p>If the argument is supplied and is the empty sequence, the function returns the
            zero-length string.</p><p>If the node identified by <code>$arg</code> 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.</p><p>Otherwise, the function returns the value of the expression
               <code>fn:string(fn:node-name($arg))</code>.</p></def></gitem><gitem><label>Error Conditions</label><def><p>The following errors may be raised when <code>$arg</code> is omitted:</p><ul><li>
               <p>If the context item is <xtermref ref="dt-absent" spec="DM31">absent</xtermref>,
                  dynamic error <xerrorref spec="XP" class="DY" code="0002" type="dynamic"/></p>
            </li><li>
               <p>If the context item is not a node, type error <xerrorref spec="XP" class="TY" code="0004" type="type"/>.</p>
            </li></ul></def></gitem><gitem><label>Notes</label><def><p role="note">Because the result depends on the choice of namespace prefixes in the source document,
         it is not good practice to use the result of this function for anything other than display
         purposes. For example, the test <code>name(.) = 'my:profile'</code> will fail if the source
         document uses an unexpected namespace prefix. Such a test (assuming it relates to an element node) 
         is better written as <code>boolean(self::my:profile)</code>.</p></def></gitem></glist></div2><div2 id="func-local-name"><head>fn:local-name</head><glist><gitem><label>Summary</label><def><p>Returns the local part of the name of <code>$arg</code> as an <code>xs:string</code>
            that is either the zero-length string, or has the lexical form of an
               <code>xs:NCName</code>.</p></def></gitem><gitem><label>Signatures</label><def><example role="signature"><proto name="local-name" return-type="xs:string" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"/></example><example role="signature"><proto name="local-name" return-type="xs:string" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg" type="node()?"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>The zero-argument form of this function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-dependent">context-dependent</termref>,  and <termref def="dt-focus-dependent">focus-dependent</termref>. </p><p>The one-argument form of this function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>If the argument is omitted, it defaults to the context item (<code>.</code>). The
            behavior of the function if the argument is omitted is exactly the same as if the
            context item had been passed as the argument.</p><p>If the argument is supplied and is the empty sequence, the function returns the
            zero-length string.</p><p>If the node identified by <code>$arg</code> 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.</p><p>Otherwise, the function returns the local part of the expanded-QName of the node
            identified by <code>$arg</code>, as determined by the <code>dm:node-name</code> accessor
            defined in <xspecref spec="DM31" ref="dm-node-name"/>). This will be an
               <code>xs:string</code> whose lexical form is an <code>xs:NCName</code>.</p></def></gitem><gitem><label>Error Conditions</label><def><p>The following errors may be raised when <code>$arg</code> is omitted:</p><ul><li>
               <p>If the context item is <xtermref ref="dt-absent" spec="DM31">absent</xtermref>,
                  dynamic error <xerrorref spec="XP" class="DY" code="0002" type="dynamic"/></p>
            </li><li>
               <p>If the context item is not a node, type error <xerrorref spec="XP" class="TY" code="0004" type="type"/>.</p>
            </li></ul></def></gitem></glist></div2><div2 id="func-namespace-uri"><head>fn:namespace-uri</head><glist><gitem><label>Summary</label><def><p>Returns the namespace URI part of the name of <code>$arg</code>, as an
               <code>xs:anyURI</code> value.</p></def></gitem><gitem><label>Signatures</label><def><example role="signature"><proto name="namespace-uri" return-type="xs:anyURI" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"/></example><example role="signature"><proto name="namespace-uri" return-type="xs:anyURI" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg" type="node()?"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>The zero-argument form of this function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-dependent">context-dependent</termref>,  and <termref def="dt-focus-dependent">focus-dependent</termref>. </p><p>The one-argument form of this function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>If the argument is omitted, it defaults to the context node (<code>.</code>). The
            behavior of the function if the argument is omitted is exactly the same as if the
            context item had been passed as the argument.</p><p>If the node identified by <code>$arg</code> is neither an element nor an attribute node,
            or if it is an element or attribute node whose expanded-QName (as determined by the
               <code>dm:node-name</code> accessor in the <xspecref spec="DM31" ref="dm-node-name"/>)
            is in no namespace, then the function returns the zero-length <code>xs:anyURI</code>
            value.</p><p>Otherwise, the result will be the namespace URI part of the expanded-QName of the node
            identified by <code>$arg</code>, as determined by the <code>dm:node-name</code> accessor
            defined in <xspecref spec="DM31" ref="dm-node-name"/>), returned as an
               <code>xs:anyURI</code> value.</p></def></gitem><gitem><label>Error Conditions</label><def><p>The following errors may be raised when <code>$arg</code> is omitted:</p><ul><li>
               <p>If the context item is <xtermref ref="dt-absent" spec="DM31">absent</xtermref>,
                  dynamic error <xerrorref spec="XP" class="DY" code="0002" type="dynamic"/></p>
            </li><li>
               <p>If the context item is not a node, type error <xerrorref spec="XP" class="TY" code="0004" type="type"/>.</p>
            </li></ul></def></gitem></glist></div2><div2 id="func-lang"><head>fn:lang</head><glist><gitem><label>Summary</label><def><p>This function tests whether the language of <code>$node</code>, or the context item if
            the second argument is omitted, as specified by <code>xml:lang</code> attributes is the
            same as, or is a sublanguage of, the language specified by <code>$testlang</code>.</p></def></gitem><gitem><label>Signatures</label><def><example role="signature"><proto name="lang" return-type="xs:boolean" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="testlang" type="xs:string?"/></proto></example><example role="signature"><proto name="lang" return-type="xs:boolean" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="testlang" type="xs:string?"/><arg name="node" type="node()"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>The one-argument form of this function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-dependent">context-dependent</termref>,  and <termref def="dt-focus-dependent">focus-dependent</termref>. </p><p>The two-argument form of this function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>The behavior of the function if the second argument is omitted is exactly the same as if
            the context item (<code>.</code>) had been passed as the second argument.</p><p>The language of the argument <code>$node</code>, or the context item if the second
            argument is omitted, is determined by the value of the <code>xml:lang</code> attribute
            on the node, or, if the node has no such attribute, by the value of the
               <code>xml:lang</code> attribute on the nearest ancestor of the node that has an
               <code>xml:lang</code> attribute. If there is no such ancestor, then the function
            returns <code>false</code>. </p><p>If <code>$testlang</code> is the empty sequence it is interpreted as the zero-length
            string.</p><p>The relevant <code>xml:lang</code> attribute is determined by the value of the XPath
            expression:</p><eg xml:space="preserve">(ancestor-or-self::*/@xml:lang)[last()]</eg><p>If this expression returns an empty sequence, the function returns <code>false</code>. </p><p>Otherwise, the function returns <code>true</code> if and only if, based on a caseless
            default match as specified in section 3.13 of <bibref ref="Unicode"/>, either:</p><olist><item><p>
                  <code>$testlang</code> is equal to the string-value of the relevant
                     <code>xml:lang</code> attribute, or</p></item><item><p>
                  <code>$testlang</code> is equal to some substring of the string-value of the
                  relevant <code>xml:lang</code> attribute that starts at the start of the
                  string-value and ends immediately before a hyphen, "-" (the character "-" is
                  HYPHEN-MINUS, #x002D).</p></item></olist></def></gitem><gitem><label>Error Conditions</label><def><p>The following errors may be raised when <code>$arg</code> is omitted:</p><ul><li>
               <p>If the context item is <xtermref ref="dt-absent" spec="DM31">absent</xtermref>,
                  dynamic error <xerrorref spec="XP" class="DY" code="0002" type="dynamic"/></p>
            </li><li>
               <p>If the context item is not a node, type error <xerrorref spec="XP" class="TY" code="0004" type="type"/>.</p>
            </li></ul></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>fn:lang("en")</code> would return <code>true</code> if the
               context node were any of the following four elements:</p><ulist><item><p>
                     <code>&lt;para xml:lang="en"/&gt;</code>
                  </p></item><item><p>
                     <code>&lt;div xml:lang="en"&gt;&lt;para&gt;And now, and
                        forever!&lt;/para&gt;&lt;/div&gt;</code>
                  </p></item><item><p>
                     <code>&lt;para xml:lang="EN"/&gt;</code>
                  </p></item><item><p>
                     <code>&lt;para xml:lang="en-us"/&gt;</code>
                  </p></item></ulist><p>The expression <code>fn:lang("fr")</code> would return <code>false</code> if the
               context node were <code>&lt;para xml:lang="EN"/&gt;</code>
            </p></def></gitem></glist></div2><div2 id="func-root"><head>fn:root</head><glist><gitem><label>Summary</label><def><p>Returns the root of the tree to which <code>$arg</code> belongs. This will usually, but
            not necessarily, be a document node.</p></def></gitem><gitem><label>Signatures</label><def><example role="signature"><proto name="root" return-type="node()" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"/></example><example role="signature"><proto name="root" return-type="node()?" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg" type="node()?"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>The zero-argument form of this function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-dependent">context-dependent</termref>,  and <termref def="dt-focus-dependent">focus-dependent</termref>. </p><p>The one-argument form of this function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>If the function is called without an argument, the context item (<code>.</code>) is used
            as the default argument. The behavior of the function if the argument is omitted is
            exactly the same as if the context item had been passed as the argument.</p><p>The function returns the value of the expression
               <code>($arg/ancestor-or-self::node())[1]</code>.</p></def></gitem><gitem><label>Error Conditions</label><def><p>The following errors may be raised when <code>$arg</code> is omitted:</p><ul><li>
               <p>If the context item is <xtermref ref="dt-absent" spec="DM31">absent</xtermref>,
                  dynamic error <xerrorref spec="XP" class="DY" code="0002" type="dynamic"/></p>
            </li><li>
               <p>If the context item is not a node, type error <xerrorref spec="XP" class="TY" code="0004" type="type"/>.</p>
            </li></ul></def></gitem><gitem><label>Examples</label><def role="example"><p>These examples use some variables which could be defined in <bibref ref="xquery-31"/>
               as:</p><eg xml:space="preserve">let $i := &lt;tool&gt;wrench&lt;/tool&gt;
let $o := &lt;order&gt; {$i} &lt;quantity&gt;5&lt;/quantity&gt; &lt;/order&gt;
let $odoc := document {$o}
let $newi := $o/tool</eg><p>Or they could be defined in <bibref ref="xslt-30"/> as:</p><eg xml:space="preserve">&lt;xsl:variable name="i" as="element()"&gt;
  &lt;tool&gt;wrench&lt;/tool&gt;
&lt;/xsl:variable&gt;

&lt;xsl:variable name="o" as="element()"&gt;
  &lt;order&gt;
    &lt;xsl:copy-of select="$i"/&gt;
    &lt;quantity&gt;5&lt;/quantity&gt;
  &lt;/order&gt;
&lt;/xsl:variable&gt;

&lt;xsl:variable name="odoc"&gt;
  &lt;xsl:copy-of select="$o"/&gt;
&lt;/xsl:variable&gt;

&lt;xsl:variable name="newi" select="$o/tool"/&gt;</eg><p><code>fn:root($i)</code> returns the element node <code>$i</code>
            </p><p><code>fn:root($o/quantity)</code> returns the element node <code>$o</code>
            </p><p><code>fn:root($odoc//quantity)</code> returns the document node <code>$odoc</code>
            </p><p><code>fn:root($newi)</code> returns the element node <code>$o</code>
            </p><p>The final three examples could be made type-safe by wrapping their operands with
                  <code>fn:exactly-one()</code>.</p></def></gitem></glist></div2><div2 id="func-path"><head>fn:path</head><glist><gitem><label>Summary</label><def><p>Returns a path expression that can be used to select the supplied node relative to the
            root of its containing document.</p></def></gitem><gitem><label>Signatures</label><def><example role="signature"><proto name="path" return-type="xs:string?" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"/></example><example role="signature"><proto name="path" return-type="xs:string?" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg" type="node()?"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>The one-argument form of this function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-dependent">context-dependent</termref>,  and <termref def="dt-focus-dependent">focus-dependent</termref>. </p><p>The two-argument form of this function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>The behavior of the function if the argument is omitted is exactly the same as if the
            context item (<code>.</code>) had been passed as the argument.</p><p>If <code>$arg</code> is the empty sequence, the function returns the empty sequence.</p><p>If <code>$arg</code> is a document node, the function returns the string
               <code>"/"</code>.</p><p>Otherwise, the function returns a string that consists of a sequence of steps, one
            for each ancestor-or-self of <code>$arg</code> other than the root node. This string is
            prefixed by <code>"Q{http://www.w3.org/2005/xpath-functions}root()"</code> if the root
            node is not a document node. Each step consists of the character <code>"/"</code>
            followed by a string whose form depends on the kind of node selected by that step, as
            follows:</p><olist><item><p>For an element node,
                        <code>Q{<emph>uri</emph>}<emph>local</emph>[<emph>position</emph>]</code>,
                  where <code><emph>uri</emph></code> is the namespace URI of the node name or the
                  empty string if the node is in no namespace, <code><emph>local</emph></code> is
                  the local part of the node name, and <code><emph>position</emph></code> is an
                  integer representing the position of the selected node among its like-named
                  siblings.</p></item><item><p>For an attribute node:</p><olist><item><p>if the node is in no namespace, <code>@<emph>local</emph></code>, where
                              <code><emph>local</emph></code> is the local part of the node name</p></item><item><p>otherwise, <code>@Q{<emph>uri</emph>}<emph>local</emph></code>, where
                              <code><emph>uri</emph></code> is the namespace URI of the node name,
                        and <code><emph>local</emph></code> is the local part of the node name</p></item></olist></item><item><p>For a text node: <code>text()[<emph>position</emph>]</code> where
                        <code><emph>position</emph></code> is an integer representing the position
                  of the selected node among its text node siblings</p></item><item><p>For a comment node: <code>comment()[<emph>position</emph>]</code> where
                        <code><emph>position</emph></code> is an integer representing the position
                  of the selected node among its comment node siblings</p></item><item><p>For a processing-instruction node:
                        <code>processing-instruction(<emph>local</emph>)[<emph>position</emph>]</code>
                  where <code><emph>local</emph></code> is the name of the processing instruction
                  node and <code><emph>position</emph></code> is an integer representing the
                  position of the selected node among its like-named processing-instruction node
                  siblings</p></item><item><p>For a namespace node:</p><olist><item><p>If the namespace node has a name:
                           <code>namespace::<emph>prefix</emph></code>, where
                              <code><emph>prefix</emph></code> is the local part of the name of the
                        namespace node (which represents the namespace prefix).</p></item><item><p>If the namespace node has no name (that is, it represents the default
                        namespace):
                           <code>namespace::*[Q{http://www.w3.org/2005/xpath-functions}local-name()=""]</code></p></item></olist></item></olist></def></gitem><gitem><label>Error Conditions</label><def><p diff="add" at="D">The following errors may be raised when <code>$arg</code> is omitted:</p><ulist diff="add" at="D"><item><p>If the context item is <xtermref ref="dt-absent" spec="DM31">absent</xtermref>,
                  dynamic error <xerrorref spec="XP" class="DY" code="0002" type="dynamic"/></p></item><item><p>If the context item is not a node, type error <xerrorref spec="XP" class="TY" code="0004" type="type"/>.</p></item></ulist></def></gitem><gitem><label>Examples</label><def role="example"><eg xml:space="preserve">let $e := 
document {            
&lt;p xmlns="http://example.com/one" xml:lang="de" author="Friedrich von Schiller"&gt;
Freude, schöner Götterfunken,&lt;br/&gt;
Tochter aus Elysium,&lt;br/&gt;
Wir betreten feuertrunken,&lt;br/&gt;
Himmlische, dein Heiligtum.&lt;/p&gt;}
         </eg><p>The expression <code>fn:path($e)</code> returns <code>'/'</code>.</p><p>The expression <code>fn:path($e/*:p)</code> returns <code>'/Q{http://example.com/one}p[1]'</code>.</p><p>The expression <code>fn:path($e/*:p/@xml:lang)</code> returns <code>'/Q{http://example.com/one}p[1]/@Q{http://www.w3.org/XML/1998/namespace}lang'</code>.</p><p>The expression <code>fn:path($e/*:p/@author)</code> returns <code>'/Q{http://example.com/one}p[1]/@author'</code>.</p><p>The expression <code>fn:path($e/*:p/*:br[2])</code> returns <code>'/Q{http://example.com/one}p[1]/Q{http://example.com/one}br[2]'</code>.</p><p>The expression <code>fn:path($e//text()[starts-with(normalize-space(),
                  'Tochter')])</code> returns <code>'/Q{http://example.com/one}p[1]/text()[2]'</code>.</p><eg xml:space="preserve">let $emp := 
            &lt;employee xml:id="ID21256"&gt;
               &lt;empnr&gt;E21256&lt;/empnr&gt;
               &lt;first&gt;John&lt;/first&gt;
               &lt;last&gt;Brown&lt;/last&gt;
            &lt;/employee&gt;
         </eg><p>The expression <code>fn:path($emp)</code> returns <code>'Q{http://www.w3.org/2005/xpath-functions}root()'</code>.</p><p>The expression <code>fn:path($emp/@xml:id)</code> returns <code>'Q{http://www.w3.org/2005/xpath-functions}root()/@Q{http://www.w3.org/XML/1998/namespace}id'</code>.</p><p>The expression <code>fn:path($emp/empnr)</code> returns <code>'Q{http://www.w3.org/2005/xpath-functions}root()/Q{}empnr[1]'</code>.</p></def></gitem></glist></div2><div2 id="func-has-children"><head>fn:has-children</head><glist><gitem><label>Summary</label><def><p>Returns true if the supplied node has one or more child nodes (of any kind).</p></def></gitem><gitem><label>Signatures</label><def><example role="signature"><proto name="has-children" return-type="xs:boolean" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"/></example><example role="signature"><proto name="has-children" return-type="xs:boolean" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="node" type="node()?"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>The zero-argument form of this function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-dependent">context-dependent</termref>,  and <termref def="dt-focus-dependent">focus-dependent</termref>. </p><p>The one-argument form of this function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>If the argument is omitted, it defaults to the context item (<code>.</code>). The
            behavior of the function if the argument is omitted is exactly the same as if the
            context item had been passed as the argument.</p><p>Provided that the supplied argument <code>$node</code> matches the expected type
               <code>node()?</code>, the result of the function call
               <code>fn:has-children($node)</code> is defined to be the same as the result of the
            expression <code>fn:exists($node/child::node())</code>.</p></def></gitem><gitem><label>Error Conditions</label><def><p>The following errors may be raised when <code>$node</code> is omitted:</p><ul><li>
               <p>If the context item is <xtermref ref="dt-absent" spec="DM31">absent</xtermref>,
                  dynamic error <xerrorref spec="XP" class="DY" code="0002" type="dynamic"/></p>
            </li><li>
               <p>If the context item is not a node, type error <xerrorref spec="XP" class="TY" code="0004" type="type"/>.</p>
            </li></ul></def></gitem><gitem><label>Notes</label><def><p role="note">If <code>$node</code> is an empty sequence the result is false.</p><p role="note">The motivation for this function is to support streamed evaluation. According to the
            streaming rules in <bibref ref="xslt-30"/>, the following construct is not
            streamable:</p><eg role="note" xml:space="preserve">
&lt;xsl:if test="exists(row)"&gt;
  &lt;ul&gt;
    &lt;xsl:for-each select="row"&gt;
       &lt;li&gt;&lt;xsl:value-of select="."/&gt;&lt;/li&gt;
    &lt;/xsl:for-each&gt;
  &lt;/ul&gt;
&lt;/xsl:if&gt;  
</eg><p role="note">This is because it makes two downward selections to read the child <code>row</code>
            elements. The use of <code>fn:has-children</code> in the <code>xsl:if</code> conditional
            is intended to circumvent this restriction.</p><p role="note">Although the function was introduced to support streaming use cases, it has general
            utility as a convenience function.</p></def></gitem></glist></div2><div2 id="func-innermost"><head>fn:innermost</head><glist><gitem><label>Summary</label><def><p>Returns every node within the input sequence that is not an ancestor of another member
            of the input sequence; the nodes are returned in document order with duplicates
            eliminated.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="innermost" return-type="node()*" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="nodes" type="node()*"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>The effect of the function call <code>fn:innermost($nodes)</code> is defined to be
            equivalent to the result of the expression:</p><eg xml:space="preserve">$nodes except $nodes/ancestor::node()</eg><p>That is, the function takes as input a sequence of nodes, and returns every node within
            the sequence that is not an ancestor of another node within the sequence; the nodes are
            returned in document order with duplicates eliminated.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>If the source document contains nested sections represented by <code>div</code>
               elements, the expression <code>innermost(//div)</code> returns those <code>div</code>
               elements that do not contain further <code>div</code> elements.</p></def></gitem></glist></div2><div2 id="func-outermost"><head>fn:outermost</head><glist><gitem><label>Summary</label><def><p>Returns every node within the input sequence that has no ancestor that is itself a
            member of the input sequence; the nodes are returned in document order with duplicates
            eliminated.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="outermost" return-type="node()*" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="nodes" type="node()*"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>The effect of the function call <code>fn:outermost($nodes)</code> is defined to be
            equivalent to the result of the expression:</p><eg xml:space="preserve">$nodes[not(ancestor::node() intersect $nodes)]/.</eg><p>That is, the function takes as input a sequence of nodes, and returns every node within
            the sequence that does not have another node within the sequence as an ancestor; the
            nodes are returned in document order with duplicates eliminated.</p></def></gitem><gitem><label>Notes</label><def><p role="note">The formulation <code>$nodes except $nodes/descendant::node()</code> might appear to be
            simpler, but does not correctly account for attribute nodes, as these are not
            descendants of their parent element.</p><p role="note">The motivation for the function was based on XSLT streaming use cases. There are cases
            where the <bibref ref="xslt-30"/> streaming rules allow the construct
               <code>outermost(//section)</code> but do not allow <code>//section</code>; the
            function can therefore be useful in cases where it is known that sections will not be
            nested, as well as cases where the application actually wishes to process all sections
            except those that are nested within another.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>If the source document contains nested sections represented by <code>div</code>
               elements, the expression <code>outermost(//div)</code> returns those <code>div</code>
               elements that are not contained within further <code>div</code> elements.</p></def></gitem></glist></div2></div1><div1 id="sequence-functions"><head>Functions and operators on sequences</head><p>A <code>sequence</code> is an ordered collection of zero or more <code>items</code>.
                An <code>item</code> is either a node or an atomic value. The terms
                <code>sequence</code> and <code>item</code> are defined formally in <bibref ref="xquery-31"/> and <bibref ref="xpath-31"/>. </p><div2 id="general-seq-funcs"><head>General functions and operators on sequences</head><p>The following functions are defined on sequences. These functions work on any sequence, without performing
            any operations that are sensitive to the individual items in the sequence.</p><table class="index"><thead><tr><th rowspan="1" colspan="1">Function</th><th rowspan="1" colspan="1">Meaning</th></tr></thead><tbody><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:empty</code></td><td rowspan="1" colspan="1">Returns true if the argument is the empty sequence.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:exists</code></td><td rowspan="1" colspan="1">Returns true if the argument is a non-empty sequence.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:head</code></td><td rowspan="1" colspan="1">Returns the first item in a sequence. </td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:tail</code></td><td rowspan="1" colspan="1">Returns all but the first item in a sequence. </td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:insert-before</code></td><td rowspan="1" colspan="1">Returns a sequence constructed by inserting an item or a sequence of items at a given
            position within an existing sequence.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:remove</code></td><td rowspan="1" colspan="1">Returns a new sequence containing all the items of <code>$target</code> except the item
            at position <code>$position</code>.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:reverse</code></td><td rowspan="1" colspan="1">Reverses the order of items in a sequence. </td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:subsequence</code></td><td rowspan="1" colspan="1">Returns the contiguous sequence of items in the value of <code>$sourceSeq</code>
            beginning at the position indicated by the value of <code>$startingLoc</code> and
            continuing for the number of items indicated by the value of <code>$length</code>. </td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:unordered</code></td><td rowspan="1" colspan="1">Returns the items of <code>$sourceSeq</code> in an <termref def="implementation-dependent">implementation-dependent</termref> order.</td></tr></tbody></table><p>As in the previous section, for the illustrative examples below, assume an XQuery
                    or transformation operating on a non-empty Purchase Order document containing a
                    number of line-item elements. The variable <code>$seq</code> is bound to the
                    sequence of line-item nodes in document order. The variables
                    <code>$item1</code>, <code>$item2</code>, etc. are bound to separate, individual
                    line-item nodes in the sequence.</p><div3 id="func-empty"><head>fn:empty</head><glist><gitem><label>Summary</label><def><p>Returns true if the argument is the empty sequence.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="empty" return-type="xs:boolean" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg" type="item()*"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>If the value of <code>$arg</code> is the empty sequence, the function returns
               <code>true</code>; otherwise, the function returns <code>false</code>. </p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>fn:empty((1,2,3)[10])</code> returns <code>true()</code>.</p><p>The expression <code>fn:empty(fn:remove(("hello", "world"), 1))</code> returns <code>false()</code>.</p><p>The expression <code>fn:empty([])</code> returns <code>false()</code>.</p><p>The expression <code>fn:empty(map{})</code> returns <code>false()</code>.</p><p>The expression <code>fn:empty("")</code> returns <code>false()</code>.</p><p>Assuming <code>$in</code> is an element with no children:</p><eg xml:space="preserve">
               let $break := &lt;br/&gt;
               return fn:empty($break)
            </eg><p>The result is <code>false()</code>.</p></def></gitem></glist></div3><div3 id="func-exists"><head>fn:exists</head><glist><gitem><label>Summary</label><def><p>Returns true if the argument is a non-empty sequence.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="exists" return-type="xs:boolean" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg" type="item()*"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>If the value of <code>$arg</code> is a non-empty sequence, the function returns
               <code>true</code>; otherwise, the function returns <code>false</code>. </p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>fn:exists(fn:remove(("hello"), 1))</code> returns <code>false()</code>.</p><p>The expression <code>fn:exists(fn:remove(("hello", "world"), 1))</code> returns <code>true()</code>.</p><p>The expression <code>fn:exists([])</code> returns <code>true()</code>.</p><p>The expression <code>fn:exists(map{})</code> returns <code>true()</code>.</p><p>The expression <code>fn:exists("")</code> returns <code>true()</code>.</p><p>Assuming <code>$in</code> is an element with no children:</p><eg xml:space="preserve">
               let $break := <br/>
               return fn:exists($break)
            </eg><p>The result is <code>true()</code>.</p></def></gitem></glist></div3><div3 id="func-head"><head>fn:head</head><glist><gitem><label>Summary</label><def><p>Returns the first item in a sequence. </p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="head" return-type="item()?" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg" type="item()*"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>The function returns the value of the expression <code>$arg[1]</code></p></def></gitem><gitem><label>Notes</label><def><p role="note">If <code>$arg</code> is the empty sequence, the empty sequence is returned. Otherwise
            the first item in the sequence is returned.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>fn:head(1 to 5)</code> returns <code>1</code>.</p><p>The expression <code>fn:head(("a", "b", "c"))</code> returns <code>"a"</code>.</p><p>The expression <code>fn:head(())</code> returns <code>()</code>.</p><p>The expression <code>fn:head([1,2,3])</code> returns <code>[1,2,3]</code>.</p></def></gitem></glist></div3><div3 id="func-tail"><head>fn:tail</head><glist><gitem><label>Summary</label><def><p>Returns all but the first item in a sequence. </p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="tail" return-type="item()*" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg" type="item()*"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>The function returns the value of the expression <code>subsequence($arg, 2)</code></p></def></gitem><gitem><label>Notes</label><def><p role="note">If <code>$arg</code> is the empty sequence, or a sequence containing a single item, then
            the empty sequence is returned. </p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>fn:tail(1 to 5)</code> returns <code>(2, 3, 4, 5)</code>.</p><p>The expression <code>fn:tail(("a", "b", "c"))</code> returns <code>("b", "c")</code>.</p><p>The expression <code>fn:tail("a")</code> returns <code>()</code>.</p><p>The expression <code>fn:tail(())</code> returns <code>()</code>.</p><p>The expression <code>fn:tail([1,2,3])</code> returns <code>()</code>.</p></def></gitem></glist></div3><div3 id="func-insert-before"><head>fn:insert-before</head><glist><gitem><label>Summary</label><def><p>Returns a sequence constructed by inserting an item or a sequence of items at a given
            position within an existing sequence.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="insert-before" return-type="item()*" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="target" type="item()*"/><arg name="position" type="xs:integer"/><arg name="inserts" type="item()*"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>The value returned by the function consists of all items of <code>$target</code> whose
            index is less than <code>$position</code>, followed by all items of
               <code>$inserts</code>, followed by the remaining elements of <code>$target</code>, in
            that order. </p></def></gitem><gitem><label>Notes</label><def><p role="note">If <code>$target</code> is the empty sequence, <code>$inserts</code> is returned. If
               <code>$inserts</code> is the empty sequence, <code>$target</code> is returned.</p><p role="note">If <code>$position</code> is less than one (1), the first position, the effective value
            of <code>$position</code> is one (1). If <code>$position</code> is greater than the
            number of items in <code>$target</code>, then the effective value of
               <code>$position</code> is equal to the number of items in <code>$target</code> plus
            1. </p><p role="note">The value of <code>$target</code> is not affected by the sequence construction.</p></def></gitem><gitem><label>Examples</label><def role="example"><eg xml:space="preserve">let $abc := ("a", "b", "c")</eg><p>The expression <code>fn:insert-before($abc, 0, "z")</code> returns <code>("z", "a", "b", "c")</code>.</p><p>The expression <code>fn:insert-before($abc, 1, "z")</code> returns <code>("z", "a", "b", "c")</code>.</p><p>The expression <code>fn:insert-before($abc, 2, "z")</code> returns <code>("a", "z", "b", "c")</code>.</p><p>The expression <code>fn:insert-before($abc, 3, "z")</code> returns <code>("a", "b", "z", "c")</code>.</p><p>The expression <code>fn:insert-before($abc, 4, "z")</code> returns <code>("a", "b", "c", "z")</code>.</p></def></gitem></glist></div3><div3 id="func-remove"><head>fn:remove</head><glist><gitem><label>Summary</label><def><p>Returns a new sequence containing all the items of <code>$target</code> except the item
            at position <code>$position</code>.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="remove" return-type="item()*" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="target" type="item()*"/><arg name="position" type="xs:integer"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>The function returns a sequence consisting of all items of <code>$target</code> whose
            index is less than <code>$position</code>, followed by all items of <code>$target</code>
            whose index is greater than <code>$position</code>. </p></def></gitem><gitem><label>Notes</label><def><p role="note">If <code>$position</code> is less than 1 or greater than the number of items in
               <code>$target</code>, <code>$target</code> is returned.</p><p role="note">If <code>$target</code> is the empty sequence, the empty sequence is returned.</p></def></gitem><gitem><label>Examples</label><def role="example"><eg xml:space="preserve">let $abc := ("a", "b", "c")</eg><p>The expression <code>fn:remove($abc, 0)</code> returns <code>("a", "b", "c")</code>.</p><p>The expression <code>fn:remove($abc, 1)</code> returns <code>("b", "c")</code>.</p><p>The expression <code>fn:remove($abc, 6)</code> returns <code>("a", "b", "c")</code>.</p><p>The expression <code>fn:remove((), 3)</code> returns <code>()</code>.</p></def></gitem></glist></div3><div3 id="func-reverse"><head>fn:reverse</head><glist><gitem><label>Summary</label><def><p>Reverses the order of items in a sequence. </p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="reverse" return-type="item()*" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg" type="item()*"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>The function returns a sequence containing the items in <code>$arg</code> in reverse
            order.</p></def></gitem><gitem><label>Notes</label><def><p role="note">If <code>$arg</code> is the empty sequence, the empty sequence is returned. </p></def></gitem><gitem><label>Examples</label><def role="example"><eg xml:space="preserve">let $abc := ("a", "b", "c")</eg><p>The expression <code>fn:reverse($abc)</code> returns <code>("c", "b", "a")</code>.</p><p>The expression <code>fn:reverse(("hello"))</code> returns <code>("hello")</code>.</p><p>The expression <code>fn:reverse(())</code> returns <code>()</code>.</p><p>The expression <code>fn:reverse([1,2,3])</code> returns <code>[1,2,3]</code>. <emph>(The input is a sequence containing a single item (the array)).</emph></p><p>The expression <code>fn:reverse(([1,2,3],[4,5,6]))</code> returns <code>([4,5,6],[1,2,3])</code>.</p></def></gitem></glist></div3><div3 id="func-subsequence"><head>fn:subsequence</head><glist><gitem><label>Summary</label><def><p>Returns the contiguous sequence of items in the value of <code>$sourceSeq</code>
            beginning at the position indicated by the value of <code>$startingLoc</code> and
            continuing for the number of items indicated by the value of <code>$length</code>. </p></def></gitem><gitem><label>Signatures</label><def><example role="signature"><proto name="subsequence" return-type="item()*" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="sourceSeq" type="item()*"/><arg name="startingLoc" type="xs:double"/></proto></example><example role="signature"><proto name="subsequence" return-type="item()*" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="sourceSeq" type="item()*"/><arg name="startingLoc" type="xs:double"/><arg name="length" type="xs:double"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>In the two-argument case, returns:</p><eg xml:space="preserve">$sourceSeq[fn:round($startingLoc) le position()]</eg><p>In the three-argument case, returns:</p><eg xml:space="preserve">$sourceSeq[fn:round($startingLoc) le position() 
         and position() lt fn:round($startingLoc) + fn:round($length)]</eg></def></gitem><gitem><label>Notes</label><def><p role="note">The first item of a sequence is located at position 1, not position 0.</p><p role="note">If <code>$sourceSeq</code> is the empty sequence, the empty sequence is returned.</p><p role="note">In the two-argument case, the function returns a sequence comprising those items of <code>$sourceSeq</code> whose index position (counting from one) 
            is greater than or equal to the value of <code>$startingLoc</code> (rounded to an integer). No error occurs if <code>$startingLoc</code> is 
            zero or negative.</p><p role="note">In the three-argument case, The function returns a sequence comprising those items of <code>$sourceSeq</code> whose index position (counting from one) 
            is greater than or equal to the value of <code>$startingLoc</code> (rounded to an integer), and 
            less than the sum of <code>$startingLoc</code> and <code>$length</code> (both rounded to integers). No error occurs if <code>$startingLoc</code> is 
            zero or negative, or if <code>$startingLoc</code> plus <code>$length</code> exceeds the number of items in the sequence, or if 
            <code>$length</code> is negative.</p><p role="note">As a consequence of the general rules, if <code>$startingLoc</code> is
               <code>-INF</code> and <code>$length</code> is <code>+INF</code>, then
               <code>fn:round($startingLoc) + fn:round($length)</code> is <code>NaN</code>; since
               <code>position() lt NaN</code> is always false, the result is an empty sequence.</p><p role="note">The reason the function accepts arguments of type <code>xs:double</code> is that many
            computations on untyped data return an <code>xs:double</code> result; and the reason for
            the rounding rules is to compensate for any imprecision in these floating-point
            computations.</p></def></gitem><gitem><label>Examples</label><def role="example"><eg xml:space="preserve">let $seq := ("item1", "item2", "item3", "item4", "item5")</eg><p>The expression <code>fn:subsequence($seq, 4)</code> returns <code>("item4", "item5")</code>.</p><p>The expression <code>fn:subsequence($seq, 3, 2)</code> returns <code>("item3", "item4")</code>.</p></def></gitem></glist></div3><div3 id="func-unordered"><head>fn:unordered</head><glist><gitem><label>Summary</label><def><p>Returns the items of <code>$sourceSeq</code> in an <termref def="implementation-dependent">implementation-dependent</termref> order.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="unordered" return-type="item()*" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="sourceSeq" type="item()*"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-nondeterministic-wrt-ordering">nondeterministic-wrt-ordering</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>The function returns the items of <code>$sourceSeq</code> in an <termref def="implementation-dependent">implementation-dependent</termref> order.</p></def></gitem><gitem><label>Notes</label><def><p role="note">Query optimizers may be able to do a better job if the order of the output sequence is
            not specified. For example, when retrieving prices from a purchase order, if an index
            exists on prices, it may be more efficient to return the prices in index order rather
            than in document order.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>fn:unordered((1, 2, 3, 4, 5))</code> returns some permutation of <code>(1, 2, 3, 4, 5)</code>.</p></def></gitem></glist></div3></div2><div2 id="comparing-sequences"><head>Functions that compare values in sequences</head><p>The functions in this section rely on comparisons between the items in one or more
            sequences.</p><table class="index"><thead><tr><th rowspan="1" colspan="1">Function</th><th rowspan="1" colspan="1">Meaning</th></tr></thead><tbody><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:distinct-values</code></td><td rowspan="1" colspan="1">Returns the values that appear in a sequence, with duplicates eliminated.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:index-of</code></td><td rowspan="1" colspan="1">Returns a sequence of positive integers giving the positions within the sequence
               <code>$seq</code> of items that are equal to <code>$search</code>.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:deep-equal</code></td><td rowspan="1" colspan="1"> This function assesses whether two sequences are deep-equal to each other. To be
            deep-equal, they must contain items that are pairwise deep-equal; and for two items to
            be deep-equal, they must either be atomic values that compare equal, or nodes of the
            same kind, with the same name, whose children are deep-equal<phrase diff="add" at="A">,
               or maps with matching entries, or arrays with matching members.</phrase></td></tr></tbody></table><div3 id="func-distinct-values"><head>fn:distinct-values</head><glist><gitem><label>Summary</label><def><p>Returns the values that appear in a sequence, with duplicates eliminated.</p></def></gitem><gitem><label>Signatures</label><def><example role="signature"><proto name="distinct-values" return-type="xs:anyAtomicType*" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg" type="xs:anyAtomicType*"/></proto></example><example role="signature"><proto name="distinct-values" return-type="xs:anyAtomicType*" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg" type="xs:anyAtomicType*"/><arg name="collation" type="xs:string"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>The one-argument form of this function is <termref def="dt-nondeterministic-wrt-ordering">nondeterministic-wrt-ordering</termref>, <termref def="dt-context-dependent">context-dependent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>.  It depends on 
		collations, and implicit timezone.
	</p><p>The two-argument form of this function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-dependent">context-dependent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>.  It depends on 
		collations, and static base URI, and implicit timezone.
	</p></def></gitem><gitem><label>Rules</label><def><p>The function returns the sequence that results from removing from <code>$arg</code> all
            but one of a set of values that are considered equal to one another. 
            <phrase diff="chg" at="D">Two items <var>$J</var> and <var>$K</var> in the input sequence 
               (after atomization, as required by the function signature)
            are considered equal if <code>fn:deep-equal($J, $K, $coll)</code> is true,
            where <code>$coll</code> is the collation selected according to the rules in <specref ref="choosing-a-collation"/>.</phrase> This collation is used when string comparison is
            required.</p><p>The order in which the sequence of values is returned is <termref def="implementation-dependent">implementation-dependent</termref>.</p><p>Which value of a set of values that compare equal is returned is <termref def="implementation-dependent">implementation-dependent</termref>. </p><p>If the input sequence contains values of different numeric types that differ from each
            other by small amounts, then the eq operator is not transitive, because of rounding
            effects occurring during type promotion. In the situation where the input contains three
            values <code>A</code>, <code>B</code>, and <code>C</code> such that <code>A eq B</code>,
               <code>B eq C</code>, but <code>A ne C</code>, then the number of items in the result
            of the function (as well as the choice of which items are returned) is <termref def="implementation-dependent">implementation-dependent</termref>, subject only to the constraints that (a) no two
            items in the result sequence compare equal to each other, and (b) every input item that
            does not appear in the result sequence compares equal to some item that does appear in
            the result sequence.</p><p>For example, this arises when computing:</p><eg xml:space="preserve">    distinct-values(
            (xs:float('1.0'),
            xs:decimal('1.0000000000100000000001',
            xs:double( '1.00000000001'))</eg><p>because the values of type <code>xs:float</code> and <code>xs:double</code> both compare
            equal to the value of type <code>xs:decimal</code> but not equal to each other. </p></def></gitem><gitem><label>Notes</label><def><p role="note">If <code>$arg</code> is the empty sequence, the function returns the empty sequence.</p><p role="note">Values of type <code>xs:untypedAtomic</code> are compared as if they were of type
            <code>xs:string</code>.</p><p role="note">Values that cannot be compared, because the <code>eq</code> operator is not defined for
            their types, are considered to be distinct.</p><p role="note">For <code>xs:float</code> and <code>xs:double</code> values, positive zero is equal to
            negative zero and, although <code>NaN</code> does not equal itself, if <code>$arg</code>
            contains multiple <code>NaN</code> values a single <code>NaN</code> is returned.</p><p role="note"> If <code>xs:dateTime</code>, <code>xs:date</code> or <code>xs:time</code> values do not
            have a timezone, they are considered to have the implicit timezone provided by the
            dynamic context for the purpose of comparison. Note that <code>xs:dateTime</code>,
            <code>xs:date</code> or <code>xs:time</code> values can compare equal even if their
            timezones are different.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>fn:distinct-values((1, 2.0, 3, 2))</code> returns some permutation of <code>(1, 3, 2.0)</code>. <emph>(The result may include either the <code>xs:integer</code> 2 or the <code>xs:decimal</code> 2.0).</emph></p><p>The expression <code>fn:distinct-values((xs:untypedAtomic("cherry"),
                  xs:untypedAtomic("plum"), xs:untypedAtomic("plum")))</code> returns some permutation of <code>(xs:untypedAtomic("cherry"),
                  xs:untypedAtomic("plum"))</code>.</p></def></gitem></glist></div3><div3 id="func-index-of"><head>fn:index-of</head><glist><gitem><label>Summary</label><def><p>Returns a sequence of positive integers giving the positions within the sequence
               <code>$seq</code> of items that are equal to <code>$search</code>.</p></def></gitem><gitem><label>Signatures</label><def><example role="signature"><proto name="index-of" return-type="xs:integer*" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="seq" type="xs:anyAtomicType*"/><arg name="search" type="xs:anyAtomicType"/></proto></example><example role="signature"><proto name="index-of" return-type="xs:integer*" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="seq" type="xs:anyAtomicType*"/><arg name="search" type="xs:anyAtomicType"/><arg name="collation" type="xs:string"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>The two-argument form of this function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-dependent">context-dependent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>.  It depends on 
		collations, and implicit timezone.
	</p><p>The three-argument form of this function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-dependent">context-dependent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>.  It depends on 
		collations, and static base URI, and implicit timezone.
	</p></def></gitem><gitem><label>Rules</label><def><p>The function returns a sequence of positive integers giving the positions within the
            sequence <code>$seq</code> of items that are equal to <code>$search</code>.</p><p>The collation used by this function is determined according to the rules in <specref ref="choosing-a-collation"/>. This collation is used when string comparison is
            required.</p><p>The items in the sequence <code>$seq</code> are compared with <code>$search</code> under
            the rules for the <code>eq</code> operator. Values of type <code>xs:untypedAtomic</code>
            are compared as if they were of type <code>xs:string</code>. Values that cannot be
            compared, because the <code>eq</code> operator is not defined for their types, are
            considered to be distinct. If an item compares equal, then the position of that item in
            the sequence <code>$seq</code> is included in the result.</p><p>The first item in a sequence is at position 1, not position 0.</p><p>The result sequence is in ascending numeric order.</p></def></gitem><gitem><label>Notes</label><def><p role="note">If the value of <code>$seq</code> is the empty sequence, or if no item in
               <code>$seq</code> matches <code>$search</code>, then the function returns the empty
            sequence.</p><p role="note">No error occurs if non-comparable values are encountered. So when comparing two atomic
            values, the effective boolean value of <code>fn:index-of($a, $b)</code> is true if
               <code>$a</code> and <code>$b</code> are equal, false if they are not equal or not
            comparable.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>fn:index-of((10, 20, 30, 40), 35)</code> returns <code>()</code>.</p><p>The expression <code>fn:index-of((10, 20, 30, 30, 20, 10), 20)</code> returns <code>(2, 5)</code>.</p><p>The expression <code>fn:index-of(("a", "sport", "and", "a", "pastime"),
                  "a")</code> returns <code>(1, 4)</code>.</p><p>The expression <code>fn:index-of(current-date(), 23)</code> returns <code>()</code>.</p><p>The expression <code>fn:index-of([1, [5, 6], [6, 7]], 6)</code> returns <code>(3, 4)</code>. <emph>(The array is atomized to a sequence of five integers).</emph></p><p>If <code>@a</code> is an attribute of type <code>xs:NMTOKENS</code> whose string
               value is <code>"red green blue"</code>, and whose typed value is therefore
                  <code>("red", "green", "blue")</code>, then <code>fn:index-of(@a, "blue")</code>
               returns <code>3</code>. This is because the function calling mechanism atomizes the
               attribute node to produce a sequence of three <code>xs:NMTOKEN</code> values.</p></def></gitem></glist></div3><div3 id="func-deep-equal"><head>fn:deep-equal</head><glist><gitem><label>Summary</label><def><p> This function assesses whether two sequences are deep-equal to each other. To be
            deep-equal, they must contain items that are pairwise deep-equal; and for two items to
            be deep-equal, they must either be atomic values that compare equal, or nodes of the
            same kind, with the same name, whose children are deep-equal<phrase diff="add" at="A">,
               or maps with matching entries, or arrays with matching members.</phrase></p></def></gitem><gitem><label>Signatures</label><def><example role="signature"><proto name="deep-equal" return-type="xs:boolean" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="parameter1" type="item()*"/><arg name="parameter2" type="item()*"/></proto></example><example role="signature"><proto name="deep-equal" return-type="xs:boolean" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="parameter1" type="item()*"/><arg name="parameter2" type="item()*"/><arg name="collation" type="xs:string"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>The two-argument form of this function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-dependent">context-dependent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>.  It depends on 
		collations, and implicit timezone.
	</p><p>The three-argument form of this function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-dependent">context-dependent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>.  It depends on 
		collations, and static base URI, and implicit timezone.
	</p></def></gitem><gitem><label>Rules</label><def><p>The <code>$collation</code> argument identifies a collation which is used at all levels
            of recursion when strings are compared (but not when names are compared), according to
            the rules in <specref ref="choosing-a-collation"/>.</p><p>If the two sequences are both empty, the function returns <code>true</code>.</p><p>If the two sequences are of different lengths, the function returns
            <code>false</code>.</p><p>If the two sequences are of the same length, the function returns <code>true</code> if
            and only if every item in the sequence <code>$parameter1</code> is deep-equal to the
            item at the same position in the sequence <code>$parameter2</code>. The rules for
            deciding whether two items are deep-equal follow.</p><p>Call the two items <code>$i1</code> and <code>$i2</code> respectively.</p><p>If <code>$i1</code> and <code>$i2</code> are both atomic values, they are deep-equal if
            and only if <code>($i1 eq $i2)</code> is <code>true</code>, or if both values are
               <code>NaN</code>. If the <code>eq</code> operator is not defined for <code>$i1</code>
            and <code>$i2</code>, the function returns <code>false</code>.</p><p diff="del" at="A"> If one of the pair <code>$i1</code> or <code>$i2</code> is an atomic
            value and the other is not, <phrase diff="add" at="A">or if one is a node and the other
               is not, </phrase> the function returns <code>false</code>.</p><p diff="add" at="A">If <code>$i1</code> and <code>$i2</code> are both <termref def="dt-map">maps</termref>, the result is <code>true</code> if and only if all the
            following conditions apply:</p><olist diff="add" at="A"><item><p>Both maps have the same number of entries.</p></item><item><p>For every entry in the first map, there is an entry in the second map that:</p><olist><item><p>has the <termref def="dt-same-key">same key</termref> (note that the
                        collation is not used when comparing keys), and </p></item><item><p>has the same associated value (compared using the <code>fn:deep-equal</code>
                        function, under the collation supplied in the original call to
                           <code>fn:deep-equal</code>).</p></item></olist></item></olist><p diff="add" at="A">If <code>$i1</code> and <code>$i2</code> are both <termref def="dt-array">arrays</termref>, the result is <code>true</code> if and only if all
            the following conditions apply:</p><olist diff="add" at="A"><item><p>Both arrays have the same number of members (<code>array:size($i1) eq
                     array:size($i2)</code>).</p></item><item><p>Members in the same position of both arrays are deep-equal to each other, under
                  the collation supplied in the original call to <code>fn:deep-equal</code>: that is,
                     <code>every $p in 1 to array:size($i1) satisfies deep-equal($i1($p), $i2($p),
                     $collation)</code></p></item></olist><p>If <code>$i1</code> and <code>$i2</code> are both nodes, they are compared as described
            below:</p><olist><item><p>If the two nodes are of different kinds, the result is <code>false</code>.</p></item><item><p>If the two nodes are both document nodes then they are deep-equal if and only if
                  the sequence <code>$i1/(*|text())</code> is deep-equal to the sequence
                     <code>$i2/(*|text())</code>.</p></item><item><p> If the two nodes are both element nodes then they are deep-equal if and only if
                  all of the following conditions are satisfied:</p><olist><item><p>The two nodes have the same name, that is <code>(node-name($i1) eq
                           node-name($i2))</code>.</p></item><item><p>Either both nodes are annotated as having simple content or both nodes
                        are annotated as having complex content. For this purpose "simple content"
                        means either a simple type or a complex type with simple content; "complex
                        content" means a complex type whose variety is mixed, element-only, or
                        empty.</p><note><p>It is a consequence of this rule that validating a document <var>D</var>
                           against a schema will usually (but not necessarily) result in a document
                           that is not deep-equal to <var>D</var>. The exception is when the schema
                           allows all elements to have mixed content.</p></note></item><item><p>The two nodes have the same number of attributes, and for every attribute
                           <code>$a1</code> in <code>$i1/@*</code> there exists an attribute
                           <code>$a2</code> in <code>$i2/@*</code> such that <code>$a1</code> and
                           <code>$a2</code> are deep-equal.</p></item><item><p> One of the following conditions holds:</p><ulist><item><p>Both element nodes are annotated as having simple content (as defined
                              in 3(b) above), and the typed value of <code>$i1</code> is deep-equal
                              to the typed value of <code>$i2</code>.</p></item><item><p>Both element nodes have a type annotation that is a complex type with
                              variety element-only, and the sequence <code>$i1/*</code> is
                              deep-equal to the sequence <code>$i2/*</code>.</p></item><item><p>Both element nodes have a type annotation that is a complex type with
                              variety mixed, and the sequence <code>$i1/(*|text())</code> is
                              deep-equal to the sequence <code>$i2/(*|text())</code>.</p></item><item><p>Both element nodes have a type annotation that is a complex type with
                              variety empty.</p></item></ulist></item></olist></item><item><p>If the two nodes are both attribute nodes then they are deep-equal if and only if
                  both the following conditions are satisfied:</p><olist><item><p>The two nodes have the same name, that is <code>(node-name($i1) eq
                           node-name($i2))</code>.</p></item><item><p>The typed value of <code>$i1</code> is deep-equal to the typed value of
                           <code>$i2</code>.</p></item></olist></item><item><p>If the two nodes are both processing instruction nodes, then they are deep-equal
                  if and only if both the following conditions are satisfied:</p><olist><item><p>The two nodes have the same name, that is <code>(node-name($i1) eq
                           node-name($i2))</code>.</p></item><item><p>The string value of <code>$i1</code> is equal to the string value of
                           <code>$i2</code>.</p></item></olist></item><item><p> If the two nodes are both namespace nodes, then they are deep-equal if and only
                  if both the following conditions are satisfied:</p><olist><item><p>The two nodes either have the same name or are both nameless, that is
                           <code>fn:deep-equal(node-name($i1), node-name($i2))</code>.</p></item><item><p>The string value of <code>$i1</code> is equal to the string value of
                           <code>$i2</code> when compared using the Unicode codepoint collation.</p></item></olist></item><item><p>If the two nodes are both text nodes or comment nodes, then they are deep-equal if
                  and only if their string-values are equal.</p></item></olist><p diff="add" at="A">In all other cases the result is false.</p></def></gitem><gitem><label>Error Conditions</label><def><p>A type error is raised <errorref class="TY" code="0015" type="type"/> if either input
            sequence contains a function item <phrase diff="add" at="A">that is not a map or
               array</phrase>. </p></def></gitem><gitem><label>Notes</label><def><p role="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 the values returned by the <code>is-id</code> and
               <code>is-idrefs</code> accessors (see <xspecref spec="DM31" ref="dm-is-id"/> and
               <xspecref spec="DM31" ref="dm-is-idrefs"/>). The order of children is significant,
            but the order of attributes is insignificant. </p><p role="note">The contents of comments and processing instructions are significant only if these nodes
            appear directly as items in the two sequences being compared. The content of a comment
            or processing instruction that appears as a descendant of an item in one of the
            sequences being compared does not affect the result. However, the presence of a comment
            or processing instruction, if it causes a text node to be split into two text nodes, may
            affect the result.</p><p role="note">Comparing items of different kind (for example, comparing an atomic
            value to a node, or a map to an array, or an integer to an <code>xs:date</code>) returns false, it does not return an error. So
            the result of <code>fn:deep-equal(1, current-dateTime())</code> is <code>false</code>.</p><p role="note">Comparing a function (other than a map or array) to any other value raises a type error.</p></def></gitem><gitem><label>Examples</label><def role="example"><eg xml:space="preserve">let $at := &lt;attendees&gt; &lt;name last='Parker'
            first='Peter'/&gt; &lt;name last='Barker' first='Bob'/&gt; &lt;name last='Parker'
            first='Peter'/&gt; &lt;/attendees&gt;</eg><p>The expression <code>fn:deep-equal($at, $at/*)</code> returns <code>false()</code>.</p><p>The expression <code>fn:deep-equal($at/name[1], $at/name[2])</code> returns <code>false()</code>.</p><p>The expression <code>fn:deep-equal($at/name[1], $at/name[3])</code> returns <code>true()</code>.</p><p>The expression <code>fn:deep-equal($at/name[1], 'Peter Parker')</code> returns <code>false()</code>.</p><p>The expression <code>fn:deep-equal(map{1:'a', 2:'b'}, map{2:'b', 1:'a'})</code> returns <code>true()</code>.</p><p>The expression <code>fn:deep-equal([1, 2, 3], [1, 2, 3])</code> returns <code>true()</code>.</p><p>The expression <code>fn:deep-equal((1, 2, 3), [1, 2, 3])</code> returns <code>false()</code>.</p></def></gitem></glist></div3></div2><div2 id="cardinality-functions"><head>Functions that test the cardinality of sequences</head><p>The following functions test the cardinality of their sequence arguments.</p><table class="index"><thead><tr><th rowspan="1" colspan="1">Function</th><th rowspan="1" colspan="1">Meaning</th></tr></thead><tbody><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:zero-or-one</code></td><td rowspan="1" colspan="1">Returns <code>$arg</code> if it contains zero or one items. Otherwise, raises an
            error.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:one-or-more</code></td><td rowspan="1" colspan="1">Returns <code>$arg</code> if it contains one or more items. Otherwise, raises an error.
         </td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:exactly-one</code></td><td rowspan="1" colspan="1">Returns <code>$arg</code> if it contains exactly one item. Otherwise, raises an error.
         </td></tr></tbody></table><p>The functions <code>fn:zero-or-one</code>, <code>fn:one-or-more</code>, and
                    <code>fn:exactly-one</code> defined in this section, check that the cardinality
                    of a sequence is in the expected range. They are particularly useful with regard
                    to static typing. For example, the function call <code>fn:remove($seq, fn:index-of($seq2, 'abc'))</code>
                    requires the result of the call on <code>fn:index-of</code> to be a singleton integer, 
                    but the static type system cannot infer this; writing the expression as 
                    <code>fn:remove($seq, fn:exactly-one(fn:index-of($seq2, 'abc')))</code> 
                    will provide a suitable static type at query analysis time, and ensures that the length of the sequence is
                    correct with a dynamic check at query execution time.</p><p>The type signatures for these functions deliberately declare the argument type as
                    <code>item()*</code>, permitting a sequence of any length. A more restrictive
                    signature would defeat the purpose of the function, which is to defer
                    cardinality checking until query execution time.</p><div3 id="func-zero-or-one"><head>fn:zero-or-one</head><glist><gitem><label>Summary</label><def><p>Returns <code>$arg</code> if it contains zero or one items. Otherwise, raises an
            error.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="zero-or-one" return-type="item()?" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg" type="item()*"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>Except in error cases, the function returns <code>$arg</code> unchanged.</p></def></gitem><gitem><label>Error Conditions</label><def><p>A dynamic error is raised <errorref class="RG" code="0003"/> if <code>$arg</code>
            contains more than one item.</p></def></gitem></glist></div3><div3 id="func-one-or-more"><head>fn:one-or-more</head><glist><gitem><label>Summary</label><def><p>Returns <code>$arg</code> if it contains one or more items. Otherwise, raises an error.
         </p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="one-or-more" return-type="item()+" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg" type="item()*"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>Except in error cases, the function returns <code>$arg</code> unchanged.</p></def></gitem><gitem><label>Error Conditions</label><def><p>A dynamic error is raised <errorref class="RG" code="0004"/> if <code>$arg</code> is an
            empty sequence.</p></def></gitem></glist></div3><div3 id="func-exactly-one"><head>fn:exactly-one</head><glist><gitem><label>Summary</label><def><p>Returns <code>$arg</code> if it contains exactly one item. Otherwise, raises an error.
         </p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="exactly-one" return-type="item()" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg" type="item()*"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>Except in error cases, the function returns <code>$arg</code> unchanged.</p></def></gitem><gitem><label>Error Conditions</label><def><p>A dynamic error is raised <errorref class="RG" code="0005"/> if <code>$arg</code> is an
            empty sequence or a sequence containing more than one item.</p></def></gitem></glist></div3></div2><div2 id="aggregate-functions"><head>Aggregate functions</head><p>Aggregate functions take a sequence as argument and return a single value
                    computed from values in the sequence. Except for <code>fn:count</code>, the
                    sequence must consist of values of a single type or one if its subtypes, or they
                    must be numeric. <code>xs:untypedAtomic</code> values are permitted in the
                    input sequence and handled by special conversion rules. The type of the items in
                    the sequence must also support certain operations.</p><table class="index"><thead><tr><th rowspan="1" colspan="1">Function</th><th rowspan="1" colspan="1">Meaning</th></tr></thead><tbody><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:count</code></td><td rowspan="1" colspan="1">Returns the number of items in a sequence.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:avg</code></td><td rowspan="1" colspan="1">Returns the average of the values in the input sequence <code>$arg</code>, that is, the
            sum of the values divided by the number of values.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:max</code></td><td rowspan="1" colspan="1">Returns a value that is equal to the highest value appearing in the input sequence.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:min</code></td><td rowspan="1" colspan="1">Returns a value that is equal to the lowest value appearing in the input sequence.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:sum</code></td><td rowspan="1" colspan="1">Returns a value obtained by adding together the values in <code>$arg</code>.</td></tr></tbody></table><div3 id="func-count"><head>fn:count</head><glist><gitem><label>Summary</label><def><p>Returns the number of items in a sequence.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="count" return-type="xs:integer" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg" type="item()*"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>The function returns the number of items in the value of <code>$arg</code>.</p></def></gitem><gitem><label>Notes</label><def><p role="note">Returns 0 if <code>$arg</code> is the empty sequence.</p></def></gitem><gitem><label>Examples</label><def role="example"><eg xml:space="preserve">let $seq1 := ($item1, $item2)</eg><eg xml:space="preserve">let $seq2 := (98.5, 98.3, 98.9)</eg><eg xml:space="preserve">let $seq3 := ()</eg><p>The expression <code>fn:count($seq1)</code> returns <code>2</code>.</p><p>The expression <code>fn:count($seq3)</code> returns <code>0</code>.</p><p>The expression <code>fn:count($seq2)</code> returns <code>3</code>.</p><p>The expression <code>fn:count($seq2[. &gt; 100])</code> returns <code>0</code>.</p><p>The expression <code>fn:count([])</code> returns <code>1</code>.</p><p>The expression <code>fn:count([1,2,3])</code> returns <code>1</code>.</p></def></gitem></glist></div3><div3 id="func-avg"><head>fn:avg</head><glist><gitem><label>Summary</label><def><p>Returns the average of the values in the input sequence <code>$arg</code>, that is, the
            sum of the values divided by the number of values.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="avg" return-type="xs:anyAtomicType?" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg" type="xs:anyAtomicType*"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>If <code>$arg</code> is the empty sequence, the empty sequence is returned.</p><p>If <code>$arg</code> contains values of type <code>xs:untypedAtomic</code> they are cast
            to <code>xs:double</code>. </p><p>Duration values must either all be <code>xs:yearMonthDuration</code> values or must all
            be <code>xs:dayTimeDuration</code> values. For numeric values, the numeric promotion
            rules defined in <specref ref="op.numeric"/> are used to promote all values to a single
            common type. After these operations, <code>$arg</code> must satisfy the following condition:</p><p>There must be a type <var>T</var> such that:</p><olist><item>every item in <code>$arg</code> is an instance of <var>T</var>.</item><item><var>T</var> is one of <code>xs:double</code>, <code>xs:float</code>,<code>xs:decimal</code>, <code>xs:yearMonthDuration</code>, or<code>xs:dayTimeDuration</code>.</item></olist><p>The function returns the average of the values as <code>sum($arg) div
            count($arg)</code>; but the implementation may use an otherwise equivalent algorithm
            that avoids arithmetic overflow.</p></def></gitem><gitem><label>Error Conditions</label><def><p>A type error is raised <errorref class="RG" code="0006"/> if the input sequence contains
            items of incompatible types, as described above.</p></def></gitem><gitem><label>Examples</label><def role="example"><eg xml:space="preserve">let $d1 := xs:yearMonthDuration("P20Y")</eg><eg xml:space="preserve">let $d2 := xs:yearMonthDuration("P10M")</eg><eg xml:space="preserve">let $seq3 := (3, 4, 5)</eg><p>The expression <code>fn:avg($seq3)</code> returns <code>4.0</code>. <emph>(The result is of type <code>xs:decimal</code>.)</emph></p><p>The expression <code>fn:avg(($d1, $d2))</code> returns <code>xs:yearMonthDuration("P10Y5M")</code>.</p><p><code>fn:avg(($d1, $seq3))</code> raises a type error <errorref class="RG" code="0006"/>. </p><p>The expression <code>fn:avg(())</code> returns <code>()</code>.</p><p>The expression <code>fn:avg((xs:float('INF'), xs:float('-INF')))</code> returns <code>xs:float('NaN')</code>.</p><p>The expression <code>fn:avg(($seq3, xs:float('NaN')))</code> returns <code>xs:float('NaN')</code>.</p></def></gitem></glist></div3><div3 id="func-max"><head>fn:max</head><glist><gitem><label>Summary</label><def><p>Returns a value that is equal to the highest value appearing in the input sequence.</p></def></gitem><gitem><label>Signatures</label><def><example role="signature"><proto name="max" return-type="xs:anyAtomicType?" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg" type="xs:anyAtomicType*"/></proto></example><example role="signature"><proto name="max" return-type="xs:anyAtomicType?" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg" type="xs:anyAtomicType*"/><arg name="collation" type="xs:string"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>The zero-argument form of this function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-dependent">context-dependent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>.  It depends on 
		collations, and implicit timezone.
	</p><p>The one-argument form of this function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-dependent">context-dependent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>.  It depends on 
		collations, and static base URI, and implicit timezone.
	</p></def></gitem><gitem><label>Rules</label><def><p>The following conversions are applied to the input sequence <code>$arg</code>, in order:</p><olist><item><p>Values of type <code>xs:untypedAtomic</code> in <code>$arg</code> are cast to
                     <code>xs:double</code>.</p></item><item diff="chg" at="B"><p>If the resulting sequence contains values that are instances of more than one primitive type
                  (meaning the 19 primitive types defined in <bibref ref="xmlschema11-2"/>), then:
               </p><olist><item><p>If each value is an instance of one of the types <code>xs:string</code> or <code>xs:anyURI</code>,
                  then all the values are cast to type <code>xs:string</code>.</p></item><item><p>If each value is an instance of one of the types <code>xs:decimal</code> or <code>xs:float</code>,
                     then all the values are cast to type <code>xs:float</code>.</p></item><item><p>If each value is an instance of one of the types <code>xs:decimal</code>, <code>xs:float</code>,
                     or <code>xs:double</code>, then all the values are cast to type <code>xs:double</code>.</p></item><item><p>Otherwise, a type error is raised <errorref class="RG" code="0006"/>.</p></item></olist><note><p>The primitive type of an <code>xs:integer</code> value for this purpose is <code>xs:decimal</code>.</p></note></item></olist><p>The items in the resulting sequence may be reordered in an arbitrary order. The
            resulting sequence is referred to below as the converted sequence. The function returns
            an item from the converted sequence rather than the input sequence. </p><p>If the converted sequence is empty, the function returns the empty sequence.</p><p>All items in the converted sequence must be derived from a single base type for which
            the <code>le</code> operator is defined. In addition, the values in the sequence must
            have a total order. If date/time values do not have a timezone, they are considered to
            have the implicit timezone provided by the dynamic context for the purpose of
            comparison. Duration values must either all be <code>xs:yearMonthDuration</code> values
            or must all be <code>xs:dayTimeDuration</code> values.</p><p>If the converted sequence contains the value <code>NaN</code>, the value
               <code>NaN</code> is returned 
            <phrase diff="add" at="B">(as an <code>xs:float</code> or <code>xs:double</code> as appropriate)</phrase>.</p><p>If the items in the converted sequence are of type <code>xs:string</code> or types
            derived by restriction from <code>xs:string</code>, then the determination of the item
            with the smallest value is made according to the collation that is used. If the type of
            the items in the converted sequence is not <code>xs:string</code> and
               <code>$collation</code> is specified, the collation is ignored.</p><p>The collation used by this function is determined according to the rules in <specref ref="choosing-a-collation"/>.</p><p>The function returns the result of the expression:</p><eg xml:space="preserve">
   if (every $v in $c satisfies $c[1] ge $v)
   then $c[1] 
   else fn:max(fn:tail($c))</eg><p>evaluated with <code>$collation</code> as the default collation if specified, and with
               <code>$c</code> as the converted sequence.</p></def></gitem><gitem><label>Error Conditions</label><def><p>A type error is raised <errorref class="RG" code="0006"/> if the input sequence contains
            items of incompatible types, as described above.</p></def></gitem><gitem><label>Notes</label><def><p role="note">Because the rules allow the sequence to be reordered, if there are two or more items that are
            "equal highest", the specific item whose value is returned is <termref def="implementation-dependent">implementation-dependent</termref>. This can arise for example if two different strings
            compare equal under the selected collation, or if two different <code>xs:dateTime</code>
            values compare equal despite being in different timezones.</p><p role="note">If the converted sequence contains exactly one value then that value is returned.</p><p role="note">The default type when the <code>fn:max</code> function is applied to
               <code>xs:untypedAtomic</code> values is <code>xs:double</code>. This differs from the
            default type for operators such as <code>gt</code>, and for sorting in XQuery and XSLT,
            which is <code>xs:string</code>.</p><p role="note">The rules for the dynamic type of the result are stricter in version 3.1 of the specification than
         in earlier versions. For example, if all the values in the input sequence belong to types derived from
         <code>xs:integer</code>, version 3.0 required only that the result be an instance
         of the least common supertype of the types present in the input sequence; Version 3.1
         requires that the returned value retains its original type. This does not apply, however, where type promotion
         is needed to convert all the values to a common primitive type.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>fn:max((3,4,5))</code> returns <code>5</code>.</p><p>The expression <code>fn:max([3,4,5])</code> returns <code>5</code>. <emph>(Arrays are atomized).</emph></p><p>The expression <code>fn:max((xs:integer(5), xs:float(5.0), xs:double(0)))</code> returns <code>xs:double(5.0e0)</code>.</p><p><code>fn:max((3,4,"Zero"))</code> raises a type error <errorref class="RG" code="0006"/>. </p><p>The expression <code>fn:max((fn:current-date(), xs:date("2100-01-01")))</code> returns <code>xs:date("2100-01-01")</code>. <emph>(Assuming that the current date is during the 21st
                  century.)</emph></p><p>The expression <code>fn:max(("a", "b", "c"))</code> returns <code>"c"</code>. <emph>(Assuming a typical default collation.)</emph></p></def></gitem></glist></div3><div3 id="func-min"><head>fn:min</head><glist><gitem><label>Summary</label><def><p>Returns a value that is equal to the lowest value appearing in the input sequence.</p></def></gitem><gitem><label>Signatures</label><def><example role="signature"><proto name="min" return-type="xs:anyAtomicType?" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg" type="xs:anyAtomicType*"/></proto></example><example role="signature"><proto name="min" return-type="xs:anyAtomicType?" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg" type="xs:anyAtomicType*"/><arg name="collation" type="xs:string"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>The zero-argument form of this function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-dependent">context-dependent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>.  It depends on 
		collations, and implicit timezone.
	</p><p>The one-argument form of this function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-dependent">context-dependent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>.  It depends on 
		collations, and static base URI, and implicit timezone.
	</p></def></gitem><gitem><label>Rules</label><def><p>The following rules are applied to the input sequence:</p><ulist><item><p>Values of type <code>xs:untypedAtomic</code> in <code>$arg</code> are cast to
                     <code>xs:double</code>.</p></item><item diff="chg" at="B"><p>If the resulting sequence contains values that are instances of more than one primitive type
                  (meaning the 19 primitive types defined in <bibref ref="xmlschema11-2"/>), then:
               </p><olist><item><p>If each value is an instance of one of the types <code>xs:string</code> or <code>xs:anyURI</code>,
                     then all the values are cast to type <code>xs:string</code>.</p></item><item><p>If each value is an instance of one of the types <code>xs:decimal</code> or <code>xs:float</code>,
                     then all the values are cast to type <code>xs:float</code>.</p></item><item><p>If each value is an instance of one of the types <code>xs:decimal</code>, <code>xs:float</code>,
                     or <code>xs:double</code>, then all the values are cast to type <code>xs:double</code>.</p></item><item><p>Otherwise, a type error is raised <errorref class="RG" code="0006"/>.</p></item></olist><note><p>The primitive type of an <code>xs:integer</code> value for this purpose is <code>xs:decimal</code>.</p></note></item></ulist><p>The items in the resulting sequence may be reordered in an arbitrary order. The
            resulting sequence is referred to below as the converted sequence. The function returns
            an item from the converted sequence rather than the input sequence. </p><p>If the converted sequence is empty, the empty sequence is returned.</p><p>All items in the converted sequence must be derived from a single base type for which
            the <code>le</code> operator is defined. In addition, the values in the sequence must
            have a total order. If date/time values do not have a timezone, they are considered to
            have the implicit timezone provided by the dynamic context for the purpose of
            comparison. Duration values must either all be <code>xs:yearMonthDuration</code> values
            or must all be <code>xs:dayTimeDuration</code> values.</p><p>If the converted sequence contains the value <code>NaN</code>, the value
               <code>NaN</code> is returned
            <phrase diff="add" at="B">(as an <code>xs:float</code> or <code>xs:double</code> as appropriate)</phrase>.</p><p>If the items in the converted sequence are of type <code>xs:string</code> or types
            derived by restriction from <code>xs:string</code>, then the determination of the item
            with the smallest value is made according to the collation that is used. If the type of
            the items in the converted sequence is not <code>xs:string</code> and
               <code>$collation</code> is specified, the collation is ignored.</p><p>The collation used by this function is determined according to the rules in <specref ref="choosing-a-collation"/>.</p><p>The function returns the result of the expression:</p><eg xml:space="preserve">
   if (every $v in $c satisfies $c[1] le $v) 
   then $c[1] 
   else fn:min(fn:tail($c))</eg><p>evaluated with <code>$collation</code> as the default collation if specified, and with
               <code>$c</code> as the converted sequence.</p></def></gitem><gitem><label>Error Conditions</label><def><p>A type error is raised <errorref class="RG" code="0006"/> if the input sequence contains
            items of incompatible types, as described above.</p></def></gitem><gitem><label>Notes</label><def><p role="note">Because the rules allow the sequence to be reordered, if there are two or items that are
            "equal lowest", the specific item whose value is returned is <termref def="implementation-dependent">implementation-dependent</termref>. This can arise for example if two different strings
            compare equal under the selected collation, or if two different <code>xs:dateTime</code>
            values compare equal despite being in different timezones.</p><p role="note">If the converted sequence contains exactly one value then that value is returned.</p><p role="note">The default type when the <code>fn:min</code> function is applied to
               <code>xs:untypedAtomic</code> values is <code>xs:double</code>. This differs from the
            default type for operators such as <code>lt</code>, and for sorting in XQuery and XSLT,
            which is <code>xs:string</code>.</p><p role="note">The rules for the dynamic type of the result are stricter in version 3.1 of the specification than
            in earlier versions. For example, if all the values in the input sequence belong to types derived from
            <code>xs:integer</code>, version 3.0 required only that the result be an instance
            of the least common supertype of the types present in the input sequence; Version 3.1
            requires that the returned value retains its original type. This does not apply, however, where type promotion
            is needed to convert all the values to a common primitive type.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>fn:min((3,4,5))</code> returns <code>3</code>.</p><p>The expression <code>fn:min([3,4,5])</code> returns <code>3</code>. <emph>(Arrays are atomized).</emph></p><p>The expression <code>fn:min((xs:integer(5), xs:float(5), xs:double(10)))</code> returns <code>xs:double(5.0e0)</code>.</p><p><code>fn:min((3,4,"Zero"))</code> raises a type error <errorref class="RG" code="0006"/>. </p><p><code>fn:min((xs:float(0.0E0), xs:float(-0.0E0)))</code> can return either positive
               or negative zero. The two items are equal, so it is <termref def="implementation-dependent">implementation-dependent</termref> which is returned.</p><p>The expression <code>fn:min((fn:current-date(), xs:date("1900-01-01")))</code> returns <code>xs:date("1900-01-01")</code>. <emph>(Assuming that the current date is set to a reasonable
                  value.)</emph></p><p>The expression <code>fn:min(("a", "b", "c"))</code> returns <code>"a"</code>. <emph>(Assuming a typical default collation.)</emph></p></def></gitem></glist></div3><div3 id="func-sum"><head>fn:sum</head><glist><gitem><label>Summary</label><def><p>Returns a value obtained by adding together the values in <code>$arg</code>.</p></def></gitem><gitem><label>Signatures</label><def><example role="signature"><proto name="sum" return-type="xs:anyAtomicType" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg" type="xs:anyAtomicType*"/></proto></example><example role="signature"><proto name="sum" return-type="xs:anyAtomicType?" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg" type="xs:anyAtomicType*"/><arg name="zero" type="xs:anyAtomicType?"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>Any values of type <code>xs:untypedAtomic</code> in <code>$arg</code> are cast to
               <code>xs:double</code>. The items in the resulting sequence may be reordered in an
            arbitrary order. The resulting sequence is referred to below as the converted
            sequence.</p><p>If the converted sequence is empty, then the single-argument form of the function
            returns the <code>xs:integer</code> value <code>0</code>; the two-argument form returns
            the value of the argument <code>$zero</code>.</p><p>If the converted sequence contains the value <code>NaN</code>, <code>NaN</code> is
            returned.</p><p>All items in <code>$arg</code> must be numeric or derived from a single base type. In
            addition, the type must support addition. Duration values must either all be
               <code>xs:yearMonthDuration</code> values or must all be
               <code>xs:dayTimeDuration</code> values. For numeric values, the numeric promotion
            rules defined in <specref ref="op.numeric"/> are used to promote all values to a single
            common type. The sum of a sequence of integers will therefore be an integer, while the
            sum of a numeric sequence that includes at least one <code>xs:double</code> will be an
               <code>xs:double</code>. </p><p>The result of the function, using the second signature, is the result of the
            expression:</p><eg xml:space="preserve">
if (fn:count($c) eq 0) then
    $zero
else if (fn:count($c) eq 1) then
    $c[1]
else
    $c[1] + fn:sum(subsequence($c, 2))</eg><p>where <code>$c</code> is the converted sequence.</p><p>The result of the function, using the first signature, is the result of the expression:
               <code>fn:sum($arg, 0)</code>.</p></def></gitem><gitem><label>Error Conditions</label><def><p>A type error is raised <errorref class="RG" code="0006"/> if the input sequence contains
            items of incompatible types, as described above.</p></def></gitem><gitem><label>Notes</label><def><p role="note">The second argument allows an appropriate value to be defined to represent the sum of an
            empty sequence. For example, when summing a sequence of durations it would be
            appropriate to return a zero-length duration of the appropriate type. This argument is
            necessary because a system that does dynamic typing cannot distinguish "an empty
            sequence of integers", for example, from "an empty sequence of durations".</p><p role="note"> If the converted sequence contains exactly one value then that value is returned.</p></def></gitem><gitem><label>Examples</label><def role="example"><eg xml:space="preserve">let $d1 := xs:yearMonthDuration("P20Y")</eg><eg xml:space="preserve">let $d2 := xs:yearMonthDuration("P10M")</eg><eg xml:space="preserve">let $seq1 := ($d1, $d2)</eg><eg xml:space="preserve">let $seq3 := (3, 4, 5)</eg><p>The expression <code>fn:sum(($d1, $d2))</code> returns <code>xs:yearMonthDuration("P20Y10M")</code>.</p><p>The expression <code>fn:sum($seq1[. lt xs:yearMonthDuration('P3M')],
                  xs:yearMonthDuration('P0M'))</code> returns <code>xs:yearMonthDuration("P0M")</code>.</p><p>The expression <code>fn:sum($seq3)</code> returns <code>12</code>.</p><p>The expression <code>fn:sum(())</code> returns <code>0</code>.</p><p>The expression <code>fn:sum((),())</code> returns <code>()</code>.</p><p>The expression <code>fn:sum((1 to 100)[. lt 0], 0) </code> returns <code>0</code>.</p><p><code>fn:sum(($d1, 9E1))</code> raises a type error <errorref class="RG" code="0006"/>. </p><p>The expression <code>fn:sum(($d1, $d2), "ein Augenblick")</code> returns <code>xs:yearMonthDuration("P20Y10M")</code>. <emph>(There is no requirement that the <code>$zero</code> value should be
                  the same type as the items in <code>$arg</code>, or even that it should belong to
                  a type that supports addition.)</emph></p><p>The expression <code>fn:sum([1, 2, 3])</code> returns <code>6</code>. <emph>(Atomizing an array returns the sequence obtained by atomizing its members.)</emph></p><p>The expression <code>fn:sum([[1, 2], [3, 4]])</code> returns <code>10</code>. <emph>(Atomizing an array returns the sequence obtained by atomizing its members.)</emph></p></def></gitem></glist></div3></div2><div2 id="fns-on-identifiers"><head>Functions on node identifiers</head><p>This section defines a number of functions used to find elements by <code>ID</code> or <code>IDREF</code> value, 
            or to generate IDs.</p><table class="index"><thead><tr><th rowspan="1" colspan="1">Function</th><th rowspan="1" colspan="1">Meaning</th></tr></thead><tbody><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:id</code></td><td rowspan="1" colspan="1">Returns the sequence of element nodes that have an <code>ID</code> value matching the
            value of one or more of the <code>IDREF</code> values supplied in <code>$arg</code>.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:element-with-id</code></td><td rowspan="1" colspan="1"> Returns the sequence of element nodes that have an <code>ID</code> value matching the
            value of one or more of the <code>IDREF</code> values supplied in <code>$arg</code>.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:idref</code></td><td rowspan="1" colspan="1">Returns the sequence of element or attribute nodes with an <code>IDREF</code> value
            matching the value of one or more of the <code>ID</code> values supplied in
               <code>$arg</code>.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:generate-id</code></td><td rowspan="1" colspan="1">This function returns a string that uniquely identifies a given node. </td></tr></tbody></table><div3 id="func-id"><head>fn:id</head><glist><gitem><label>Summary</label><def><p>Returns the sequence of element nodes that have an <code>ID</code> value matching the
            value of one or more of the <code>IDREF</code> values supplied in <code>$arg</code>.</p></def></gitem><gitem><label>Signatures</label><def><example role="signature"><proto name="id" return-type="element()*" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg" type="xs:string*"/></proto></example><example role="signature"><proto name="id" return-type="element()*" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg" type="xs:string*"/><arg name="node" type="node()"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>The one-argument form of this function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-dependent">context-dependent</termref>,  and <termref def="dt-focus-dependent">focus-dependent</termref>. </p><p>The two-argument form of this function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>The function returns a sequence, in document order with duplicates eliminated,
            containing every element node <code>E</code> that satisfies all the following
            conditions:</p><olist><item><p>
                  <code>E</code> is in the target document. The target document is the document
                  containing <code>$node</code>, or the document containing the context item
                     (<code>.</code>) if the second argument is omitted. The behavior of the
                  function if <code>$node</code> is omitted is exactly the same as if the context
                  item had been passed as <code>$node</code>.</p></item><item><p><code>E</code> has an <code>ID</code> value equal to one of the candidate
                     <code>IDREF</code> values, where:</p><ulist><item><p> An element has an <code>ID</code> value equal to <code>V</code> if either
                        or both of the following conditions are true:</p><ulist><item><p>The <code>is-id</code> property (See <xspecref spec="DM31" ref="dm-is-id"/>.) of the element node is true, and the typed value
                              of the element node is equal to <code>V</code> under the rules of the
                                 <code>eq</code> operator using the Unicode codepoint collation
                                 (<code>http://www.w3.org/2005/xpath-functions/collation/codepoint</code>).</p></item><item><p>The element has an attribute node whose <code>is-id</code> property
                              (See <xspecref spec="DM31" ref="dm-is-id"/>.) is true and whose typed
                              value is equal to <code>V</code> under the rules of the
                                 <code>eq</code> operator using the Unicode code point collation
                                 (<code>http://www.w3.org/2005/xpath-functions/collation/codepoint</code>).</p></item></ulist></item><item><p> Each <code>xs:string</code> in <code>$arg</code> is parsed as if it were of
                        type <code>IDREFS</code>, that is, each <code>xs:string</code> in
                           <code>$arg</code> is treated as a whitespace-separated sequence of
                        tokens, each acting as an <code>IDREF</code>. These tokens are then included
                        in the list of candidate <code>IDREF</code>s. If any of the tokens is not a
                        lexically valid <code>IDREF</code> (that is, if it is not lexically an
                           <code>xs:NCName</code>), it is ignored. Formally, the candidate
                           <code>IDREF</code> values are the strings in the sequence given by the
                        expression:</p><eg xml:space="preserve">for $s in $arg return 
    fn:tokenize(fn:normalize-space($s), ' ')[. castable as xs:IDREF]</eg></item></ulist></item><item><p>If several elements have the same <code>ID</code> value, then <code>E</code> is
                  the one that is first in document order.</p></item></olist></def></gitem><gitem><label>Error Conditions</label><def><p>A dynamic error is raised <errorref class="DC" code="0001" type="dynamic"/> if
               <code>$node</code>, or the context item if the second argument is absent, is a node
            in a tree whose root is not a document node.</p><p>The following errors may be raised when <code>$node</code> is omitted:</p><ul><li>
               <p>If the context item is <xtermref ref="dt-absent" spec="DM31">absent</xtermref>,
                  dynamic error <xerrorref spec="XP" class="DY" code="0002" type="dynamic"/></p>
            </li><li>
               <p>If the context item is not a node, type error <xerrorref spec="XP" class="TY" code="0004" type="type"/>.</p>
            </li></ul></def></gitem><gitem><label>Notes</label><def><p role="note">The effect of this function is anomalous in respect of element nodes with the
               <code>is-id</code> property. For legacy reasons, this function returns the element
            that has the <code>is-id</code> property, whereas it would be more appropriate to return
            its parent, that being the element that is uniquely identified by the ID. A new function
               <code>fn:element-with-id</code> has been introduced with the desired
            behavior.</p><p role="note"> If the data model is constructed from an Infoset, an attribute will have the
               <code>is-id</code> property if the corresponding attribute in the Infoset had an
            attribute type of <code>ID</code>: typically this means the attribute was declared as an
               <code>ID</code> in a DTD.</p><p role="note"> If the data model is constructed from a PSVI, an element or attribute will have the
               <code>is-id</code> property if its typed value is a single atomic value of type
               <code>xs:ID</code> or a type derived by restriction from <code>xs:ID</code>.</p><p role="note"> No error is raised in respect of a candidate <code>IDREF</code> value that does not
            match the <code>ID</code> of any element in the document. If no candidate
               <code>IDREF</code> value matches the <code>ID</code> value of any element, the
            function returns the empty sequence.</p><p role="note"> It is not necessary that the supplied argument should have type <code>xs:IDREF</code>
            or <code>xs:IDREFS</code>, or that it should be derived from a node with the
               <code>is-idrefs</code> property.</p><p role="note"> An element may have more than one <code>ID</code> value. This can occur with synthetic
            data models or with data models constructed from a PSVI where the element and one of its
            attributes are both typed as <code>xs:ID</code>.</p><p role="note"> If the source document is well-formed but not valid, it is possible for two or more
            elements to have the same <code>ID</code> value. In this situation, the function will
            select the first such element.</p><p role="note"> It is also possible in a well-formed but invalid document to have an element or
            attribute that has the <code>is-id</code> property but whose value does not conform to
            the lexical rules for the <code>xs:ID</code> type. Such a node will never be selected by
            this function.</p></def></gitem><gitem><label>Examples</label><def role="example"><eg xml:space="preserve">let $emp := 
        validate lax{    
          document{
            &lt;employee xml:id="ID21256"
                      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
                      xmlns:xs="http://www.w3.org/2001/XMLSchema"&gt;
               &lt;empnr xsi:type="xs:ID"&gt;E21256&lt;/empnr&gt;
               &lt;first&gt;John&lt;/first&gt;
               &lt;last&gt;Brown&lt;/last&gt;
            &lt;/employee&gt;
          }
        }
         </eg><p>The expression <code>$emp/id('ID21256')/name()</code> returns <code>"employee"</code>. <emph>(The <code>xml:id</code> attribute has the <code>is-id</code> property,
                  so the employee element is selected.)</emph></p><p>The expression <code>$emp/id('E21256')/name()</code> returns <code>"empnr"</code>. <emph>(Assuming the <code>empnr</code> element is given the type
                     <code>xs:ID</code> as a result of schema validation, the element will have the
                     <code>is-id</code> property and is therefore selected. Note the difference from
                  the behavior of <code>fn:element-with-id</code>.)</emph></p></def></gitem></glist></div3><div3 id="func-element-with-id"><head>fn:element-with-id</head><glist><gitem><label>Summary</label><def><p> Returns the sequence of element nodes that have an <code>ID</code> value matching the
            value of one or more of the <code>IDREF</code> values supplied in <code>$arg</code>.</p></def></gitem><gitem><label>Signatures</label><def><example role="signature"><proto name="element-with-id" return-type="element()*" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg" type="xs:string*"/></proto></example><example role="signature"><proto name="element-with-id" return-type="element()*" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg" type="xs:string*"/><arg name="node" type="node()"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>The one-argument form of this function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-dependent">context-dependent</termref>,  and <termref def="dt-focus-dependent">focus-dependent</termref>. </p><p>The two-argument form of this function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><note><p>The effect of this function is identical to <code>fn:id</code> in respect of
               elements that have an attribute with the <code>is-id</code> property. However, it
               behaves differently in respect of element nodes with the <code>is-id</code> property.
               Whereas the <code>fn:id</code> function, for legacy reasons, returns the element that has the
                  <code>is-id</code> property, this function returns the element identified by the ID,
               which is the parent of the element having the <code>is-id</code> property.</p></note><p>The function returns a sequence, in document order with duplicates eliminated,
            containing every element node <code>E</code> that satisfies all the following
            conditions:</p><olist><item><p>
                  <code>E</code> is in the target document. The target document is the document
                  containing <code>$node</code>, or the document containing the context item
                     (<code>.</code>) if the second argument is omitted. The behavior of the
                  function if <code>$node</code> is omitted is exactly the same as if the context
                  item had been passed as <code>$node</code>.</p></item><item><p><code>E</code> has an <code>ID</code> value equal to one of the candidate
                     <code>IDREF</code> values, where:</p><ulist><item><p> An element has an <code>ID</code> value equal to <code>V</code> if either
                        or both of the following conditions are true:</p><ulist><item><p>The element has an child element node whose <code>is-id</code>
                              property (See <xspecref spec="DM31" ref="dm-is-id"/>.) is true and
                              whose typed value is equal to <code>V</code> under the rules of the
                                 <code>eq</code> operator using the Unicode code point collation
                                 (<code>http://www.w3.org/2005/xpath-functions/collation/codepoint</code>).</p></item><item><p>The element has an attribute node whose <code>is-id</code> property
                              (See <xspecref spec="DM31" ref="dm-is-id"/>.) is true and whose typed
                              value is equal to <code>V</code> under the rules of the
                                 <code>eq</code> operator using the Unicode code point collation
                                 (<code>http://www.w3.org/2005/xpath-functions/collation/codepoint</code>).</p></item></ulist></item><item><p>Each <code>xs:string</code> in <code>$arg</code> is parsed as if it were of
                        type <code>IDREFS</code>, that is, each <code>xs:string</code> in
                           <code>$arg</code> is treated as a whitespace-separated sequence of
                        tokens, each acting as an <code>IDREF</code>. These tokens are then included
                        in the list of candidate <code>IDREF</code>s. If any of the tokens is not a
                        lexically valid <code>IDREF</code> (that is, if it is not lexically an
                           <code>xs:NCName</code>), it is ignored. Formally, the candidate
                           <code>IDREF</code> values are the strings in the sequence given by the
                        expression:</p><eg xml:space="preserve">for $s in $arg return 
   fn:tokenize(fn:normalize-space($s), ' ')[. castable as xs:IDREF]</eg></item></ulist></item><item><p> If several elements have the same <code>ID</code> value, then <code>E</code> is
                  the one that is first in document order.</p></item></olist></def></gitem><gitem><label>Error Conditions</label><def><p>A dynamic error is raised <errorref class="DC" code="0001" type="dynamic"/> if
               <code>$node</code>, or the context item if the second argument is omitted, is a node
            in a tree whose root is not a document node.</p><p>The following errors may be raised when <code>$node</code> is omitted:</p><ul><li>
               <p>If the context item is <xtermref ref="dt-absent" spec="DM31">absent</xtermref>,
                  dynamic error <xerrorref spec="XP" class="DY" code="0002" type="dynamic"/></p>
            </li><li>
               <p>If the context item is not a node, type error <xerrorref spec="XP" class="TY" code="0004" type="type"/>.</p>
            </li></ul></def></gitem><gitem><label>Notes</label><def><p role="note">This function is equivalent to the <code>fn:id</code> function except when dealing with
            ID-valued element nodes. Whereas the <code>fn:id</code> function selects the element
            containing the identifier, this function selects its parent.</p><p role="note">If the data model is constructed from an Infoset, an attribute will have the
               <code>is-id</code> property if the corresponding attribute in the Infoset had an
            attribute type of <code>ID</code>: typically this means the attribute was declared as an
               <code>ID</code> in a DTD.</p><p role="note"> If the data model is constructed from a PSVI, an element or attribute will have the
               <code>is-id</code> property if its typed value is a single atomic value of type
               <code>xs:ID</code> or a type derived by restriction from <code>xs:ID</code>.</p><p role="note"> No error is raised in respect of a candidate <code>IDREF</code> value that does not
            match the <code>ID</code> of any element in the document. If no candidate
               <code>IDREF</code> value matches the <code>ID</code> value of any element, the
            function returns the empty sequence.</p><p role="note"> It is not necessary that the supplied argument should have type <code>xs:IDREF</code>
            or <code>xs:IDREFS</code>, or that it should be derived from a node with the
               <code>is-idrefs</code> property.</p><p role="note"> An element may have more than one <code>ID</code> value. This can occur with synthetic
            data models or with data models constructed from a PSVI where the element and one of its
            attributes are both typed as <code>xs:ID</code>.</p><p role="note"> If the source document is well-formed but not valid, it is possible for two or more
            elements to have the same <code>ID</code> value. In this situation, the function will
            select the first such element.</p><p role="note"> It is also possible in a well-formed but invalid document to have an element or
            attribute that has the <code>is-id</code> property but whose value does not conform to
            the lexical rules for the <code>xs:ID</code> type. Such a node will never be selected by
            this function.</p></def></gitem><gitem><label>Examples</label><def role="example"><eg xml:space="preserve">let $emp := 
         validate lax{    
          document{
            &lt;employee xml:id="ID21256"
                      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
                      xmlns:xs="http://www.w3.org/2001/XMLSchema"&gt;
               &lt;empnr xsi:type="xs:ID"&gt;E21256&lt;/empnr&gt;
               &lt;first&gt;John&lt;/first&gt;
               &lt;last&gt;Brown&lt;/last&gt;
            &lt;/employee&gt;
          }
        }
         </eg><p>The expression <code>$emp/fn:element-with-id('ID21256')/name()</code> returns <code>"employee"</code>. <emph>(The <code>xml:id</code> attribute has the <code>is-id</code> property,
                  so the employee element is selected.)</emph></p><p>The expression <code>$emp/fn:element-with-id('E21256')/name()</code> returns <code>"employee"</code>. <emph>(Assuming the <code>empnr</code> element is given the type
                     <code>xs:ID</code> as a result of schema validation, the element will have the
                     <code>is-id</code> property and is therefore its parent is selected. Note the
                  difference from the behavior of <code>fn:id</code>.)</emph></p></def></gitem></glist></div3><div3 id="func-idref"><head>fn:idref</head><glist><gitem><label>Summary</label><def><p>Returns the sequence of element or attribute nodes with an <code>IDREF</code> value
            matching the value of one or more of the <code>ID</code> values supplied in
               <code>$arg</code>.</p></def></gitem><gitem><label>Signatures</label><def><example role="signature"><proto name="idref" return-type="node()*" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg" type="xs:string*"/></proto></example><example role="signature"><proto name="idref" return-type="node()*" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg" type="xs:string*"/><arg name="node" type="node()"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>The one-argument form of this function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-dependent">context-dependent</termref>,  and <termref def="dt-focus-dependent">focus-dependent</termref>. </p><p>The two-argument form of this function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p> The function returns a sequence, in document order with duplicates eliminated,
            containing every element or attribute node <code>$N</code> that satisfies all the
            following conditions:</p><olist><item><p><code>$N</code> is in the target document. The target document is the document
                  containing <code>$node</code> or the document containing the context item
                     (<code>.</code>) if the second argument is omitted. The behavior of the
                  function if <code>$node</code> is omitted is exactly the same as if the context
                  item had been passed as <code>$node</code>.</p></item><item><p><code>$N</code> has an <code>IDREF</code> value equal to one of the candidate
                     <code>ID</code> values, where:</p><ulist><item><p>A node <code>$N</code> has an <code>IDREF</code> value equal to
                           <code>V</code> if both of the following conditions are true:</p><ulist><item><p>The <code>is-idrefs</code> property (see <xspecref spec="DM31" ref="dm-is-idrefs"/>) of <code>$N</code> is <code>true</code>.</p></item><item><p>The sequence </p><eg xml:space="preserve">fn:tokenize(fn:normalize-space(fn:string($N)), ' ')</eg><p>contains a string that is
                              equal to <code>V</code> under the rules of the <code>eq</code>
                              operator using the Unicode code point collation
                                 (<code>http://www.w3.org/2005/xpath-functions/collation/codepoint</code>).</p></item></ulist></item><item><p>Each <code>xs:string</code> in <code>$arg</code> is parsed as if it were of
                        lexically of type <code>xs:ID</code>. These <code>xs:string</code>s are then
                        included in the list of candidate <code>xs:ID</code>s. If any of the strings
                        in <code>$arg</code> is not a lexically valid <code>xs:ID</code> (that is,
                        if it is not lexically an <code>xs:NCName</code>), it is ignored. More
                        formally, the candidate <code>ID</code> values are the strings in the
                        sequence:</p><eg xml:space="preserve">$arg[. castable as xs:NCName]</eg></item></ulist></item></olist></def></gitem><gitem><label>Error Conditions</label><def><p>A dynamic error is raised <errorref class="DC" code="0001" type="dynamic"/> if
               <code>$node</code>, or the context item if the second argument is omitted, is a node
            in a tree whose root is not a document node. </p><p>The following errors may be raised when <code>$node</code> is omitted:</p><ul><li>
               <p>If the context item is <xtermref ref="dt-absent" spec="DM31">absent</xtermref>,
                  dynamic error <xerrorref spec="XP" class="DY" code="0002" type="dynamic"/></p>
            </li><li>
               <p>If the context item is not a node, type error <xerrorref spec="XP" class="TY" code="0004" type="type"/>.</p>
            </li></ul></def></gitem><gitem><label>Notes</label><def><p role="note"> An element or attribute typically acquires the <code>is-idrefs</code> property by being
            validated against the schema type <code>xs:IDREF</code> or <code>xs:IDREFS</code>, or
            (for attributes only) by being described as of type <code>IDREF</code> or
               <code>IDREFS</code> in a DTD.</p><p role="note">Because the function is sensitive to the way in which the data model
         is constructed, calls on this function are not always interoperable.</p><p role="note"> No error is raised in respect of a candidate <code>ID</code> value that does not match
            the <code>IDREF</code> value of any element or attribute in the document. If no
            candidate <code>ID</code> value matches the <code>IDREF</code> value of any element or
            attribute, the function returns the empty sequence.</p><p role="note"> It is possible for two or more nodes to have an <code>IDREF</code> value that matches a
            given candidate <code>ID</code> value. In this situation, the function will return all
            such nodes. However, each matching node will be returned at most once, regardless how
            many candidate <code>ID</code> values it matches.</p><p role="note"> It is possible in a well-formed but invalid document to have a node whose
               <code>is-idrefs</code> property is true but that does not conform to the lexical
            rules for the <code>xs:IDREF</code> type. The effect of the above rules is that
            ill-formed candidate <code>ID</code> values and ill-formed <code>IDREF</code> values are
            ignored.</p><p role="note">If the data model is constructed from a PSVI, the typed value of a node that has the
               <code>is-idrefs</code> property will contain at least one atomic value of type
               <code>xs:IDREF</code> (or a type derived by restriction from <code>xs:IDREF</code>).
            It may also contain atomic values of other types. These atomic values are treated as
            candidate <code>ID</code> values <phrase diff="chg" at="D">if two conditions are met: their lexical form must be valid as an
               <code>xs:NCName</code>, and there must be at least one instance of <code>xs:IDREF</code>
            in the typed value of the node. If these conditions are not satisfied, such values are ignored.</phrase></p></def></gitem><gitem><label>Examples</label><def role="example"><eg xml:space="preserve">let $emp := 
      validate lax {  
        document {    
          &lt;employees xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
                     xmlns:xs="http://www.w3.org/2001/XMLSchema"&gt;  
            &lt;employee xml:id="ID21256"&gt;
               &lt;empnr xsi:type="xs:ID"&gt;E21256&lt;/empnr&gt;
               &lt;first&gt;Anil&lt;/first&gt;
               &lt;last&gt;Singh&lt;/last&gt;
               &lt;deputy xsi:type="xs:IDREF"&gt;E30561&lt;/deputy&gt;
            &lt;/employee&gt;
            &lt;employee xml:id="ID30561"&gt;
               &lt;empnr xsi:type="xs:ID"&gt;E30561&lt;/empnr&gt;
               &lt;first&gt;John&lt;/first&gt;
               &lt;last&gt;Brown&lt;/last&gt;
               &lt;manager xsi:type="xs:IDREF"&gt;ID21256&lt;/manager&gt;
            &lt;/employee&gt;
          &lt;/employees&gt;
        }
      }
         </eg><p>The expression <code>$emp/(element-with-id('ID21256')/@xml:id =&gt; fn:idref())/ancestor::employee/last =&gt; string()</code> returns <code>"Brown"</code>. <emph>(Assuming that <code>manager</code> has the is-idref property, the call on <code>fn:idref</code> selects
                  the <code>manager</code> element. If, instead, the <code>manager</code> had a <code>ref</code>
               attribute with the is-idref property, the call on <code>fn:idref</code> would select the attribute node.)</emph></p><p>The expression <code>$emp/(element-with-id('E30561')/empnr =&gt; fn:idref())/ancestor::employee/last =&gt; string()</code> returns <code>"Singh"</code>. <emph>(Assuming that <code>employee/deputy</code> has the is-idref property, the call on <code>fn:idref</code> selects
                  the <code>deputy</code> element.)</emph></p></def></gitem></glist></div3><div3 id="func-generate-id"><head>fn:generate-id</head><glist><gitem><label>Summary</label><def><p>This function returns a string that uniquely identifies a given node. </p></def></gitem><gitem><label>Signatures</label><def><example role="signature"><proto name="generate-id" return-type="xs:string" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"/></example><example role="signature"><proto name="generate-id" return-type="xs:string" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg" type="node()?"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>The zero-argument form of this function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-dependent">context-dependent</termref>,  and <termref def="dt-focus-dependent">focus-dependent</termref>. </p><p>The one-argument form of this function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>If the argument is omitted, it defaults to the context item (<code>.</code>). The
            behavior of the function if the argument is omitted is exactly the same as if the
            context item had been passed as the argument.</p><p>If the argument is the empty sequence, the result is the zero-length string.</p><p>In other cases, the function returns a string that uniquely identifies a given node.
            <phrase diff="add" at="E">More formally, it is guaranteed that within a single
             <termref def="execution-scope">execution scope</termref>, 
               <code>fn:codepoint-equal(fn:generate-id($N), fn:generate-id($M))</code> returns true 
               if and only if <code>($M is $N)</code> returns true.</phrase></p><p>The returned identifier <rfc2119>must</rfc2119> consist of ASCII alphanumeric characters
            and <rfc2119>must</rfc2119> start with an alphabetic character. Thus, the string is
            syntactically an XML name.</p></def></gitem><gitem><label>Error Conditions</label><def><p>The following errors may be raised when <code>$arg</code> is omitted:</p><ul><li>
               <p>If the context item is <xtermref ref="dt-absent" spec="DM31">absent</xtermref>,
                  dynamic error <xerrorref spec="XP" class="DY" code="0002" type="dynamic"/></p>
            </li><li>
               <p>If the context item is not a node, type error <xerrorref spec="XP" class="TY" code="0004" type="type"/>.</p>
            </li></ul></def></gitem><gitem><label>Notes</label><def><p role="note">An implementation is free to generate an identifier in any convenient way provided that
            it always generates the same identifier for the same node and that different identifiers
            are always generated from different nodes. An implementation is under no obligation to
            generate the same identifiers each time a document is transformed or queried.</p><p role="note">There is no guarantee that a generated unique identifier will be distinct from any
            unique IDs specified in the source document.</p><p role="note">There is no inverse to this function; it is not directly possible to find the node with
            a given generated ID. Of course, it is possible to search a given sequence of nodes
            using an expression such as <code>$nodes[generate-id()=$id]</code>.</p><p role="note">It is advisable, but not required, for implementations to generate IDs that are distinct
            even when compared using a case-blind collation.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The primary use case for this function is to generate hyperlinks. For example, when
               generating HTML, an anchor for a given section <code>$sect</code> can be generated by
               writing (in either XSLT or XQuery):</p><p>
               <code>&lt;a name="{fn:generate-id($sect)}"/&gt;</code>
            </p><p>and a link to that section can then be produced with code such as:</p><p>
               <code>see &lt;a href="#{fn:generate-id($sect)}"&gt;here&lt;/a&gt;</code>
            </p><p>Note that anchors generated in this way will not necessarily be the same each time a
               document is republished.</p><p>Since the keys in a map must be atomic values, it is possible to use generated IDs
               as surrogates for nodes when constructing a map. For example, in some implementations,
               testing whether a node <code>$N</code> is a member of a large node-set <code>$S</code>
               using the expression <code>fn:exists($N intersect $S)</code> may be expensive; there
               may then be performance benefits in creating a map:</p><p>
               <code>let $SMap := map:merge($S!map{fn:generate-id(.) : .})</code>
            </p><p>and then testing for membership of the node-set using:</p><p>
               <code>map:contains($SMap, fn:generate-id($N))</code>
            </p></def></gitem></glist></div3></div2><div2 id="fns-on-docs"><head>Functions giving access to external information</head><p>The functions in this section provide access to resources (such as files) in the external environment.</p><table class="index"><thead><tr><th rowspan="1" colspan="1">Function</th><th rowspan="1" colspan="1">Meaning</th></tr></thead><tbody><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:doc</code></td><td rowspan="1" colspan="1">Retrieves a document using a URI supplied as an <code>xs:string</code>, and returns the
            corresponding document node.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:doc-available</code></td><td rowspan="1" colspan="1">The function returns true if and only if the function call <code>fn:doc($uri)</code>
            would return a document node.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:collection</code></td><td rowspan="1" colspan="1">Returns a sequence of items identified by a
            collection URI; or a default collection if no URI is supplied.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:uri-collection</code></td><td rowspan="1" colspan="1">Returns a sequence of <code>xs:anyURI</code> values representing the URIs in a URI
            collection.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:unparsed-text</code></td><td rowspan="1" colspan="1">The <code>fn:unparsed-text</code> function reads an external resource (for example, a
            file) and returns a string representation of the resource.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:unparsed-text-lines</code></td><td rowspan="1" colspan="1">The <code>fn:unparsed-text-lines</code> function reads an external resource (for
            example, a file) and returns its contents as a sequence of strings, one for each line of
            text in the string representation of the resource.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:unparsed-text-available</code></td><td rowspan="1" colspan="1">Because errors in evaluating the <code>fn:unparsed-text</code> function are
            non-recoverable, these two functions are provided to allow an application to determine
            whether a call with particular arguments would succeed.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:environment-variable</code></td><td rowspan="1" colspan="1">Returns the value of a system environment variable, if it exists.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:available-environment-variables</code></td><td rowspan="1" colspan="1">Returns a list of environment variable names that are suitable for passing to
               <code>fn:environment-variable</code>, as a (possibly empty) sequence of strings.</td></tr></tbody></table><div3 id="func-doc"><head>fn:doc</head><glist><gitem><label>Summary</label><def><p>Retrieves a document using a URI supplied as an <code>xs:string</code>, and returns the
            corresponding document node.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="doc" return-type="document-node()?" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="uri" type="xs:string?"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-dependent">context-dependent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>.  It depends on 
		available documents, and static base URI.
	</p></def></gitem><gitem><label>Rules</label><def><p>If <code>$uri</code> is the empty sequence, the result is an empty sequence.</p><p>If <code>$uri</code> is a relative URI reference, it is resolved relative to the value
            of the <term>static base URI</term> property from the static context. The resulting absolute URI is
            promoted to an <code>xs:string</code>.</p><p>If the <term>available documents</term> described in <xspecref spec="XP31" ref="eval_context"/> provides a mapping from this string to a document node, the
            function returns that document node.</p><p>The URI may include a fragment identifier.</p><p>By default, this function is <termref def="deterministic">deterministic</termref>. Two
            calls on this function return the same document node if the same URI Reference (after
            resolution to an absolute URI Reference) is supplied to both calls. Thus, the following
            expression (if it does not raise an error) will always be true:</p><eg xml:space="preserve">doc("foo.xml") is doc("foo.xml")</eg><p>However, for performance reasons, implementations may provide a user option to evaluate
            the function without a guarantee of determinism. The manner in which any such option is
            provided is implementation-defined. If the user has not selected such an option, a call
            of the function must either return a deterministic result or must raise a dynamic error
               <errorref class="DC" code="0003"/>.</p><note><p>If <code>$uri</code> is read from a source document, it is generally appropriate to
               resolve it relative to the base URI property of the relevant node in the source
               document. This can be achieved by calling the <code>fn:resolve-uri</code> function,
               and passing the resulting absolute URI as an argument to the <code>fn:doc</code>
               function.</p></note><p>If two calls to this function supply different absolute URI References as arguments, the
            same document node may be returned if the implementation can determine that the two
            arguments refer to the same resource.</p><p> By defining the semantics of this function in terms of a string-to-document-node
            mapping in the dynamic context, the specification is acknowledging that the results of
            this function are outside the purview of the language specification itself, and depend
            entirely on the run-time environment in which the expression is evaluated. This run-time
            environment includes not only an unpredictable collection of resources ("the web"), but
            configurable machinery for locating resources and turning their contents into document
            nodes within the XPath data model. Both the set of resources that are reachable, and the
            mechanisms by which those resources are parsed and validated, are <termref def="implementation-dependent">implementation-dependent</termref>.</p><p> One possible processing model for this function is as follows. The resource identified
            by the URI Reference is retrieved. If the resource cannot be retrieved, a dynamic error
            is raised <errorref class="DC" code="0002"/>. The data resulting from the retrieval
            action is then parsed as an XML document and a tree is constructed in accordance with
            the <bibref ref="xpath-datamodel-30"/>. If the top-level media type is known and is
            "text", the content 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. If
            the contents cannot be parsed successfully, a dynamic error is raised <errorref class="DC" code="0002"/>. Otherwise, the result of the function is the document node
            at the root of the resulting tree. This tree is then optionally validated against a
            schema.</p><p>Various aspects of this processing are <termref def="implementation-defined">implementation-defined</termref>.
            Implementations may provide external configuration options that allow any aspect of the
            processing to be controlled by the user. In particular:</p><ulist><item><p>The set of URI schemes that the implementation recognizes is
                  implementation-defined. Implementations may allow the mapping of URIs to resources
                  to be configured by the user, using mechanisms such as catalogs or user-written
                  URI handlers.</p></item><item><p>The handling of non-XML media types is implementation-defined. Implementations may
                  allow instances of the data model to be constructed from non-XML resources, under
                  user control.</p></item><item><p>It is <termref def="implementation-defined">implementation-defined</termref> whether DTD validation and/or schema
                  validation is applied to the source document.</p></item><item><p>Implementations may provide user-defined error handling options that allow
                  processing to continue following an error in retrieving a resource, or in parsing
                  and validating its content. When errors have been handled in this way, the
                  function may return either an empty sequence, or a fallback document provided by
                  the error handler.</p></item><item><p>Implementations may provide user options that relax the requirement for the
                  function to return deterministic results.</p></item><item><p diff="add" at="E">The effect of a fragment identifier in the supplied URI 
                  is <termref def="implementation-defined">implementation-defined</termref>. One possible interpretation
               is to treat the fragment identifier as an ID attribute value, and to return a document
               node having the element with the selected ID value as its only child.</p></item></ulist></def></gitem><gitem><label>Error Conditions</label><def><p>A dynamic error <rfc2119>may</rfc2119> be raised <errorref class="DC" code="0005"/> if
               <code>$uri</code> is not a valid URI <phrase diff="add" at="D">reference</phrase>.</p><p diff="add" at="B">A dynamic error is raised <errorref class="DC" code="0002"/> if a relative URI reference
         is supplied, and the base-URI property in the static context is absent.</p><p>A dynamic error is raised <errorref class="DC" code="0002"/> if the <term>available
               documents</term> provides no mapping for the absolutized URI.</p><p>A dynamic error is raised <errorref class="DC" code="0002"/> if the resource cannot be
            retrieved or cannot be parsed successfully as XML.</p><p>A dynamic error is raised <errorref class="DC" code="0003"/> if the implementation is
            not able to guarantee that the result of the function will be deterministic, and the
            user has not indicated that an unstable result is acceptable.</p></def></gitem></glist></div3><div3 id="func-doc-available"><head>fn:doc-available</head><glist><gitem><label>Summary</label><def><p>The function returns true if and only if the function call <code>fn:doc($uri)</code>
            would return a document node.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="doc-available" return-type="xs:boolean" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="uri" type="xs:string?"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-dependent">context-dependent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>.  It depends on 
		available documents, and static base URI.
	</p></def></gitem><gitem><label>Rules</label><def><p>If <code>$uri</code> is an empty sequence, this function returns <code>false</code>.</p><p>If a call on <code>fn:doc($uri)</code> would return a document node, this function
            returns <code>true</code>.</p><p diff="del" at="E">A dynamic error is raised <errorref class="DC" code="0005"/> if <code>$uri</code> is not
            a valid URI according to the rules applied by the implementation of
            <code>fn:doc</code>.</p><p>In all other cases this function returns <code>false</code>. <phrase diff="add" at="B">This
         includes the case where <phrase diff="add" at="E">an invalid URI is supplied, and also the case where </phrase>
            a valid relative URI reference is supplied, and cannot be resolved,
         for example because the static base URI is absent.</phrase></p><p>If this function returns <code>true</code>, then calling <code>fn:doc($uri)</code>
            within the same <termref def="execution-scope"/> must return a document node. However,
            if nondeterministic processing has been selected for the <code>fn:doc</code> function,
            this guarantee is lost.</p></def></gitem></glist></div3><div3 id="func-collection"><head>fn:collection</head><glist><gitem><label>Summary</label><def><p>Returns a sequence of items identified by a
            collection URI; or a default collection if no URI is supplied.</p></def></gitem><gitem><label>Signatures</label><def><example role="signature"><proto name="collection" return-type="item()*" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"/></example><example role="signature"><proto name="collection" return-type="item()*" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg" type="xs:string?"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-dependent">context-dependent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>.  It depends on 
		available collections, and static base URI.
	</p></def></gitem><gitem><label>Rules</label><def><p>This function takes an <code>xs:string</code> as argument and returns a sequence of
            <phrase diff="chg" at="D">items</phrase> obtained by interpreting <code>$arg</code> as an <code>xs:anyURI</code> and
            resolving it according to the mapping specified in <term>available 
               collections</term> described in <xspecref spec="XP31" ref="id-xp-evaluation-context-components"/>.</p><p>If <phrase diff="chg" at="D"><term>available collections</term></phrase> provides a mapping from this string to a
            sequence of items, the function returns that sequence. If <term>available 
               collections</term> maps the string to an empty sequence, then the function returns an
            empty sequence.</p><p>If <code>$arg</code> is not specified, the function returns the sequence of <phrase diff="chg" at="D">items</phrase> in
            the default collection in the dynamic context. See <xspecref spec="XP31" ref="id-xp-evaluation-context-components"/>. </p><p>If the value of <code>$arg</code> is a relative <code>xs:anyURI</code>, it is resolved
            against the value of the base-URI property from the static context. </p><p>If <code>$arg</code> is the empty sequence, the function behaves as if it had been
            called without an argument. See above.</p><p>By default, this function is <termref def="deterministic">deterministic</termref>. This
            means that repeated calls on the function with the same argument will return the same
            result. However, for performance reasons, implementations may provide a user option to
            evaluate the function without a guarantee of determinism. The manner in which any such
            option is provided is <termref def="implementation-defined">implementation-defined</termref>. If the user has not
            selected such an option, a call to this function must either return a deterministic
            result or must raise a dynamic error <errorref class="DC" code="0003"/>.</p><p>There is no requirement that <phrase diff="chg" at="D">any nodes in the result</phrase> should be in document order, nor is
            there a requirement that the result should contain no duplicates.</p></def></gitem><gitem><label>Error Conditions</label><def><p>A dynamic error is raised <errorref class="DC" code="0002"/> if no URI is supplied and
            the value of the default collection is <xtermref ref="dt-absent" spec="DM31">absent</xtermref>.</p><p diff="add" at="B">A dynamic error is raised <errorref class="DC" code="0002"/> if a relative URI reference
            is supplied, and the base-URI property in the static context is absent.</p><p>A dynamic error is raised <errorref class="DC" code="0002"/> if <term>available node
               collections</term> provides no mapping for the absolutized URI.</p><p>A dynamic error <phrase diff="chg" at="E"><rfc2119>may</rfc2119> be</phrase> raised <errorref class="DC" code="0004"/> if <code>$arg</code> is not
            a valid <code>xs:anyURI</code>.</p></def></gitem><gitem><label>Notes</label><def><p role="note">In earlier releases, the primary use for the <code>fn:collection</code> function
         was to retrieve a collection of XML documents, perhaps held as lexical XML in operating
         system filestore, or perhaps held in an XML database. In this release the concept has
         been generalised to allow other resources to be retrieved: for example JSON documents might
         be returned as arrays or maps, non-XML text files might be returned as strings, and binary
         files might be returned as instances of <code>xs:base64Binary</code>.</p><p role="note">The abstract concept of a collection might be realized in different ways by different
            implementations, and the ways in which URIs map to collections can be equally variable. 
            Specifying resources using URIs is
            useful because URIs are dynamic, can be parameterized, and do not rely on an external
            environment.</p></def></gitem></glist></div3><div3 id="func-uri-collection"><head>fn:uri-collection</head><glist><gitem><label>Summary</label><def><p>Returns a sequence of <code>xs:anyURI</code> values representing the URIs in a URI
            collection.</p></def></gitem><gitem><label>Signatures</label><def><example role="signature"><proto name="uri-collection" return-type="xs:anyURI*" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"/></example><example role="signature"><proto name="uri-collection" return-type="xs:anyURI*" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg" type="xs:string?"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-dependent">context-dependent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>.  It depends on 
		available URI collections, and static base URI.
	</p></def></gitem><gitem><label>Rules</label><def><p>The zero-argument form of the function returns the URIs in the <term>default URI
               collection</term> described in <xspecref spec="XP31" ref="id-xp-evaluation-context-components"/>.</p><p>If the value of <code>$arg</code> is a relative <code>xs:anyURI</code>, it is resolved
            against the value of the base-URI property from the static context. </p><p>If <code>$arg</code> is the empty sequence, the function behaves as if it had been
            called without an argument. See above.</p><p>The single-argument form of the function returns the sequence of URIs corresponding to
            the supplied URI in the <term>available URI collections</term> described in
               <xspecref spec="XP31" ref="id-xp-evaluation-context-components"/>.</p><p diff="add" at="D">By default, this function is <termref def="deterministic">deterministic</termref>. This
            means that repeated calls on the function with the same argument will return the same
            result. However, for performance reasons, implementations may provide a user option to
            evaluate the function without a guarantee of determinism. The manner in which any such
            option is provided is <termref def="implementation-defined">implementation-defined</termref>. If the user has not
            selected such an option, a call to this function must either return a deterministic
            result or must raise a dynamic error <errorref class="DC" code="0003"/>.</p><p>There is no requirement that the URIs returned by this function should all be distinct,
            and no assumptions can be made about the order of URIs in the sequence, unless the
            implementation defines otherwise.</p></def></gitem><gitem><label>Error Conditions</label><def><p>A dynamic error is raised <errorref class="DC" code="0002"/> if no URI is supplied (that
            is, if the function is called with no arguments, or with a single argument that
            evaluates to an empty sequence), and the value of the default resource collection is
               <xtermref ref="dt-absent" spec="DM31">absent</xtermref>.</p><p diff="add" at="B">A dynamic error is raised <errorref class="DC" code="0002"/> if a relative URI reference
            is supplied, and the base-URI property in the static context is absent.</p><p>A dynamic error is raised <errorref class="DC" code="0002"/> if <term>available resource
               collections</term> provides no mapping for the absolutized URI.</p><p>A dynamic error <phrase diff="chg" at="E"><rfc2119>may</rfc2119> be</phrase> raised <errorref class="DC" code="0004"/> if <code>$arg</code> is not
            a valid <code>xs:anyURI</code>.</p></def></gitem><gitem><label>Notes</label><def><p role="note">In some implementations, there might be a close relationship between <term>collections</term> (as retrieved
         by the <code>fn:collection</code> function), and <term>URI collections</term> (as retrieved by this function).
         For example, a collection might return XML documents, and the corresponding URI collection might return
         the URIs of those documents. However, this specification does not impose such a close relationship. For example, there
         may be collection URIs accepted by one of the two functions and not by the other; a collection might contain
         items that do not have any URI; or a URI collection might contain URIs that cannot be dereferenced to return any 
         resource.</p><p role="note">Thus, some implementations might ensure that calling <code>fn:uri-collection</code> and then
            applying <code>fn:doc</code> to each of the returned URIs delivers the same result as
            calling <code>fn:collection</code> with the same argument; however, this is not
            guaranteed.</p><p role="note">In the case where <code>fn:uri-collection</code> returns the URIs of resources that
            could also be retrieved directly using <code>fn:collection</code>, there are several reasons why it 
            might be appropriate to use this function in preference
            to the <code>fn:collection</code> function. For example:</p><ulist role="note"><item><p>It allows different URIs for different kinds of resource to be dereferenced in
                  different ways: for
                  example, the returned URIs might be referenced using the
                     <code>fn:unparsed-text</code> function rather than the <code>fn:doc</code>
                  function.</p></item><item><p>In XSLT 3.0 it allows the documents in a collection to be processed in streaming mode using the
                     <code>xsl:stream</code> instruction.</p></item><item><p>It allows recovery from failures to read, parse, or validate individual documents,
                  by calling the <code>fn:doc</code> (or other dereferencing) function within the scope of try/catch.</p></item><item><p>It allows selection of which documents to read based on their URI, for example
                  they can be filtered to select those whose URIs end in <code>.xml</code>, or those
                  that use the <code>https</code> scheme.</p></item><item><p>An application might choose to limit the number of URIs processed in a single run,
                  for example it might process only the first 50 URIs in the collection; or it might
                  present the URIs to the user and allow the user to select which of them need to be
                  further processed.</p></item><item><p>It allows the URIs to be modified before they are dereferenced, for example by
                  adding or removing query parameters, or by redirecting the request to a local
                  cache or to a mirror site.</p></item></ulist><p role="note">For some of these use cases, this assumes that the cost of calling
               <code>fn:collection</code> might be significant (for example, it might involving
            retrieving all the documents in the collection over the network and parsing them). This
            will not necessarily be true of all implementations.</p></def></gitem></glist></div3><div3 id="func-unparsed-text"><head>fn:unparsed-text</head><glist><gitem><label>Summary</label><def><p>The <code>fn:unparsed-text</code> function reads an external resource (for example, a
            file) and returns a string representation of the resource.</p></def></gitem><gitem><label>Signatures</label><def><example role="signature"><proto name="unparsed-text" return-type="xs:string?" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="href" type="xs:string?"/></proto></example><example role="signature"><proto name="unparsed-text" return-type="xs:string?" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="href" type="xs:string?"/><arg name="encoding" type="xs:string"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-dependent">context-dependent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>.  It depends on 
		static base URI.
	</p></def></gitem><gitem><label>Rules</label><def><p>The <code>$href</code> argument <rfc2119>must</rfc2119> be a string in the form of a URI
            reference, which <rfc2119>must</rfc2119> contain no fragment identifier, and
               <rfc2119>must</rfc2119> identify a resource for which a string representation is
            available. If the URI is a relative URI reference, then it is resolved relative to the
            <term>static base URI</term> property from the static context.</p><p>The mapping of URIs to the string representation of a resource is the mapping defined in
            the <xtermref spec="XP31" ref="dt-available-text-resources">available text
               resources</xtermref> component of the dynamic context.</p><p>If the value of the <code>$href</code> argument is an empty sequence, the function
            returns an empty sequence.</p><p>The <code>$encoding</code> argument, if present, is the name of an encoding. The values
            for this attribute follow the same rules as for the <code>encoding</code> attribute in
            an XML declaration. The only values which every <termref def="implementation">implementation</termref> is <rfc2119>required</rfc2119> to recognize are
               <code>utf-8</code> and <code>utf-16</code>.</p><p>The encoding of the external resource is determined as follows:</p><olist><item><p>external encoding information is used if available, otherwise</p></item><item><p>if the media type of the resource is <code>text/xml</code> or
                     <code>application/xml</code> (see <bibref ref="rfc2376"/>), or if it matches
                  the conventions <code>text/*+xml</code> or <code>application/*+xml</code> (see
                     <bibref ref="rfc7303"/> and/or its successors), then the encoding is recognized
                  as specified in <bibref ref="xml"/>, otherwise</p></item><item><p>the value of the <code>$encoding</code> argument is used if present, otherwise</p></item><item><p>the processor <rfc2119>may</rfc2119> use <termref def="implementation-defined">implementation-defined</termref> heuristics to determine the likely encoding,
                  otherwise</p></item><item><p>UTF-8 is assumed.</p></item></olist><p>The result of the function is a string containing the string representation of the
            resource retrieved using the URI.</p></def></gitem><gitem><label>Error Conditions</label><def><p>A dynamic error is raised <errorref class="UT" code="1170"/> if <code>$href</code>
            contains a fragment identifier, <phrase diff="add" at="B">or if it cannot be resolved
            to an absolute URI (for example, because the base-URI property in the static context is absent), 
            </phrase>or if it cannot be used to retrieve the string
            representation of a resource. </p><p>A dynamic error is raised <errorref class="UT" code="1190"/> if the value of the
               <code>$encoding</code> argument is not a valid encoding name, if the <termref def="dt-processor">processor</termref> does not support the specified encoding, if
            the string representation of the retrieved resource contains octets that cannot be
            decoded into Unicode <termref def="character">characters</termref> using the specified
            encoding, or if the resulting characters are not permitted XML characters.</p><p>A dynamic error is raised <errorref class="UT" code="1200"/> if <code>$encoding</code>
            is absent and the <termref def="dt-processor">processor</termref> cannot infer the
            encoding using external information and the encoding is not UTF-8.</p></def></gitem><gitem><label>Notes</label><def><p role="note">If it is appropriate to use a base URI other than the dynamic base URI (for example,
            when resolving a relative URI reference read from a source document) then it is
            advisable to resolve the relative URI reference using the <code>fn:resolve-uri</code>
            function before passing it to the <code>fn:unparsed-text</code> function.</p><p role="note">There is no essential relationship between the sets of URIs accepted by the two
            functions <code>fn:unparsed-text</code> and <code>fn:doc</code> (a URI accepted by one
            may or may not be accepted by the other), and if a URI is accepted by both there is no
            essential relationship between the results (different resource representations are
            permitted by the architecture of the web).</p><p role="note">There are no constraints on the MIME type of the resource.</p><p role="note">The fact that the resolution of URIs is defined by a mapping in the dynamic context
            means that in effect, various aspects of the behavior of this function are <termref def="implementation-defined">implementation-defined</termref>. Implementations may provide external configuration
            options that allow any aspect of the processing to be controlled by the user. In
            particular:</p><ulist role="note"><item><p>The set of URI schemes that the implementation recognizes is
                  implementation-defined. Implementations may allow the mapping of URIs to resources
                  to be configured by the user, using mechanisms such as catalogs or user-written
                  URI handlers.</p></item><item><p>The handling of media types is implementation-defined.</p></item><item><p>Implementations may provide user-defined error handling options that allow
                  processing to continue following an error in retrieving a resource, or in reading
                  its content. When errors have been handled in this way, the function may return a
                  fallback document provided by the error handler.</p></item><item><p>Implementations may provide user options that relax the requirement for the
                  function to return deterministic results.</p></item></ulist><p role="note">The rules for determining the encoding are chosen for consistency with <bibref ref="xinclude"/>. Files with an XML media type are treated specially because there
            are use cases for this function where the retrieved text is to be included as unparsed
            XML within a CDATA section of a containing document, and because processors are likely
            to be able to reuse the code that performs encoding detection for XML external
            entities.</p><p role="note">If the text file contains characters such as <code>&lt;</code> and <code>&amp;</code>,
            these will typically be output as <code>&amp;lt;</code> and <code>&amp;amp;</code> if
            the string is serialized as XML or HTML. If these characters actually represent markup
            (for example, if the text file contains HTML), then an XSLT stylesheet can attempt to
            write them as markup to the output file using the <code>disable-output-escaping</code>
            attribute of the <code>xsl:value-of</code> instruction. Note, however, that XSLT
            implementations are not required to support this feature.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>This XSLT example attempts to read a file containing 'boilerplate' HTML and copy it
               directly to the serialized output file:</p><eg xml:space="preserve">&lt;xsl:output method="html"/&gt;

&lt;xsl:template match="/"&gt;
  &lt;xsl:value-of select="unparsed-text('header.html', 'iso-8859-1')"
                disable-output-escaping="yes"/&gt;
  &lt;xsl:apply-templates/&gt;
  &lt;xsl:value-of select="unparsed-text('footer.html', 'iso-8859-1')"
                disable-output-escaping="yes"/&gt;
&lt;/xsl:template&gt;
</eg></def></gitem></glist></div3><div3 id="func-unparsed-text-lines"><head>fn:unparsed-text-lines</head><glist><gitem><label>Summary</label><def><p>The <code>fn:unparsed-text-lines</code> function reads an external resource (for
            example, a file) and returns its contents as a sequence of strings, one for each line of
            text in the string representation of the resource.</p></def></gitem><gitem><label>Signatures</label><def><example role="signature"><proto name="unparsed-text-lines" return-type="xs:string*" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="href" type="xs:string?"/></proto></example><example role="signature"><proto name="unparsed-text-lines" return-type="xs:string*" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="href" type="xs:string?"/><arg name="encoding" type="xs:string"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-dependent">context-dependent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>.  It depends on 
		static base URI.
	</p></def></gitem><gitem><label>Rules</label><def><p>The <code>unparsed-text-lines</code> function reads an external resource (for example, a
            file) and returns its string representation as a sequence of strings, separated at
            newline boundaries. </p><p>The result of the single-argument function is the same as the result of the expression
               <code>fn:tokenize(fn:unparsed-text($href), '\r\n|\r|\n')[not(position()=last() and
               .='')]</code>. The result of the two-argument function is the same as the result of
            the expression <code>fn:tokenize(fn:unparsed-text($href, $encoding),
               '\r\n|\r|\n')[not(position()=last() and .='')]</code>. </p><p>The result is thus a sequence of strings containing the text of the resource retrieved
            using the URI, each string representing one line of text. Lines are separated by one of
            the sequences x0A, x0D, or x0Dx0A. The characters representing the newline are not
            included in the returned strings. If there are two adjacent newline sequences, a
            zero-length string will be returned to represent the empty line; but if the external
            resource ends with the sequence x0A, x0D, or x0Dx0A, the result will be as if this final
            line ending were not present.</p></def></gitem><gitem><label>Error Conditions</label><def><p>Error conditions are the same as for the <code>fn:unparsed-text</code> function.</p></def></gitem><gitem><label>Notes</label><def><p role="note">See the notes for <code>fn:unparsed-text</code>.</p></def></gitem></glist></div3><div3 id="func-unparsed-text-available"><head>fn:unparsed-text-available</head><glist><gitem><label>Summary</label><def><p>Because errors in evaluating the <code>fn:unparsed-text</code> function are
            non-recoverable, these two functions are provided to allow an application to determine
            whether a call with particular arguments would succeed.</p></def></gitem><gitem><label>Signatures</label><def><example role="signature"><proto name="unparsed-text-available" return-type="xs:boolean" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="href" type="xs:string?"/></proto></example><example role="signature"><proto name="unparsed-text-available" return-type="xs:boolean" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="href" type="xs:string?"/><arg name="encoding" type="xs:string"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-dependent">context-dependent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>.  It depends on 
		static base URI.
	</p></def></gitem><gitem><label>Rules</label><def><p>The <code>fn:unparsed-text-available</code> function determines whether a call
            on the <code>fn:unparsed-text</code> function with identical arguments would
            return a string.</p><p>If the first argument is an empty sequence, the function returns false. </p><p>In other cases, the function returns true if a call on
               <code>fn:unparsed-text</code> with the same arguments would succeed, and
            false if a call on <code>fn:unparsed-text</code> with the same arguments would
            fail with a non-recoverable dynamic error.</p><p>The functions <code>fn:unparsed-text</code> and
               <code>fn:unparsed-text-available</code> have the same requirement for
               <termref def="deterministic">determinism</termref> as the functions
               <code>fn:doc</code> and <code>fn:doc-available</code>. This means that unless the
            user has explicitly stated a requirement for a reduced level of determinism, either of
            these functions if called twice with the same arguments during the course of a
            transformation <rfc2119>must</rfc2119> return the same results each time; moreover, the
            results of a call on <code>fn:unparsed-text-available</code>
            <rfc2119>must</rfc2119> be consistent with the results of a subsequent call on
               <code>unparsed-text</code> with the same arguments.</p></def></gitem><gitem><label>Notes</label><def><p role="note">This requires that the <code>fn:unparsed-text-available</code> function should
            actually attempt to read the resource identified by the URI, and check that it is
            correctly encoded and contains no characters that are invalid in XML. Implementations
            may avoid the cost of repeating these checks for example by caching the validated
            contents of the resource, to anticipate a subsequent call on the
               <code>fn:unparsed-text</code> or <code>fn:unparsed-text-lines</code>
            function. Alternatively, implementations may be able to rewrite an expression such as
               <code>if (unparsed-text-available(A)) then unparsed-text(A) else ...</code> to
            generate a single call internally.</p><p role="note">Since the function <code>fn:unparsed-text-lines</code> succeeds or fails under
            exactly the same circumstances as <code>fn:unparsed-text</code>, the
               <code>fn:unparsed-text-available</code> function may equally be used to test
            whether a call on <code>fn:unparsed-text-lines</code> would succeed.</p></def></gitem></glist></div3><div3 id="func-environment-variable"><head>fn:environment-variable</head><glist><gitem><label>Summary</label><def><p>Returns the value of a system environment variable, if it exists.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="environment-variable" return-type="xs:string?" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="name" type="xs:string"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-dependent">context-dependent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>.  It depends on 
		environment variables.
	</p></def></gitem><gitem><label>Rules</label><def><p>The set of available <xtermref spec="XP31" ref="dt-environment-variables">environment
               variables</xtermref> is a set of (name, value) pairs forming part of the dynamic
            context, in which the name is unique within the set of pairs. The name and value are
            arbitrary strings.</p><p>If the <code>$name</code> argument matches the name of one of these pairs, the function
            returns the corresponding value.</p><p>If there is no environment variable with a matching name, the function returns the empty
            sequence.</p><p>The collation used for matching names is <termref def="implementation-defined">implementation-defined</termref>, but
            must be the same as the collation used to ensure that the names of all environment
            variables are unique.</p><p>The function is <termref def="dt-deterministic">deterministic</termref>, which means
            that if it is called several times within the same <termref def="execution-scope">execution scope</termref>, with the same arguments, it must return the same
            result.</p></def></gitem><gitem><label>Notes</label><def><p role="note">On many platforms, the term "environment variable" has a natural meaning in terms of
            facilities provided by the operating system. This interpretation of the concept does not
            exclude other interpretations, such as a mapping to a set of configuration parameters in
            a database system.</p><p role="note">Environment variable names are usually case sensitive. Names are usually of the form
               <code>(letter|_) (letter|_|digit)*</code>, but this varies by platform.</p><p role="note">On some platforms, there may sometimes be multiple environment variables with the same
            name; in this case, it is implementation-dependent as to which is returned; see for
            example <bibref ref="POSIX.1-2008"/> (Chapter 8, Environment Variables). Implementations
               <rfc2119>may</rfc2119> use prefixes or other naming conventions to disambiguate the
            names.</p><p role="note">The requirement to ensure that the function is deterministic means in practice that the
            implementation must make a snapshot of the environment variables at some time during
            execution, and return values obtained from this snapshot, rather than using live values
            that are subject to change at any time.</p><p role="note">Operating system environment variables may be associated with a particular process,
            while queries and stylesheets may execute across multiple processes (or multiple
            machines). In such circumstances implementations <rfc2119>may</rfc2119> choose to
            provide access to the environment variables associated with the process in which the
            query or stylesheet processing was initiated.</p><p role="note">Security advice: Queries from untrusted sources should not be permitted unrestricted
            access to environment variables. For example, the name of the account under which the
            query is running may be useful information to a would-be intruder. An implementation may
            therefore choose to restrict access to the environment, or may provide a facility to
            make <code>fn:environment-variable</code> always return the empty sequence.</p></def></gitem></glist></div3><div3 id="func-available-environment-variables"><head>fn:available-environment-variables</head><glist><gitem><label>Summary</label><def><p>Returns a list of environment variable names that are suitable for passing to
               <code>fn:environment-variable</code>, as a (possibly empty) sequence of strings.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="available-environment-variables" return-type="xs:string*" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"/></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-dependent">context-dependent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>.  It depends on 
		environment variables.
	</p></def></gitem><gitem><label>Rules</label><def><p>The function returns a sequence of strings, being the names of the environment variables
            in the dynamic context in some <termref def="implementation-dependent">implementation-dependent</termref> order.</p><p>The function is <termref def="dt-deterministic">deterministic</termref>: that is, the
            set of available environment variables does not vary during evaluation.</p></def></gitem><gitem><label>Notes</label><def><p role="note">The function returns a list of strings, containing no duplicates.</p><p role="note">It is intended that the strings in this list should be suitable for passing to
               <code>fn:environment-variable</code>.</p><p role="note">See also the note on security under the definition of the
               <code>fn:environment-variable</code> function. If access to environment variables has
            been disabled, <code>fn:available-environment-variables</code> always returns the empty
            sequence.</p></def></gitem></glist></div3></div2><div2 id="parsing-and-serializing"><head>Parsing and serializing</head><p>These functions convert between the lexical representation of XML and the tree representation.</p><table class="index"><thead><tr><th rowspan="1" colspan="1">Function</th><th rowspan="1" colspan="1">Meaning</th></tr></thead><tbody><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:parse-xml</code></td><td rowspan="1" colspan="1">This function takes as input an XML document represented as a string, and returns the
            document node at the root of an XDM tree representing the parsed document.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:parse-xml-fragment</code></td><td rowspan="1" colspan="1">This function takes as input an XML external entity represented as a string, and returns
            the document node at the root of an XDM tree representing the parsed document
            fragment.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:serialize</code></td><td rowspan="1" colspan="1">This function serializes the supplied input sequence <code>$arg</code> as described in
               <bibref ref="xslt-xquery-serialization-31"/>, returning the serialized representation
            of the sequence as a string.</td></tr></tbody></table><div3 id="func-parse-xml"><head>fn:parse-xml</head><glist><gitem><label>Summary</label><def><p>This function takes as input an XML document represented as a string, and returns the
            document node at the root of an XDM tree representing the parsed document.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="parse-xml" return-type="document-node(element(*))?" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg" type="xs:string?"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-nondeterministic">nondeterministic</termref>, <termref def="dt-context-dependent">context-dependent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>.  It depends on 
		static base URI.
	</p></def></gitem><gitem><label>Rules</label><def><p>If <code>$arg</code> is the empty sequence, the function returns the empty sequence.</p><p>The precise process used to construct the XDM instance is <termref def="implementation-defined">implementation-defined</termref>. In particular, it is implementation-defined whether
            DTD and/or schema validation is invoked, and it is implementation-defined whether an XML
            1.0 or XML 1.1 parser is used.</p><p>The <term>static base URI</term> property from the static context of the <code>fn:parse-xml</code>
            function call is used both as the base URI used by the XML parser to resolve relative
            entity references within the document, and as the base URI of the document node that is
            returned.</p><p>The document URI of the returned node is <termref def="absent">absent</termref>.</p><p>The function is <emph>not</emph>
            <termref def="deterministic">deterministic</termref>: that is, if the function is called
            twice with the same arguments, it is <termref def="implementation-dependent">implementation-dependent</termref> whether the same node is returned on both
            occasions.</p></def></gitem><gitem><label>Error Conditions</label><def><p>A dynamic error is raised <errorref class="DC" code="0006"/> if the content of
               <code>$arg</code> is not a well-formed and namespace-well-formed XML document.</p><p>A dynamic error is raised <errorref class="DC" code="0006"/> if DTD-based validation is
            carried out and the content of <code>$arg</code> is not valid against its DTD.</p></def></gitem><gitem><label>Notes</label><def><p role="note">Since the XML document is presented to the parser as a string, rather than as a sequence
            of octets, the encoding specified within the XML declaration has no meaning. If the XML
            parser accepts input only in the form of a sequence of octets, then the processor must
            ensure that the string is encoded as octets in a way that is consistent with rules used
            by the XML parser to detect the encoding.</p><p role="note">The primary use case for this function is to handle input documents that contain nested
            XML documents embedded within CDATA sections. Since the content of the CDATA section are
            exposed as text, the receiving query or stylesheet may pass this text to the
               <code>fn:parse-xml</code> function to create a tree representation of the nested
            document.</p><p role="note">Similarly, nested XML within comments is sometimes encountered, and lexical XML is
            sometimes returned by extension functions, for example, functions that access web
            services or read from databases.</p><p role="note">A use case arises in XSLT where there is a need to preprocess an input document before
            parsing. For example, an application might wish to edit the document to remove its
            DOCTYPE declaration. This can be done by reading the raw text using the
               <code>fn:unparsed-text</code> function, editing the resulting string, and then
            passing it to the <code>fn:parse-xml</code> function.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>fn:parse-xml("&lt;alpha&gt;abcd&lt;/alpha&gt;")</code> returns a newly
               created document node, having an <code>alpha</code> element as its only child; the
                  <code>alpha</code> element in turn is the parent of a text node whose string value
               is <code>"abcd"</code>.</p></def></gitem></glist></div3><div3 id="func-parse-xml-fragment"><head>fn:parse-xml-fragment</head><glist><gitem><label>Summary</label><def><p>This function takes as input an XML external entity represented as a string, and returns
            the document node at the root of an XDM tree representing the parsed document
            fragment.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="parse-xml-fragment" return-type="document-node()?" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg" type="xs:string?"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-nondeterministic">nondeterministic</termref>, <termref def="dt-context-dependent">context-dependent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>.  It depends on 
		static base URI.
	</p></def></gitem><gitem><label>Rules</label><def><p>If <code>$arg</code> is the empty sequence, the function returns the empty sequence.</p><p>The input must be a namespace-well-formed external general parsed entity. More
            specifically, it must be a string conforming to the production rule <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="xml" ref="NT-extParsedEnt" xlink:type="simple">extParsedEnt</xnt> in <bibref ref="xml"/>, it must contain
            no entity references other than references to predefined entities, and it must satisfy
            all the rules of <bibref ref="xml-names"/> for namespace-well-formed documents with
            the exception that the rule requiring it to be a well-formed document is replaced by the
            rule requiring it to be a well-formed external general parsed entity.</p><p>The string is parsed to form a sequence of nodes which become children of the new
            document node, in the same way as the content of any element is converted into a
            sequence of children for the resulting element node.</p><p>Schema validation is <emph>not</emph> invoked, which means that the nodes in the
            returned document will all be untyped.</p><p>The precise process used to construct the XDM instance is <termref def="implementation-defined">implementation-defined</termref>. In particular, it is implementation-defined whether
            an XML 1.0 or XML 1.1 parser is used.</p><p>The <term>static base URI</term> from the static context of the <code>fn:parse-xml-fragment</code>
            function call is used as the base URI of the document node that is returned.</p><p>The document URI of the returned node is <termref def="absent">absent</termref>.</p><p>The function is <emph>not</emph>
            <termref def="deterministic">deterministic</termref>: that is, if the function is called
            twice with the same arguments, it is <termref def="implementation-dependent">implementation-dependent</termref> whether the same node is returned on both
            occasions.</p></def></gitem><gitem><label>Error Conditions</label><def><p>A dynamic error is raised <errorref class="DC" code="0006"/> if the content of
               <code>$arg</code> is not a well-formed external general parsed entity, if it contains
            entity references other than references to predefined entities, or if a document that
            incorporates this well-formed parsed entity would not be namespace-well-formed.</p></def></gitem><gitem><label>Notes</label><def><p role="note">See also the notes for the <code>fn:parse-xml</code> function.</p><p role="note">The main differences between <code>fn:parse-xml</code> and
               <code>fn:parse-xml-fragment</code> are that for <code>fn:parse-xml</code>, the
            children of the resulting document node must contain exactly one element node and no
            text nodes, wheras for <code>fn:parse-xml-fragment</code>, the resulting document node
            can have any number (including zero) of element and text nodes among its children. An
            additional difference is that the <emph>text declaration</emph> at the start of an
            external entity has slightly different syntax from the <emph>XML declaration</emph> at
            the start of a well-formed document.</p><p role="note">Note that all whitespace outside the <emph>text declaration</emph> is significant,
            including whitespace that precedes the first element node.</p><p role="note">One use case for this function is to handle XML fragments stored in databases, which
            frequently allow zero-or-more top level element nodes. Another use case is to parse the
            contents of a <code>CDATA</code> section embedded within another XML document.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression
                  <code>fn:parse-xml-fragment("&lt;alpha&gt;abcd&lt;/alpha&gt;&lt;beta&gt;abcd&lt;/beta&gt;")</code>
               returns a newly created document node, having two elements named <code>alpha</code>
               and <code>beta</code> as its children; each of these elements in turn is the parent
               of a text node.</p><p>The expression <code>fn:parse-xml-fragment("He was &lt;i&gt;so&lt;/i&gt; kind")</code>
               returns a newly created document node having three children: a text node whose string
               value is <code>"He was "</code>, an element node named <code>i</code> having a child
               text node with string value <code>"so"</code>, and a text node whose string value is
                  <code>" kind"</code>.</p><p>The expression <code>fn:parse-xml-fragment("")</code> returns a document node having
               no children.</p><p>The expression <code>fn:parse-xml-fragment(" ")</code> returns a document node whose
               children comprise a single text node whose string value is a single space.</p><p>The expression <code>fn:parse-xml-fragment('&lt;?xml version="1.0" encoding="utf8"
                  standalone="yes"?&gt;&lt;a/&gt;')</code> results in a dynamic error <errorref class="DC" code="0006"/> because the "standalone" keyword is not permitted in the text
               declaration that appears at the start of an external general parsed entity. (Thus, it
               is not the case that any input accepted by the <code>fn:parse-xml</code> function
               will also be accepted by <code>fn:parse-xml-fragment</code>.)</p></def></gitem></glist></div3><div3 id="func-serialize"><head>fn:serialize</head><glist><gitem><label>Summary</label><def><p>This function serializes the supplied input sequence <code>$arg</code> as described in
               <bibref ref="xslt-xquery-serialization-31"/>, returning the serialized representation
            of the sequence as a string.</p></def></gitem><gitem><label>Signatures</label><def><example role="signature"><proto name="serialize" return-type="xs:string" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg" type="item()*"/></proto></example><example role="signature"><proto name="serialize" return-type="xs:string" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arg" type="item()*"/><arg name="params" type="item()?"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>The value of the first argument <code>$arg</code> acts as the input sequence to the serialization process,
            which starts with sequence normalization.</p><p>The second argument <code>$params</code>, if present, provides serialization parameters. These may be supplied in either 
         of two forms:</p><olist><item><p>As an <code>output:serialization-parameters</code>
               element, having the format described in <xspecref spec="SER31" ref="serparams-in-xdm-instance"/>. In this case the type of the supplied
               argument must match the required type <code>element(output:serialization-parameters)</code>.</p></item><item><p diff="add" at="D">As a map. In this case the type of the supplied argument must match the required type <code>map(*)</code></p></item></olist><p>The single-argument version of this function has the same effect as the two-argument
            version called with <code>$params</code> set to an empty sequence. This in turn is the
            same as the effect of passing an <code>output:serialization-parameters</code> element
            with no child elements.</p><p>The final stage of serialization, that is, encoding, is skipped. If the serializer does
            not allow this phase to be skipped, then the sequence of octets returned by the
            serializer is decoded into a string by reversing the character encoding performed in the
            final stage.</p><p>If the second argument is omitted, or is supplied in the form of an <code>output:serialization-parameters</code>
         element, then the values of any serialization parameters that are not explicitly specified is <termref def="implementation-defined">implementation-defined</termref>,
         and may depend on the context.</p><p diff="add" at="D">If the second argument is supplied as a map, then the <termref def="option-parameter-conventions">option parameter conventions</termref>
         apply. In this case:</p><olist diff="add" at="D"><item><p>Each entry in the map defines one serialization parameter.</p></item><item><p>The key of the entry is an <code>xs:string</code> value in the cases of parameter names defined in these specifications, or an
            <code>xs:QName</code> (with non-absent namespace) in the case of implementation-defined serialization parameters.</p></item><item><p>The required type of each parameter, and its default value, are defined by the following table. The default
            value is used when the map contains no entry for the parameter in question, and also when an entry is present, with the
            empty sequence as its value. The table also indicates how the value of the map entry is to be interpreted in cases
            where further explanation is needed.</p></item></olist><table class="no-code-break data"><thead><tr><th rowspan="1" colspan="1">Parameter</th><th rowspan="1" colspan="1">Required type</th><th rowspan="1" colspan="1">Interpretation</th><th rowspan="1" colspan="1">Default Value</th></tr></thead><tbody><tr><td rowspan="1" colspan="1"><code>allow-duplicate-names</code></td><td rowspan="1" colspan="1"><code>xs:boolean?</code></td><td rowspan="1" colspan="1"><code>true()</code> means "yes", <code>false()</code> means "no"</td><td rowspan="1" colspan="1"><code>no</code></td></tr><tr><td rowspan="1" colspan="1"><code>byte-order-mark</code></td><td rowspan="1" colspan="1"><code>xs:boolean?</code></td><td rowspan="1" colspan="1"><code>true()</code> means "yes", <code>false()</code> means "no"</td><td rowspan="1" colspan="1"><code>no</code></td></tr><tr><td rowspan="1" colspan="1"><code>cdata-section-elements</code></td><td rowspan="1" colspan="1"><code>xs:QName*</code></td><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1"><code>()</code></td></tr><tr><td rowspan="1" colspan="1"><code>doctype-public</code></td><td rowspan="1" colspan="1"><code>xs:string?</code></td><td rowspan="1" colspan="1">Zero-length string and <code>()</code> both represent "absent"</td><td rowspan="1" colspan="1">absent</td></tr><tr><td rowspan="1" colspan="1"><code>doctype-system</code></td><td rowspan="1" colspan="1"><code>xs:string?</code></td><td rowspan="1" colspan="1">Zero-length string and <code>()</code> both represent "absent"</td><td rowspan="1" colspan="1">absent</td></tr><tr><td rowspan="1" colspan="1"><code>encoding</code></td><td rowspan="1" colspan="1"><code>xs:string?</code></td><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1"><code>utf-8</code></td></tr><tr><td rowspan="1" colspan="1"><code>escape-uri-attributes</code></td><td rowspan="1" colspan="1"><code>xs:boolean?</code></td><td rowspan="1" colspan="1"><code>true()</code> means "yes", <code>false()</code> means "no"</td><td rowspan="1" colspan="1"><code>yes</code></td></tr><tr><td rowspan="1" colspan="1"><code>html-version</code></td><td rowspan="1" colspan="1"><code>xs:decimal?</code></td><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1"><code>5</code></td></tr><tr><td rowspan="1" colspan="1"><code>include-content-type</code></td><td rowspan="1" colspan="1"><code>xs:boolean?</code></td><td rowspan="1" colspan="1"><code>true()</code> means "yes", <code>false()</code> means "no"</td><td rowspan="1" colspan="1"><code>yes</code></td></tr><tr><td rowspan="1" colspan="1"><code>indent</code></td><td rowspan="1" colspan="1"><code>xs:boolean?</code></td><td rowspan="1" colspan="1"><code>true()</code> means "yes", <code>false()</code> means "no"</td><td rowspan="1" colspan="1"><code>no</code></td></tr><tr><td rowspan="1" colspan="1"><code>item-separator</code></td><td rowspan="1" colspan="1"><code>xs:string?</code></td><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1">absent</td></tr><tr><td rowspan="1" colspan="1"><code>json-node-output-method</code></td><td rowspan="1" colspan="1"><code>union(xs:string, xs:QName)?</code></td><td rowspan="1" colspan="1">See Notes 1, 2</td><td rowspan="1" colspan="1"><code>xml</code></td></tr><tr><td rowspan="1" colspan="1"><code>media-type</code></td><td rowspan="1" colspan="1"><code>xs:string?</code></td><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1">(a media type suitable for the chosen <code>method</code>)</td></tr><tr><td rowspan="1" colspan="1"><code>method</code></td><td rowspan="1" colspan="1"><code>union(xs:string, xs:QName)?</code></td><td rowspan="1" colspan="1">See Notes 1, 2</td><td rowspan="1" colspan="1"><code>xml</code></td></tr><tr><td rowspan="1" colspan="1"><code>normalization-form</code></td><td rowspan="1" colspan="1"><code>xs:string?</code></td><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1"><code>none</code></td></tr><tr><td rowspan="1" colspan="1"><code>omit-xml-declaration</code></td><td rowspan="1" colspan="1"><code>xs:boolean?</code></td><td rowspan="1" colspan="1"><code>true()</code> means "yes", <code>false()</code> means "no"</td><td rowspan="1" colspan="1"><code>yes</code></td></tr><tr><td rowspan="1" colspan="1"><code>standalone</code></td><td rowspan="1" colspan="1"><code>xs:boolean?</code></td><td rowspan="1" colspan="1"><code>true()</code> means "yes", <code>false()</code> means "no", <code>()</code> means "omit"</td><td rowspan="1" colspan="1"><code>omit</code></td></tr><tr><td rowspan="1" colspan="1"><code>suppress-indentation</code></td><td rowspan="1" colspan="1"><code>xs:QName*</code></td><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1"><code>()</code></td></tr><tr><td rowspan="1" colspan="1"><code>undeclare-prefixes</code></td><td rowspan="1" colspan="1"><code>xs:boolean?</code></td><td rowspan="1" colspan="1"><code>true()</code> means "yes", <code>false()</code> means "no"</td><td rowspan="1" colspan="1"><code>no</code></td></tr><tr><td rowspan="1" colspan="1"><code>use-character-maps</code></td><td rowspan="1" colspan="1"><code>map(xs:string, xs:string)?</code></td><td rowspan="1" colspan="1">See Note 3</td><td rowspan="1" colspan="1"><code>map{}</code></td></tr><tr><td rowspan="1" colspan="1"><code>version</code></td><td rowspan="1" colspan="1"><code>xs:string?</code></td><td rowspan="1" colspan="1"/><td rowspan="1" colspan="1"><code>1.0</code></td></tr></tbody></table><p>Notes to the table:</p><olist><item><p>The notation <code>union(A, B)</code> is used to represent a union type whose member types are <code>A</code>
            and <code>B</code>.</p></item><item><p>If an <code>xs:QName</code> is supplied <phrase diff="add" at="E">for the <code>method</code> or <code>json-node-output-method</code> 
               options,</phrase> then it must have a non-absent namespace URI. This
            means that system-defined serialization methods such as <code>xml</code> and <code>json</code>
            are defined as strings, not as <code>xs:QName</code> values.</p></item><item><p><phrase diff="add" at="E">For the <code>use-character-maps</code> option</phrase>, the value is a map, whose keys 
               are the characters to be mapped (as <code>xs:string</code> instances),
            and whose corresponding values are the strings to be substituted for these characters. 
            <phrase diff="del" at="E">The <termref def="option-parameter-conventions">option parameter conventions</termref>
               apply recursively to this nested map.</phrase></p></item></olist></def></gitem><gitem><label>Error Conditions</label><def><p>A type error <xerrorref spec="XP" class="TY" code="0004"/> occurs if the second argument
            is present and does not match either of the types <code>element(output:serialization-parameters)?</code>
         or <code>map(*)</code>.</p><note><p>This is defined as a type error so that it can be enforced via the function signature by implementations
         that generalize the type system in a suitable way.</p></note><p>If the host language makes serialization an optional feature and the implementation does
            not support serialization, then a dynamic error <errorref class="DC" code="0010"/> is
            raised.</p><p>The serialization process will raise an error if <code>$arg</code> is an attribute or
            namespace node.</p><p>When the second argument is supplied as a map, 
            and the supplied value is of the wrong type for the particular parameter, for example if the value of <code>indent</code>
         is a string rather than a boolean, then as defined by the <termref def="option-parameter-conventions">option parameter conventions</termref>,
         a type error <xerrorref spec="XP" class="TY" code="0004"/> is raised. 
         If the value is of the correct type, but does not satisfy the rules for that
         parameter defined in <bibref ref="xslt-xquery-serialization-31"/>, then a dynamic error 
         <xerrorref spec="SER31" class="PM" code="0016"/> is raised. (For example, this occurs if the map supplied to
         <code>use-character-maps</code> includes a key that is a string whose length is not one (1)).</p><p>If any serialization error occurs, including the detection of an invalid value for a
            serialization parameter as described above, this results in the <code>fn:serialize</code> call failing with
            a dynamic error.</p></def></gitem><gitem><label>Notes</label><def><p role="note">One use case for this function arises when there is a need to construct an XML document
            containing nested XML documents within a CDATA section (or on occasions within a
            comment). See <code>fn:parse-xml</code> for further details.</p><p role="note">Another use case arises when there is a need to call an extension function that expects
            a lexical XML document as input.</p><p role="note">There are also use cases where the application wants to post-process the output of a
            query or transformation, for example by adding an internal DTD subset, or by inserting
            proprietary markup delimiters such as the <code>&lt;% ... %&gt;</code> used by some
            templating languages.</p><p role="note">The ability to specify the serialization parameters in an <code>output:serialization-parameters</code>
         element provides backwards compatibility with the 3.0 version of this specification; the ability to
         use a map takes advantage of new features in the 3.1 version. The default parameter values are
         implementation-defined when an <code>output:serialization-parameters</code>
            element is used (or when the argument is omitted), but are fixed by this specification in the
         case where a map (including an empty map) is supplied for the argument.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>Given the variables:</p><eg xml:space="preserve">let $params := 
&lt;output:serialization-parameters 
        xmlns:output="http://www.w3.org/2010/xslt-xquery-serialization"&gt;
  &lt;output:omit-xml-declaration value="yes"/&gt;
&lt;/output:serialization-parameters&gt;
         </eg><eg xml:space="preserve">let $data := 
&lt;a b="3"/&gt;
         </eg><p>The following call might produce the output shown:</p><p>The expression <code>fn:serialize($data, $params)</code> returns <code>'&lt;a b="3"/&gt;'</code>.</p><p>The following call would also produce the output shown (though the second argument could equally well be supplied
               as an empty map (<code>map{}</code>), since both parameters are given their default values):</p><p>The expression <code>fn:serialize($data, map{"method":"xml", "omit-xml-declaration":true()})</code> returns <code>'&lt;a b="3"/&gt;'</code>.</p></def></gitem></glist></div3></div2></div1><div1 id="context"><head>Context functions</head><p>The following functions are defined to obtain information from the 
            static or dynamic context.</p><table class="index"><thead><tr><th rowspan="1" colspan="1">Function</th><th rowspan="1" colspan="1">Meaning</th></tr></thead><tbody><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:position</code></td><td rowspan="1" colspan="1">Returns the context position from the dynamic context.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:last</code></td><td rowspan="1" colspan="1">Returns the context size from the dynamic context.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:current-dateTime</code></td><td rowspan="1" colspan="1">Returns the current date and time (with timezone).</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:current-date</code></td><td rowspan="1" colspan="1">Returns the current date.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:current-time</code></td><td rowspan="1" colspan="1">Returns the current time.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:implicit-timezone</code></td><td rowspan="1" colspan="1">Returns the value of the implicit timezone property from the dynamic context. </td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:default-collation</code></td><td rowspan="1" colspan="1">Returns the value of the default collation property from the static context. </td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:default-language</code></td><td rowspan="1" colspan="1">Returns the value of the default language property from the dynamic context. </td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:static-base-uri</code></td><td rowspan="1" colspan="1">This function returns the value of the <term>static base URI</term> property from the static
            context.</td></tr></tbody></table><div2 id="func-position"><head>fn:position</head><glist><gitem><label>Summary</label><def><p>Returns the context position from the dynamic context.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="position" return-type="xs:integer" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"/></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-dependent">context-dependent</termref>,  and <termref def="dt-focus-dependent">focus-dependent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>Returns the context position from the dynamic context. (See <xspecref spec="XP31" ref="id-xp-evaluation-context-components"/>.)</p></def></gitem><gitem><label>Error Conditions</label><def><p>A dynamic error is raised <xerrorref spec="XP" class="DY" code="0002" type="type"/> if
            the context item is <xtermref ref="dt-absent" spec="DM31">absent</xtermref>.</p></def></gitem></glist></div2><div2 id="func-last"><head>fn:last</head><glist><gitem><label>Summary</label><def><p>Returns the context size from the dynamic context.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="last" return-type="xs:integer" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"/></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-dependent">context-dependent</termref>,  and <termref def="dt-focus-dependent">focus-dependent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>Returns the context size from the dynamic context. (See <xspecref spec="XP31" ref="id-xp-evaluation-context-components"/>.)</p></def></gitem><gitem><label>Error Conditions</label><def><p>A dynamic error is raised <xerrorref spec="XP" class="DY" code="0002" type="type"/> if
            the context <phrase diff="chg" at="D">size</phrase> is <xtermref ref="dt-absent" spec="DM31">absent</xtermref>.</p></def></gitem><gitem><label>Notes</label><def><p role="note">Under most circumstances, the context size is absent only if the context item is absent. However, XSLT 3.0 with
         streaming defines situations in which the context item and context position are known, but the context size is unknown.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>(1 to 20)[fn:last() - 1]</code> returns <code>19</code>.</p></def></gitem></glist></div2><div2 id="func-current-dateTime"><head>fn:current-dateTime</head><glist><gitem><label>Summary</label><def><p>Returns the current date and time (with timezone).</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="current-dateTime" return-type="xs:dateTimeStamp" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"/></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-dependent">context-dependent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>.  It depends on 
		implicit timezone.
	</p></def></gitem><gitem><label>Rules</label><def><p>Returns the current dateTime (with timezone) from the dynamic context. (See <xspecref spec="XP31" ref="id-xp-evaluation-context-components"/>.) This is an
               <code>xs:dateTime</code> that is current at some time during the evaluation of a
            query or transformation in which <code>fn:current-dateTime</code> is executed.</p><p>This function is <termref def="dt-deterministic"/>. The precise instant during the query
            or transformation represented by the value of <code>fn:current-dateTime()</code> is
            <termref def="implementation-dependent">implementation-dependent</termref>.</p><p>If the implementation supports data types from XSD 1.1 then the returned value will be
            an instance of <code>xs:dateTimeStamp</code>. Otherwise, the only guarantees are that it
            will be an instance of <code>xs:dateTime</code> and will have a timezone component.</p></def></gitem><gitem><label>Notes</label><def><p role="note">The returned <code>xs:dateTime</code> will always have an associated timezone, which
            will always be the same as the implicit timezone in the dynamic context</p></def></gitem><gitem><label>Examples</label><def role="example"><p><code>fn:current-dateTime()</code> returns an <code>xs:dateTimeStamp</code>
               corresponding to the current date and time. For example, a call of
                  <code>fn:current-dateTime()</code> might return
                  <code>2004-05-12T18:17:15.125Z</code> corresponding to the current time on May 12,
               2004 in timezone <code>Z</code>. </p></def></gitem></glist></div2><div2 id="func-current-date"><head>fn:current-date</head><glist><gitem><label>Summary</label><def><p>Returns the current date.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="current-date" return-type="xs:date" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"/></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-dependent">context-dependent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>.  It depends on 
		implicit timezone.
	</p></def></gitem><gitem><label>Rules</label><def><p>Returns <code>xs:date(fn:current-dateTime())</code>. This is an <code>xs:date</code>
            (with timezone) that is current at some time during the evaluation of a query or
            transformation in which <code>fn:current-date</code> is executed.</p><p>This function is <termref def="dt-deterministic"/>. The precise instant during the query
            or transformation represented by the value of <code>fn:current-date</code> is <termref def="implementation-dependent">implementation-dependent</termref>.</p></def></gitem><gitem><label>Notes</label><def><p role="note">The returned date will always have an associated timezone, which will always be the same
            as the implicit timezone in the dynamic context</p></def></gitem><gitem><label>Examples</label><def role="example"><p><code>fn:current-date()</code> returns an <code>xs:date</code> corresponding to the
               current date. For example, a call of <code>fn:current-date()</code> might return
                  <code>2004-05-12+01:00</code>. </p></def></gitem></glist></div2><div2 id="func-current-time"><head>fn:current-time</head><glist><gitem><label>Summary</label><def><p>Returns the current time.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="current-time" return-type="xs:time" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"/></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-dependent">context-dependent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>.  It depends on 
		implicit timezone.
	</p></def></gitem><gitem><label>Rules</label><def><p>Returns <code>xs:time(fn:current-dateTime())</code>. This is an <code>xs:time</code>
            (with timezone) that is current at some time during the evaluation of a query or
            transformation in which <code>fn:current-time</code> is executed.</p><p>This function is <termref def="dt-deterministic"/>. The precise instant during the query
            or transformation represented by the value of <code>fn:current-time()</code> is <termref def="implementation-dependent">implementation-dependent</termref>.</p></def></gitem><gitem><label>Notes</label><def><p role="note">The returned time will always have an associated timezone, which will always be the same
            as the implicit timezone in the dynamic context</p></def></gitem><gitem><label>Examples</label><def role="example"><p><code>fn:current-time()</code> returns an <code>xs:time</code> corresponding to the
               current time. For example, a call of <code>fn:current-time()</code> might return
                  <code>23:17:00.000-05:00</code>. </p></def></gitem></glist></div2><div2 id="func-implicit-timezone"><head>fn:implicit-timezone</head><glist><gitem><label>Summary</label><def><p>Returns the value of the implicit timezone property from the dynamic context. </p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="implicit-timezone" return-type="xs:dayTimeDuration" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"/></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-dependent">context-dependent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>.  It depends on 
		implicit timezone.
	</p></def></gitem><gitem><label>Rules</label><def><p>Returns the value of the implicit timezone property from the dynamic context. Components
            of the dynamic context are described in <xspecref spec="XP31" ref="id-xp-evaluation-context-components"/>.</p></def></gitem></glist></div2><div2 id="func-default-collation"><head>fn:default-collation</head><glist><gitem><label>Summary</label><def><p>Returns the value of the default collation property from the static context. </p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="default-collation" return-type="xs:string" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"/></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-dependent">context-dependent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>.  It depends on 
		collations.
	</p></def></gitem><gitem><label>Rules</label><def><p>Returns the value of the default collation property from the static context. Components
            of the static context are described in <xspecref spec="XP31" ref="id-xp-static-context-components"/>.</p></def></gitem><gitem><label>Notes</label><def><p role="note">The default collation property can never be absent. If it is not explicitly defined, a
            system defined default can be invoked. If this is not provided, the Unicode codepoint
            collation (<code>http://www.w3.org/2005/xpath-functions/collation/codepoint</code>) is
            used. </p></def></gitem></glist></div2><div2 id="func-default-language" diff="add" at="D"><head>fn:default-language</head><glist><gitem><label>Summary</label><def><p>Returns the value of the default language property from the dynamic context. </p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="default-language" return-type="xs:language" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"/></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-dependent">context-dependent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>.  It depends on 
		default language.
	</p></def></gitem><gitem><label>Rules</label><def><p>Returns the value of the default language property from the dynamic context. Components
            of the dynamic context are described in <xspecref spec="XP31" ref="eval_context"/>.</p></def></gitem><gitem><label>Notes</label><def><p role="note">The default language property can never be absent. The functions <code>fn:format-integer</code>,
         <code>fn:format-date</code>, <code>fn:format-time</code>, and <code>fn:format-dateTime</code>
         are defined to use the default language if no explicit language is supplied. The default language
         may play a role in selection of a default collation, but this is not a requirement.</p></def></gitem></glist></div2><div2 id="func-static-base-uri"><head>fn:static-base-uri</head><glist><gitem><label>Summary</label><def><p>This function returns the value of the <term>static base URI</term> property from the static
            context.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="static-base-uri" return-type="xs:anyURI?" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"/></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-dependent">context-dependent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>.  It depends on 
		static base URI.
	</p></def></gitem><gitem><label>Rules</label><def><p>The function returns the value of the <term>static base URI</term> property from the static context.
            If the property is absent, the empty sequence is returned.</p><p>Components of the static context are described in <xspecref spec="XP31" ref="static_context"/> .</p></def></gitem><gitem><label>Notes</label><def><p role="note">XQuery 3.0 and XSLT 3.0 give an implementation freedom to use different base URIs during
            the static analysis phase and the dynamic evaluation phase, that is, for compile-time
            and run-time resources respectively. This is appropriate when the implementation allows
            the output of static analysis (a "compiled" query or stylesheet) to be deployed for execution
            to a different location from the one where static analysis took place. In this situation, the
               <code>fn:static-base-uri</code> function should return a URI suitable for locating
            resources needed during dynamic evaluation.</p></def></gitem></glist></div2></div1><div1 id="higher-order-functions"><head>Higher-order functions</head><div2 id="functions-on-functions"><head>Functions on functions</head><p>The functions included in this section operate on function items, that is, values referring to a function.</p><p diff="add" at="D"><termdef id="dt-higher-order" term="higher-order">Functions that accept functions among their arguments,
               or that return functions in their result, are described in this specification as <term>higher-order</term>
               functions.</termdef> Some host languages may exclude higher-order functions from the set of functions
            that they support, or may include such functions in an optional conformance feature.</p><note><p>Some functions such as <code>fn:parse-json</code> allow the option of supplying a callback function
            for example to define exception behavior. Where this is not essential to the use of the function,
            the function has not been classified as higher-order for this purpose; in applications where function items
            cannot be created, these particular options will not be available.</p></note><table class="index"><thead><tr><th rowspan="1" colspan="1">Function</th><th rowspan="1" colspan="1">Meaning</th></tr></thead><tbody><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:function-lookup</code></td><td rowspan="1" colspan="1">Returns the function having a given name and arity, if there is one.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:function-name</code></td><td rowspan="1" colspan="1">Returns the name of the function identified by a function item.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:function-arity</code></td><td rowspan="1" colspan="1">Returns the arity of the function identified by a function item.</td></tr></tbody></table><div3 id="func-function-lookup"><head>fn:function-lookup</head><glist><gitem><label>Summary</label><def><p>Returns the function having a given name and arity, if there is one.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="function-lookup" return-type="function(*)?" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="name" type="xs:QName"/><arg name="arity" type="xs:integer"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-dependent">context-dependent</termref>, <termref def="dt-focus-dependent">focus-dependent</termref>,  and <termref def="dt-higher-order">higher-order</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>A call to <code>fn:function-lookup</code> returns the function obtained by looking up
            the expanded QName supplied as <code>$name</code> and the arity supplied as
               <code>$arity</code> in the named functions component of the dynamic context
            (specifically, the dynamic context of the call to <code>fn:function-lookup</code>).</p><p>Furthermore, if that function has an implementation-dependent implementation (see note
            below), then the implementation of the function returned by
               <code>fn:function-lookup</code> is associated with the static and dynamic context of
            the call to <code>fn:function-lookup</code>.</p><note><p>The above rule deliberately uses the same wording as the corresponding rule for Named
               Function References. The term "a function [with] an implementation-dependent
               implementation" essentially means a function whose implementation is provided by the
               language processor rather than by the stylesheet or query author. This rule is
               therefore relevant to built-in functions and vendor-supplied extension functions
               whose result depends on the context of the function call.</p></note><p>Otherwise (if no known function can be identified by name and arity), an empty sequence
            is returned.</p><p>If the arguments to <code>fn:function-lookup</code> identify a function that is present
            in the static context of the function call, the function will always return the same
            function that a static reference to this function would bind to. If there is no such
            function in the static context, then the results depend on what is present in the
            dynamic context, which is <termref def="implementation-defined">implementation-defined</termref>.</p></def></gitem><gitem><label>Notes</label><def><p role="note">This function can be useful where there is a need to make a dynamic decision on which of
            several statically-known functions to call. It can thus be used as a substitute for
            polymorphism, in the case where the application has been designed so several functions
            implement the same interface.</p><p role="note">The function can also be useful in cases where a query or stylesheet module is written
            to work with alternative versions of a library module. In such cases the author of the
            main module might wish to test whether an imported library module contains or does not
            contain a particular function, and to call a function in that module only if it is
            available in the version that was imported. A static call would cause a static error if
            the function is not available, whereas getting the function using
               <code>fn:function-lookup</code> allows the caller to take fallback action in this
            situation. </p><p role="note">If the function that is retrieved by <code>fn:function-lookup</code> is <termref def="dt-context-dependent">context-dependent</termref>, that is, if it has
            dependencies on the static or dynamic context of its caller, the context that applies is
            the static and/or dynamic context of the call to the <code>fn:function-lookup</code>
            function itself. The context thus effectively forms part of the closure of the returned
            function. In practice this applies only where the target of
               <code>fn:function-lookup</code> is a built-in function, because user-defined
            functions never depend on the static or dynamic context of the function call. The rule
            applies recursively, since <code>fn:function-lookup</code> is itself a context-dependent
            built-in function. </p><p role="note">These specifications do not define any circumstances in which the dynamic context will
            contain functions that are not present in the static context, but neither do they rule
            this out. For example an API <rfc2119>may</rfc2119> provide the ability to add functions
            to the dynamic context. Equally, these specifications do not define any mechanism for
            creating context-dependent functions other than the built-in context-dependent
            functions, but neither do they rule out the existence of such functions. </p><p role="note">The mere fact that a function exists and has a name does not of itself mean that the
         function is present in the dynamic context. For example, functions obtained through
         use of the <code>fn:load-xquery-module</code> function are not added to the dynamic context.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>fn:function-lookup(xs:QName('fn:substring'), 2)('abcd',
                  2)</code> returns <code>'bcd'</code>.</p><p>The expression <code>(fn:function-lookup(xs:QName('xs:dateTimeStamp'), 1),
                  xs:dateTime#1)[1] ('2011-11-11T11:11:11Z')</code> returns an
                  <code>xs:dateTime</code> value set to the specified date, time, and timezone; if
               the implementation supports XSD 1.1 then the result will be an instance of the
               derived type <code>xs:dateTimeStamp</code>. The query is written to ensure that no
               failure occurs when the implementation does not recognize the type
                  <code>xs:dateTimeStamp</code>.</p><p>The expression <code>let $f := fn:function-lookup(xs:QName('zip:binary-entry'), 2)
                  return if (exists($f)) then $f($href, $entry) else ()</code> returns the result of
               calling <code>zip:binary-entry($href, $entry)</code> if the function is available, or
               an empty sequence otherwise.</p></def></gitem></glist></div3><div3 id="func-function-name"><head>fn:function-name</head><glist><gitem><label>Summary</label><def><p>Returns the name of the function identified by a function item.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="function-name" return-type="xs:QName?" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="func" type="function(*)"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>, <termref def="dt-focus-independent">focus-independent</termref>,  and <termref def="dt-higher-order">higher-order</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>If <code>$func</code> refers to a named function, <code>fn:function-name($func)</code>
            returns the name of that function.</p><p>Otherwise (<code>$func</code> refers to an anonymous function),
               <code>fn:function-name($func)</code> returns an empty sequence.</p><p>The prefix part of the returned QName is <termref def="implementation-dependent">implementation-dependent</termref>.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>fn:function-name(fn:substring#2)</code> returns <code>fn:QName("http://www.w3.org/2005/xpath-functions",
                  "fn:substring")</code>. <emph>(The namespace prefix of the returned QName is not
                  predictable.)</emph></p><p>The expression <code>fn:function-name(function($node){count($node/*)})</code> returns <code>()</code>.</p></def></gitem></glist></div3><div3 id="func-function-arity"><head>fn:function-arity</head><glist><gitem><label>Summary</label><def><p>Returns the arity of the function identified by a function item.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="function-arity" return-type="xs:integer" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="func" type="function(*)"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>, <termref def="dt-focus-independent">focus-independent</termref>,  and <termref def="dt-higher-order">higher-order</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>The <code>fn:function-arity</code> function returns the arity (number of arguments) of
            the function identified by <code>$func</code>.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>fn:function-arity(fn:substring#2)</code> returns <code>2</code>.</p><p>The expression <code>fn:function-arity(function($node){name($node)})</code> returns <code>1</code>.</p><p>The expression <code>let $initial := fn:substring(?, 1, 1) return
                  fn:function-arity($initial)</code> returns <code>1</code>.</p></def></gitem></glist></div3></div2><div2 id="basic-hofs"><head>Basic higher-order functions</head><p>The following functions take function items as an argument.</p><table class="index"><thead><tr><th rowspan="1" colspan="1">Function</th><th rowspan="1" colspan="1">Meaning</th></tr></thead><tbody><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:for-each</code></td><td rowspan="1" colspan="1">Applies the function item <var>$action</var> to every item from the sequence <var>$seq</var>
            in turn, returning the concatenation of the resulting sequences in order.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:filter</code></td><td rowspan="1" colspan="1">Returns those items from the sequence <var>$seq</var> for which the supplied function
               <var>$f</var> returns true.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:fold-left</code></td><td rowspan="1" colspan="1">Processes the supplied sequence from left to right, applying the supplied function
            repeatedly to each item in turn, together with an accumulated result value.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:fold-right</code></td><td rowspan="1" colspan="1">Processes the supplied sequence from right to left, applying the supplied function
            repeatedly to each item in turn, together with an accumulated result value.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:for-each-pair</code></td><td rowspan="1" colspan="1">Applies the function item <var>$action</var> to successive pairs of items taken one from
               <var>$seq1</var> and one from <var>$seq2</var>, returning the concatenation of the
            resulting sequences in order.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:sort</code></td><td rowspan="1" colspan="1">Sorts a supplied sequence, based on the value of a sort key supplied as a function.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:apply</code></td><td rowspan="1" colspan="1">Makes a dynamic call on a function with an argument list supplied in the form of an array.</td></tr></tbody></table><p diff="add" at="E">With all these functions, if the caller-supplied function fails with a dynamic error,
            this error is propagated as an error from the higher-order function itself.</p><div3 id="func-for-each"><head>fn:for-each</head><glist><gitem><label>Summary</label><def><p>Applies the function item <var>$action</var> to every item from the sequence <var>$seq</var>
            in turn, returning the concatenation of the resulting sequences in order.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="for-each" return-type="item()*" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="seq" type="item()*"/><arg name="action" type="function(item()) as item()*"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>, <termref def="dt-focus-independent">focus-independent</termref>,  and <termref def="dt-higher-order">higher-order</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>The effect of the function is equivalent to the following implementation in XQuery:</p><eg xml:space="preserve">
declare function fn:for-each($seq, $action) {
  if (fn:empty($seq))
  then ()
  else ($action(fn:head($seq)), fn:for-each(fn:tail($seq), $action))
};</eg><p>or its equivalent in XSLT:</p><eg xml:space="preserve">
&lt;xsl:function name="fn:for-each"&gt;
  &lt;xsl:param name="seq"/&gt;
  &lt;xsl:param name="action"/&gt;
  &lt;xsl:if test="fn:exists($seq)"&gt;
    &lt;xsl:sequence select="$action(fn:head($seq)), fn:for-each(fn:tail($seq), $action)"/&gt;
  &lt;/xsl:if&gt;
&lt;/xsl:function&gt;
         </eg></def></gitem><gitem><label>Notes</label><def><p role="note">The function call <code>fn:for-each($SEQ, $F)</code> is equivalent to the expression
               <code>for $i in $SEQ return $F($i)</code>, assuming that ordering mode is
               <code>ordered</code>.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>fn:for-each(1 to 5, function($a) { $a * $a })</code> returns <code>(1, 4, 9, 16, 25)</code>.</p><p>The expression <code>fn:for-each(("john", "jane"),
                  fn:string-to-codepoints#1)</code> returns <code>(106, 111, 104, 110, 106, 97, 110, 101)</code>.</p><p>The expression <code>fn:for-each(("23", "29"), xs:int#1)</code> returns <code>(23, 29)</code>.</p></def></gitem></glist></div3><div3 id="func-filter"><head>fn:filter</head><glist><gitem><label>Summary</label><def><p>Returns those items from the sequence <var>$seq</var> for which the supplied function
               <var>$f</var> returns true.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="filter" return-type="item()*" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="seq" type="item()*"/><arg name="f" type="function(item()) as xs:boolean"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>, <termref def="dt-focus-independent">focus-independent</termref>,  and <termref def="dt-higher-order">higher-order</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>The effect of the function is equivalent to the following implementation in XQuery:</p><eg xml:space="preserve">
declare function fn:filter(
        $seq as item()*,
        $f as function(item()) as xs:boolean)
        as item()* {
  if (fn:empty($seq))
  then ()
  else ( fn:head($seq)[$f(.) eq fn:true()], 
         fn:filter(fn:tail($seq), $f)
       )
};</eg><p>or its equivalent in XSLT:</p><eg xml:space="preserve">
&lt;xsl:function name="fn:filter" as="item()*"&gt;
  &lt;xsl:param name="seq" as="item()*"/&gt;
  &lt;xsl:param name="f" as="function(item()) as xs:boolean"/&gt;
  &lt;xsl:if test="fn:exists($seq)"&gt;
    &lt;xsl:sequence select="fn:head($seq)[$f(.) eq fn:true()], fn:filter(fn:tail($seq), $f)"/&gt;
  &lt;/xsl:if&gt;
&lt;/xsl:function&gt;
         </eg></def></gitem><gitem><label>Error Conditions</label><def><p>As a consequence of the function signature and the function calling rules, a type error
            occurs if the supplied function <var>$f</var> returns anything other than a single
               <code>xs:boolean</code> item; there is no conversion to an effective boolean
            value.</p></def></gitem><gitem><label>Notes</label><def><p role="note">The function call <code>fn:filter($SEQ, $F)</code> has a very similar effect to the
            expression <code>$SEQ[$F(.)]</code>. There are some differences, however. In the case of
               <code>fn:filter</code>, the function <code>$F</code> is required to return a boolean;
            there is no special treatment for numeric predicate values, and no conversion to an
            effective boolean value. Also, with a filter expression <code>$SEQ[$F(.)]</code>, the
            focus within the predicate is different from that outside; this means that the use of a
            context-sensitive function such as <code>fn:lang#1</code> will give different results in
            the two cases.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>fn:filter(1 to 10, function($a) {$a mod 2 = 0})</code> returns <code>(2, 4, 6, 8, 10)</code>.</p><p>The expression <code>fn:filter((), fn:lang("en", ?))</code> returns <code>()</code>.</p></def></gitem></glist></div3><div3 id="func-fold-left"><head>fn:fold-left</head><glist><gitem><label>Summary</label><def><p>Processes the supplied sequence from left to right, applying the supplied function
            repeatedly to each item in turn, together with an accumulated result value.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="fold-left" return-type="item()*" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="seq" type="item()*"/><arg name="zero" type="item()*"/><arg name="f" type="function(item()*, item()) as item()*"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>, <termref def="dt-focus-independent">focus-independent</termref>,  and <termref def="dt-higher-order">higher-order</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>The effect of the function is equivalent to the following implementation in XQuery:</p><eg xml:space="preserve">
declare function fn:fold-left(
        $seq as item()*,
        $zero as item()*,
        $f as function(item()*, item()) as item()*) 
        as item()* {
  if (fn:empty($seq))
  then $zero
  else fn:fold-left(fn:tail($seq), $f($zero, fn:head($seq)), $f)
};</eg><p>or its equivalent in XSLT:</p><eg xml:space="preserve">
&lt;xsl:function name="fn:fold-left" as="item()*"&gt;
  &lt;xsl:param name="seq" as="item()*"/&gt;
  &lt;xsl:param name="zero" as="item()*"/&gt;
  &lt;xsl:param name="f" as="function(item()*, item()) as item()*"/&gt;
  &lt;xsl:choose&gt;
    &lt;xsl:when test="fn:empty($seq)"&gt;
      &lt;xsl:sequence select="$zero"/&gt;
    &lt;/xsl:when&gt;
    &lt;xsl:otherwise&gt;
      &lt;xsl:sequence select="fn:fold-left(fn:tail($seq), $f($zero, fn:head($seq)), $f)"/&gt;
    &lt;/xsl:otherwise&gt;
  &lt;/xsl:choose&gt;
&lt;/xsl:function&gt;
         </eg></def></gitem><gitem><label>Error Conditions</label><def><p>As a consequence of the function signature and the function calling rules, a type error
            occurs if the supplied function <var>$f</var> cannot be applied to two arguments, where
            the first argument is either the value of <var>$zero</var> or the result of a previous
            application of <var>$f</var>, and the second 
            <phrase diff="chg" at="B-bug26173">is any single item from the sequence <var>$seq</var></phrase>.</p></def></gitem><gitem><label>Notes</label><def><p role="note">This operation is often referred to in the functional programming literature as
            "folding" or "reducing" a sequence. It takes a function that operates on a pair of
            values, and applies it repeatedly, with an accumulated result as the first argument, and
            the next item in the sequence as the second argument. The accumulated result is
            initially set to the value of the <var>$zero</var> argument, which is conventionally a
            value (such as zero in the case of addition, one in the case of multiplication, or a
            zero-length string in the case of string concatenation) that causes the function to
            return the value of the other argument unchanged.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>fn:fold-left(1 to 5, 0, function($a, $b) { $a + $b
                  })</code> returns <code>15</code>. <emph>(This returns the sum of the items in the sequence).</emph></p><p>The expression <code>fn:fold-left((2,3,5,7), 1, function($a, $b) { $a * $b
                  })</code> returns <code>210</code>. <emph>(This returns the product of the items in the sequence).</emph></p><p>The expression <code>fn:fold-left((true(), false(), false()), false(), function($a, $b) {
                  $a or $b })</code> returns <code>true()</code>. <emph>(This returns true if any item in the sequence has an effective boolean
                  value of true).</emph></p><p>The expression <code>fn:fold-left((true(), false(), false()), false(), function($a, $b) {
                  $a and $b })</code> returns <code>false()</code>. <emph>(This returns true only if every item in the sequence has an effective
                  boolean value of true).</emph></p><p>The expression <code>fn:fold-left(1 to 5, (), function($a, $b) {($b,
                  $a)})</code> returns <code>(5,4,3,2,1)</code>. <emph>(This reverses the order of the items in a sequence).</emph></p><p>The expression <code>fn:fold-left(1 to 5, "", fn:concat(?, ".", ?))</code> returns <code>".1.2.3.4.5"</code>.</p><p>The expression <code>fn:fold-left(1 to 5, "$zero", fn:concat("$f(", ?, ", ", ?, ")"))</code> returns <code>"$f($f($f($f($f($zero, 1), 2), 3), 4), 5)"</code>.</p><p>The expression <code>fn:fold-left(1 to 5, map{}, function($map, $n) {map:put($map, $n, $n*2)})</code> returns <code>map{1:2, 2:4, 3:6, 4:8, 5:10}</code>.</p></def></gitem></glist></div3><div3 id="func-fold-right"><head>fn:fold-right</head><glist><gitem><label>Summary</label><def><p>Processes the supplied sequence from right to left, applying the supplied function
            repeatedly to each item in turn, together with an accumulated result value.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="fold-right" return-type="item()*" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="seq" type="item()*"/><arg name="zero" type="item()*"/><arg name="f" type="function(item(), item()*) as item()*"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>, <termref def="dt-focus-independent">focus-independent</termref>,  and <termref def="dt-higher-order">higher-order</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>The effect of the function is equivalent to the following implementation in XQuery:</p><eg xml:space="preserve">
declare function fn:fold-right(
        $seq as item()*, 
        $zero as item()*, 
        $f as function(item(), item()*) as item()*) 
        as item()* {
  if (fn:empty($seq))
  then $zero
  else $f(fn:head($seq), fn:fold-right(fn:tail($seq), $zero, $f))
};</eg><p>or its equivalent in XSLT:</p><eg xml:space="preserve">
&lt;xsl:function name="fn:fold-right" as="item()*"&gt;
  &lt;xsl:param name="seq" as="item()*"/&gt;
  &lt;xsl:param name="zero" as="item()*"/&gt;
  &lt;xsl:param name="f" as="function(item(), item()*) as item()*"/&gt;
  &lt;xsl:choose&gt;
    &lt;xsl:when test="fn:empty($seq)"&gt;
      &lt;xsl:sequence select="$zero"/&gt;
    &lt;/xsl:when&gt;
    &lt;xsl:otherwise&gt;
      &lt;xsl:sequence select="$f(fn:head($seq), fn:fold-right(fn:tail($seq), $zero, $f))"/&gt;
    &lt;/xsl:otherwise&gt;
  &lt;/xsl:choose&gt;
&lt;/xsl:function&gt;
         </eg></def></gitem><gitem><label>Error Conditions</label><def><p>As a consequence of the function signature and the function calling rules, a type error
            occurs if the supplied function <var>$f</var> cannot be applied to two arguments, where
            the first argument is any item in the sequence <var>$seq</var>, and the second is either
            the value of <var>$zero</var> or the result of a previous application of
            <var>$f</var>.</p></def></gitem><gitem><label>Notes</label><def><p role="note">This operation is often referred to in the functional programming literature as
            "folding" or "reducing" a sequence. It takes a function that operates on a pair of
            values, and applies it repeatedly, with the next item in the sequence as the first
            argument, and the result of processing the remainder of the sequence as the second
            argument. The accumulated result is initially set to the value of the <var>$zero</var>
            argument, which is conventionally a value (such as zero in the case of addition, one in
            the case of multiplication, or a zero-length string in the case of string concatenation)
            that causes the function to return the value of the other argument unchanged.</p><p role="note">In cases where the function performs an associative operation on its two arguments (such
            as addition or multiplication), <code>fn:fold-right</code> produces the same result as
               <code>fn:fold-left</code>.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>fn:fold-right(1 to 5, 0, function($a, $b) { $a + $b
                  })</code> returns <code>15</code>. <emph>(This returns the sum of the items in the sequence).</emph></p><p>The expression <code>fn:fold-right(1 to 5, "", fn:concat(?, ".", ?))</code> returns <code>"1.2.3.4.5."</code>.</p><p>The expression <code>fn:fold-right(1 to 5, "$zero", concat("$f(", ?, ", ", ?,
                  ")"))</code> returns <code>"$f(1, $f(2, $f(3, $f(4, $f(5, $zero)))))"</code>.</p></def></gitem></glist></div3><div3 id="func-for-each-pair"><head>fn:for-each-pair</head><glist><gitem><label>Summary</label><def><p>Applies the function item <var>$action</var> to successive pairs of items taken one from
               <var>$seq1</var> and one from <var>$seq2</var>, returning the concatenation of the
            resulting sequences in order.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="for-each-pair" return-type="item()*" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="seq1" type="item()*"/><arg name="seq2" type="item()*"/><arg name="action" type="function(item(), item()) as item()*"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>, <termref def="dt-focus-independent">focus-independent</termref>,  and <termref def="dt-higher-order">higher-order</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>The effect of the function is equivalent to the following implementation in XQuery:</p><eg xml:space="preserve">
declare function fn:for-each-pair($seq1, $seq2, $action)
{
   if(fn:exists($seq1) and fn:exists($seq2)) 
   then (
     $action(fn:head($seq1), fn:head($seq2)),
     fn:for-each-pair(fn:tail($seq1), fn:tail($seq2), $action)
   )
   else ()
};</eg><p>or its equivalent in XSLT:</p><eg xml:space="preserve">
&lt;xsl:function name="fn:for-each-pair"&gt;
  &lt;xsl:param name="seq1"/&gt;
  &lt;xsl:param name="seq2"/&gt;
  &lt;xsl:param name="action"/&gt;
  &lt;xsl:if test="fn:exists($seq1) and fn:exists($seq2)"&gt;
    &lt;xsl:sequence select="$action(fn:head($seq1), fn:head($seq2))"/&gt;
    &lt;xsl:sequence select="fn:for-each-pair(fn:tail($seq1), fn:tail($seq2), $action)"/&gt;
  &lt;/xsl:if&gt;
&lt;/xsl:function&gt;
         </eg></def></gitem><gitem><label>Notes</label><def><p role="note">If one sequence is longer than the other, excess items in the longer sequence are ignored.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>fn:for-each-pair(("a", "b", "c"), ("x", "y", "z"),
                  concat#2)</code> returns <code>("ax", "by", "cz")</code>.</p><p>The expression <code>fn:for-each-pair(1 to 5, 1 to 5, function($a, $b){10*$a + $b})</code> returns <code>(11, 22, 33, 44, 55)</code>.</p><p>The expression <code>let $s := 1 to 8 return fn:for-each-pair($s, tail($s), function($a, $b){$a*$b})</code> returns <code>(2, 6, 12, 20, 30, 42, 56)</code>.</p></def></gitem></glist></div3><div3 id="func-sort" diff="add" at="B"><head>fn:sort</head><glist><gitem><label>Summary</label><def><p>Sorts a supplied sequence, based on the value of a sort key supplied as a function.</p></def></gitem><gitem><label>Signatures</label><def><example role="signature"><proto name="sort" return-type="item()*" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="input" type="item()*"/></proto></example><example role="signature"><proto name="sort" return-type="item()*" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="input" type="item()*"/><arg name="collation" type="xs:string?"/></proto></example><example role="signature"><proto name="sort" return-type="item()*" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="input" type="item()*"/><arg name="collation" type="xs:string?"/><arg name="key" type="function(item()) as xs:anyAtomicType*"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>The one-argument form of this function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-dependent">context-dependent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>.  It depends on 
		collations.
	</p><p>The two-argument form of this function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-dependent">context-dependent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>.  It depends on 
		collations.
	</p><p>The three-argument form of this function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-dependent">context-dependent</termref>, <termref def="dt-focus-independent">focus-independent</termref>,  and <termref def="dt-higher-order">higher-order</termref>.  It depends on 
		collations.
	</p></def></gitem><gitem><label>Rules</label><def><p>Calling the single-argument version of the function is equivalent to calling the two-argument form
         with <code>default-collation()</code> as the second argument: that is, it sorts a sequence of items according
         to the typed value of the items, using the default collation to compare strings.</p><p>Calling the two-argument version of the function is equivalent to calling the three-argument form
            with <code>fn:data#1</code> as the third argument: that is, it sorts a sequence of items according
            to the typed value of the items, using a specified collation to compare strings.</p><p>In the case of both <code>fn:sort#2</code> and <code>fn:sort#3</code>, supplying an empty
         sequence as the second argument is equivalent to supplying <code>fn:default-collation()</code>. For more
         information on collations see <specref ref="choosing-a-collation"/>.</p><p>The result of the function is obtained as follows:</p><ulist><item><p>For each item in the sequence <code>$input</code>, the function supplied as <code>$key</code> 
               is evaluated with that item as its argument. 
               The resulting values are the sort keys of the items in the input sequence.
            </p></item><item><p>The result sequence contains the same items as the input sequence <code>$input</code>, but generally in a different order.</p></item><item><p>Let <var>$C</var> be the selected collation, or the default collation where applicable.</p></item><item><p>The order of items in the result is such that, given two items <code>$A</code> and <code>$B</code>:</p><ulist><item><p>If <code>(fn:deep-equal($key($A), $key($B), $C)</code>, then the relative order of <code>$A</code> and <code>$B</code> 
                  in the output is the same as their relative order in the input (that is, the sort is stable)
               </p></item><item><p>Otherwise, if <code>(deep-less-than($key($A), $key($B), $C)</code>, then <code>$A</code> precedes <code>$B</code> in the output. 
                  The function <code>deep-less-than</code> is defined as the boolean result of the expression:
               </p><eg diff="chg" at="D" xml:space="preserve"><code>if (fn:empty($A)) 
     then fn:exists($B)
else if (fn:deep-equal($A[1], $B[1], $C)) 
     then deep-less-than(fn:tail($A), fn:tail($B), $C)
else if ($A[1] ne $A[1] (:that is, $A[1] is NaN:)) 
     then fn:true()
else if (is-string($A[1]) and is-string($B[1]) 
     then fn:compare($A[1], $B[1], $C) lt 0
else $A[1] lt $B[1]</code></eg><p>where the function <code>is-string($X)</code> returns true if and only if <code>$X</code> is an instance of 
                     <code>xs:string</code>, <code>xs:anyURI</code>, or <code>xs:untypedAtomic</code>.</p><p>This ordering of sequences is referred to by mathematicians as "lexicographic ordering".
                  </p></item></ulist></item></ulist></def></gitem><gitem><label>Error Conditions</label><def><p>If the set of computed sort keys contains values that are not comparable using the <code>lt</code> operator then the sort 
            operation will fail with a type error (<xerrorref spec="XP" class="TY" code="0004"/>).
         </p></def></gitem><gitem><label>Notes</label><def><p role="note">XSLT and XQuery both provide native sorting capability, but previous releases of XPath provided no sorting functionality
         for use in standalone environments.</p><p role="note">In addition there are cases where this function may be more flexible than the built-in sorting capability for XQuery or XSLT,
         for example when the sort key or collation is chosen dynamically, or when the sort key is a sequence of items rather than a single
         item.</p><p role="note">The results are compatible with the results of XSLT sorting (using <code>xsl:sort</code>) in the case where the sort key evaluates to a sequence of
         length zero or one, given the options <code>stable="yes"</code> and <code>order="ascending"</code>.</p><p role="note">The results are compatible with the results of XQuery sorting (using the <code>order by</code> clause) in the case where the sort key evaluates to a sequence of
            length zero or one, given the options <code>stable</code>, <code>ascending</code>, and <code>empty least</code>.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>fn:sort((1, 4, 6, 5, 3))</code> returns <code>(1, 3, 4, 5, 6)</code>.</p><p>The expression <code>fn:sort((1, -2, 5, 10, -10, 10, 8), (), fn:abs#1)</code> returns <code>(1, -2, 5, 8, 10, -10, 10)</code>.</p><p>To sort a set of strings <code>$in</code> using Swedish collation:</p><eg xml:space="preserve">
let $SWEDISH := "http://www.w3.org/2013/collation/UCA?lang=se"
return fn:sort($in, $SWEDISH)
            </eg><p>To sort a sequence of employees by last name as the major sort key and first name as the minor sort key,
               using the default collation:
            </p><eg xml:space="preserve">fn:sort($employees, (), function($emp) {$emp/name ! (last, first)})</eg></def></gitem></glist></div3><div3 id="func-apply" diff="add" at="C"><head>fn:apply</head><glist><gitem><label>Summary</label><def><p>Makes a dynamic call on a function with an argument list supplied in the form of an array.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="apply" return-type="item()*" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="function" type="function(*)"/><arg name="array" type="array(*)"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>, <termref def="dt-focus-independent">focus-independent</termref>,  and <termref def="dt-higher-order">higher-order</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>The result of the function is obtained by invoking the supplied function <code>$function</code> with arguments
         taken from the members of the supplied array <code>$array</code>. The first argument of the function call is the first
         member of <code>$array</code>, the second argument is the second member of <code>$array</code>, and so on.</p><p>The arity of the supplied function <code>$function</code> must be the same as the size of the array <code>$array</code>.</p><p>The effect of calling <code>fn:apply($f, [$a, $b, $c, ...])</code> is the same as the effect of the dynamic function call 
            <code>$f($a, $b, $c, ....)</code>. For example, the function conversion rules are applied to the supplied arguments
            in the usual way.</p></def></gitem><gitem><label>Error Conditions</label><def><p>A dynamic error is raised if the arity of the function <code>$function</code> is not the same as the size of the
            array <code>$array</code> (<errorref spec="FO" class="AP" code="0001"/>).
         </p></def></gitem><gitem><label>Notes</label><def><p role="note">The function is useful where the arity of a function item is not known statically.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>fn:apply(fn:concat#3, ["a", "b", "c"])</code> returns <code>"abc"</code>.</p><p>The expression <code>fn:apply($f, array:subarray(["a", "b", "c", "d", "e", "f"], 1, fn:function-arity($f)))</code> 
               calls the supplied function <code>$f</code> supplying the number of arguments required by its arity.</p></def></gitem></glist></div3></div2><div2 id="dynamic-loading" diff="add" at="B"><head>Dynamic Loading</head><p>The following functions allow dynamic loading and execution of XQuery queries and XSLT stylesheets.</p><table class="index"><thead><tr><th rowspan="1" colspan="1">Function</th><th rowspan="1" colspan="1">Meaning</th></tr></thead><tbody><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:load-xquery-module</code></td><td rowspan="1" colspan="1">Provides access to the public functions and global variables of a dynamically-loaded XQuery library module.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:transform</code></td><td rowspan="1" colspan="1">Invokes a transformation using a dynamically-loaded XSLT stylesheet.</td></tr></tbody></table><div3 id="func-load-xquery-module"><head>fn:load-xquery-module</head><glist><gitem><label>Summary</label><def><p>Provides access to the public functions and global variables of a dynamically-loaded XQuery library module.</p></def></gitem><gitem><label>Signatures</label><def><example role="signature"><proto name="load-xquery-module" return-type="map(*)" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="module-uri" type="xs:string"/></proto></example><example role="signature"><proto name="load-xquery-module" return-type="map(*)" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="module-uri" type="xs:string"/><arg name="options" type="map(*)"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-dependent">context-dependent</termref>, <termref def="dt-focus-independent">focus-independent</termref>,  and <termref def="dt-higher-order">higher-order</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>The function loads an implementation-defined set of modules having the target namespace <code>$module-uri</code>.</p><p>Calling the one-argument version of the function has the same effect as calling the two-argument version with an empty map
            as the second argument.</p><p diff="chg" at="D">The <code>$options</code> argument can be used to control the way in which the function operates. 
            The <termref def="option-parameter-conventions">option parameter conventions</termref> apply.</p><table style="border-collapse: collapse"><thead><tr style="border-top: 2px solid black; border-bottom: 2px solid black"><th style="text-align:left; padding-right: 10px; " rowspan="1" colspan="1">Key</th><th style="text-align:left" rowspan="1" colspan="1">Meaning</th></tr></thead><tbody><tr><td style="white-space:nowrap; padding-right: 10px; vertical-align:top; border-bottom: 2px solid black" rowspan="1" colspan="1"><code>xquery-version</code></td><td style="vertical-align:top; border-bottom: 2px solid black" rowspan="1" colspan="1">The minimum level of the XQuery language that the
                  processor must support. <ulist><item><p><term>Type: </term><code>xs:decimal</code></p></item><item><p><term>Default: </term><code>The version given in the prolog of the library module; or
                  implementation-defined if this is absent.</code></p></item></ulist></td></tr><tr><td style="white-space:nowrap; padding-right: 10px; vertical-align:top; border-bottom: 2px solid black" rowspan="1" colspan="1"><code>location-hints</code></td><td style="vertical-align:top; border-bottom: 2px solid black" rowspan="1" colspan="1">A sequence of URIs (in the form of <code>xs:string</code> values) which may be used or ignored in an
                  <termref def="implementation-defined">implementation-defined</termref> way.<ulist><item><p><term>Type: </term><code>xs:string*</code></p></item><item><p><term>Default: </term><code>Empty sequence</code></p></item></ulist></td></tr><tr><td style="white-space:nowrap; padding-right: 10px; vertical-align:top; border-bottom: 2px solid black" rowspan="1" colspan="1"><code>context-item</code></td><td style="vertical-align:top; border-bottom: 2px solid black" rowspan="1" colspan="1">The item to be used as the initial context item when evaluating global variables in the library module. Supplying
                  an empty sequence is equivalent to omitting the entry from the map, and indicates the absence of a context item.
                  If the library module specifies a required type for the context item, then the supplied value <rfc2119>must</rfc2119> conform to
                  this type, without conversion.<ulist><item><p><term>Type: </term><code>item()?</code></p></item><item><p><term>Default: </term><code>Absent</code></p></item></ulist></td></tr><tr><td style="white-space:nowrap; padding-right: 10px; vertical-align:top; border-bottom: 2px solid black" rowspan="1" colspan="1"><code>variables</code></td><td style="vertical-align:top; border-bottom: 2px solid black" rowspan="1" colspan="1">Values for external variables defined in the library module. Values <rfc2119>must</rfc2119> be supplied
                  for external variables that have no default value, and <rfc2119>may</rfc2119> be supplied for external variables
                  that do have a default value. The supplied value <rfc2119>must</rfc2119> conform to the required type of the variable, without conversion.
                  The map contains one entry for each external variable: the key is the variable's name, and the associated value is
                  the variable's value. The <termref def="option-parameter-conventions">option parameter conventions</termref> do not apply
                  to this contained map.<ulist><item><p><term>Type: </term><code>map(xs:QName, item()*)</code></p></item><item><p><term>Default: </term><code>An empty map</code></p></item></ulist></td></tr><tr><td style="white-space:nowrap; padding-right: 10px; vertical-align:top; border-bottom: 2px solid black" rowspan="1" colspan="1"><code>vendor-options</code></td><td style="vertical-align:top; border-bottom: 2px solid black" rowspan="1" colspan="1">Values for vendor-defined configuration options for the XQuery processor used to process the request. The key is the
                  name of an option, expressed as a QName: the namespace URI of the QName <rfc2119>should</rfc2119> be a URI controlled
                  by the vendor of the XQuery processor. The meaning of the associated value is <termref def="implementation-defined">implementation-defined</termref>.
                  Implementations <rfc2119>should</rfc2119> ignore options whose names are in an unrecognized namespace. 
                  The <termref def="option-parameter-conventions">option parameter conventions</termref> do not apply
                  to this contained map.<ulist><item><p><term>Type: </term><code>map(xs:QName, item()*)</code></p></item><item><p><term>Default: </term><code>An empty map</code></p></item></ulist></td></tr></tbody></table><p>The result of the function is a map <var>R</var> with two entries:</p><olist><item><p>There is an entry whose key is the <code>xs:string</code> value <code>"variables"</code> and whose associated value
               is a map <var>V</var>. This map (<var>V</var>) contains one entry for each public global variable declared in the library module. 
               The key of the
            entry is the name of the variable, as an <code>xs:QName</code> value; the associated value is the value of the variable.</p></item><item><p>There is an entry whose key is the <code>xs:string</code> value <code>"functions"</code> and whose associated value
               is a map <var>F</var>. This map (<var>F</var>) contains one entry for each public function declared in the library module, except that when two functions
               have the same name (but different arity), they share the same entry. The key of the
               entry is the name of the function(s), as an <code>xs:QName</code> value; the associated value is a map <var>A</var>.
               This map (<var>A</var>) contains one entry for each function with the given name; its key is the arity of the function,
               as an <code>xs:integer</code> value, and its associated value is the function itself, as a function item. The function
               can be invoked using the rules for dynamic function invocation.
            </p></item></olist><p>The static and dynamic context of the library module are established according to the rules in 
            <xspecref spec="XQ31" ref="id-xq-context-components"/>.</p><p>It is <termref def="dt-implementation-defined">implementation-defined</termref> whether constructs in the library module 
            are evaluated in the same <termref def="execution-scope">execution scope</termref> as the calling module.</p><p>The library module that is loaded may import other modules using an <code>import module</code> declaration. The result of
            <code>fn:load-xquery-module</code> does not include global variables or functions declared in such a transitively-imported module.
            However, the <code>options</code> map supplied in the function call <rfc2119>may</rfc2119> 
            (and if no default is defined, <rfc2119>must</rfc2119>)
            supply values for external variables declared in transitively-loaded library modules.</p><p>The library module that is loaded may import schema declarations using an <code>import schema</code> declaration. It is
            <termref def="dt-implementation-defined">implementation-defined</termref> whether schema components in the in-scope 
            schema definitions of the calling module
            are automatically added to the in-scope schema definitions of the dynamically loaded module. The in-scope schema definitions
            of the calling and called modules must be consistent, according to the rules defined in 
            <xspecref spec="XQ31" ref="id-consistency-constraints"/>.</p><p diff="chg" at="D">Where nodes are passed to or from the dynamically loaded module, for example as an argument or result of a function, 
            they <rfc2119>should</rfc2119> if possible retain their node identity, their base URI, their type annotations, and their relationships to all other nodes 
            in the containing tree (including ancestors and siblings). If this is not possible, for example because the only way of passing nodes 
            to the chosen XQuery implementation is by serializing and re-parsing, then a node <rfc2119>may</rfc2119> be passed in the form of a deep 
            copy, which may lose information about the identity of the node, about its ancestors and siblings, about its base URI, about its type annotations, and about its 
            relationships to other nodes passed across the interface.</p></def></gitem><gitem><label>Error Conditions</label><def><p>If <code>$module-uri</code> is a zero length string, a dynamic error is raised <errorref class="QM" code="0001"/>.</p><p>If the implementation is not able to find a library module with the specified target namespace, 
            an error is raised <errorref class="QM" code="0002"/>.</p><p>If a static error (including a statically-detected type error) is encountered when processing the library module, 
            a dynamic error is raised <errorref class="QM" code="0003"/>.</p><p diff="del" at="E">If the imported module requires a value for the initial context item or for an external variable, and no value is supplied,
            an error is raised [FOQM0004]</p><p>If a value is supplied for the initial context item or for an external variable and the value does not conform to the required
            type declared in the dynamically loaded module, a dynamic error is raised <errorref class="QM" code="0005"/>.</p><p diff="add" at="D">If no suitable XQuery processor is available, a dynamic error is raised <errorref class="QM" code="0006"/>.
         This includes (but is not limited to) the following cases:</p><olist diff="add" at="D"><item><p>No XQuery processor is available;</p></item><item><p>Use of the function has been disabled;</p></item><item><p>No XQuery processor supporting the requested version of XQuery is available;</p></item><item><p>No XQuery processor supporting the optional Module Feature is available.</p></item></olist><p diff="del" at="E">If the supplied options are invalid according to the rules of the <termref def="option-parameter-conventions"/>, 
            a dynamic error is raised [FOQM0007].</p><p>If a dynamic error (including a dynamically-detected type error) is encountered when processing the module 
            (for example, when evaluating its global variables), the dynamic error is returned <emph>as is</emph>.</p></def></gitem><gitem><label>Notes</label><def><p role="note">As with all other functions in this specification, conformance requirements depend on the host language.
         For example, a host language might specify that provision of this function is optional, or that it is excluded entirely,
         or that implementations are required to support XQuery modules using a specified version of XQuery.</p><p role="note">Even where support for this function is mandatory, it is <rfc2119>recommended</rfc2119> for security reasons that implementations
         should provide a user option to disable its use, or to disable aspects of its functionality.</p></def></gitem></glist></div3><div3 id="func-transform"><head>fn:transform</head><glist><gitem><label>Summary</label><def><p>Invokes a transformation using a dynamically-loaded XSLT stylesheet.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="transform" return-type="map(*)" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="options" type="map(*)"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-nondeterministic">nondeterministic</termref>, <termref def="dt-context-dependent">context-dependent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>This function loads an XSLT stylesheet and invokes it to perform a transformation.</p><p>The inputs to the transformation are supplied in the form of a map. 
            The <termref def="option-parameter-conventions">option parameter conventions</termref> apply
            to this map; they do not apply to any nested map unless otherwise specified.</p><p>The function first identifies the <term>requested XSLT version</term>, as follows:</p><ulist><item><p>If the <code>xslt-version</code>
               option is present, the requested XSLT version is the value of that option. </p></item><item><p>Otherwise, the requested XSLT version
               is the value of the <code>[xsl:]version</code> attribute of the outermost element in the supplied stylesheet or package.</p></item></ulist><p>The function then attempts to locate an XSLT processor that implements the requested XSLT version.</p><ulist><item><p>If a processor that implements the requested XSLT version is available, then it is used. </p></item><item><p>Otherwise, if a processor that implements a version later than the requested version is available, then it is used. </p></item><item><p>Otherwise, the function fails indicating that no suitable XSLT processor is available.</p></item></ulist><note><p>The phrase <emph>locate an XSLT processor</emph> includes the possibility of locating a software product and
         configuring it to act as an XSLT processor that implements the requested XSLT version.</p></note><p>If more than one XSLT processor is available under the above rules, then the one that is chosen may be selected according to
         the availability of requested features: see below.</p><p>Once an XSLT processor has been selected that implements a given version of XSLT, the processor
         follows the rules of that version of the XSLT specification. This includes any decision to operate in backwards or forwards
         compatibility mode. For example, if an XSLT 2.0 processor is selected, and the stylesheet specifies <code>version="1.0"</code>,
         then the processor will operate in backwards compatibility mode; if the same processor is selected and the stylesheet
         specifies <code>version="3.0"</code>, the processor will operate in forwards compatibility mode.</p><p>The combinations of options that are relevant to each version of XSLT, other than <code>xslt-version</code> 
            itself, are listed below. This is followed by a table giving the meaning of each option.</p><olist><item><p>For invocation of an XSLT 1.0 processor (see <bibref ref="xslt10"/>), 
                  the supplied options must include all of the following <phrase duff="chg" at="E">(if anything else is present, it is ignored)</phrase>:</p><olist><item><p>The stylesheet, provided by supplying exactly one of the following:</p><slist><sitem><code>stylesheet-location</code></sitem><sitem><code>stylesheet-node</code></sitem><sitem><code>stylesheet-text</code></sitem></slist></item><item><p>The source tree, provided as the value of the <code>source-node</code> option.</p></item><item><p>Zero or more of the following additional options:</p><slist><sitem><code>stylesheet-base-uri</code></sitem><sitem><code>stylesheet-params</code> (defaults to an empty map)</sitem><sitem><code>initial-mode</code> (defaults to the unnamed mode)</sitem><sitem><code>delivery-format</code> (defaults to <code>document</code>)</sitem><sitem><code>serialization-params</code> (defaults to an empty map)</sitem><sitem><code>enable-messages</code> (default is implementation-defined)</sitem><sitem><code>requested-properties</code> (default is an empty map)</sitem><sitem><code>vendor-options</code> (defaults to an empty map)</sitem><sitem><code>cache</code> (default is implementation-defined)</sitem></slist></item></olist></item><item><p>For invocation of an XSLT 2.0 processor (see <bibref ref="xslt20"/>), 
                  the supplied options must include all of the following <phrase duff="chg" at="E">(if anything else is present, it is ignored)</phrase>:</p><olist><item><p>The stylesheet, provided by supplying exactly one of the following:</p><slist><sitem><code>stylesheet-location</code></sitem><sitem><code>stylesheet-node</code></sitem><sitem><code>stylesheet-text</code></sitem></slist></item><item><p>Invocation details, as exactly one of the following:</p><olist><item><p>For apply-templates invocation, all of the following:</p><p><code>source-node</code></p><p>Optionally, <code>initial-mode</code> (defaults to the unnamed mode)</p></item><item><p>For call-template invocation, all of the following:</p><p><code>initial-template</code></p><p>Optionally, <code>source-node</code></p></item></olist></item><item><p>Zero or more of the following additional options:</p><slist><sitem><code>stylesheet-base-uri</code></sitem><sitem><code>stylesheet-params</code> (defaults to an empty map)</sitem><sitem><code>base-output-uri</code> (defaults to absent)</sitem><sitem><code>delivery-format</code> (defaults to <code>document</code>)</sitem><sitem><code>serialization-params</code> (defaults to an empty map)</sitem><sitem><code>enable-messages</code> (default is implementation-defined)</sitem><sitem><code>enable-trace</code> (default is implementation-defined)</sitem><sitem><code>requested-properties</code> (default is an empty map)</sitem><sitem><code>vendor-options</code> (defaults to an empty map)</sitem><sitem><code>cache</code> (default is implementation-defined)</sitem></slist></item></olist></item><item><p>For invocation of an XSLT 3.0 processor (see <bibref ref="xslt-30"/>), 
                  the supplied options must include all of the following <phrase duff="chg" at="E">(if anything else is present, it is ignored)</phrase>:</p><olist><item><p>The stylesheet, provided either by supplying exactly one of the following:</p><slist><sitem><code>stylesheet-location</code></sitem><sitem><code>stylesheet-node</code></sitem><sitem><code>stylesheet-text</code></sitem></slist><p>Or by supplying exactly one of the following:</p><slist><sitem><code>package-location</code></sitem><sitem><code>package-node</code></sitem><sitem><code>package-text</code></sitem><sitem><code>package-name</code> plus optionally <code>package-version</code></sitem></slist></item><item><p>Invocation details, as exactly one of the following combinations:</p><olist><item><p>For apply-templates invocation, all of the following:</p><p>Exactly one of <code>source-node</code> or <code>initial-match-selection</code></p><p>Optionally, <code>initial-mode</code></p><p>Optionally, <code>template-params</code></p><p>Optionally, <code>tunnel-params</code></p></item><item><p>For call-template invocation using an explicit template name, all of the following:</p><p><code>initial-template</code></p><p>Optionally, <code>template-params</code></p><p>Optionally, <code>tunnel-params</code></p><p>Optionally, <code>source-node</code></p></item><item><p>For call-template invocation using the defaulted template name <code>xsl:initial-template</code>, all of the following:</p><p>Optionally, <code>template-params</code></p><p>Optionally, <code>tunnel-params</code></p><note><p>If the <code>source-node</code> option is present and <code>initial-template</code> is absent,
                              then apply-templates invocation will be used. To use call-template invocation on the template
                              named <code>xsl:initial-template</code> while also supplying a context item for use when evaluating
                              global variables, either (a) supply the context item using the <code>global-context-item</code> option,
                              or (b) supply <code>source-node</code>, and set the <code>initial-template</code> option explicitly to the 
                              QName <code>xsl:initial-template</code></p></note></item><item><p>For call-function invocation, all of the following:</p><p><code>initial-function</code></p><p><code>function-params</code></p></item></olist><note><p>The invocation method can be determined as the first of the following which applies:</p><ulist><item><p>If <code>initial-function</code> is present, then call-function invocation.</p></item><item><p>If <code>initial-template</code> is present, then call-template invocation.</p></item><item><p>If <code>source-node</code> or <code>initial-match-selection</code>
                              is present, then apply-templates invocation.</p></item><item><p>Otherwise, <code>call-template</code> invocation using
                              the default entry point <code>xsl:initial-template</code>.</p></item></ulist></note></item><item><p>Zero or more of the following additional options:</p><slist><sitem><code>stylesheet-base-uri</code></sitem><sitem><code>static-params</code> (defaults to an empty map)</sitem><sitem><code>stylesheet-params</code> (defaults to an empty map)</sitem><sitem><code>global-context-item</code> (defaults to absent)</sitem><sitem><code>base-output-uri</code> (defaults to absent)</sitem><sitem><code>delivery-format</code></sitem><sitem><code>serialization-params</code> (defaults to an empty map)</sitem><sitem><code>enable-assertions</code> (default is false)</sitem><sitem><code>enable-messages</code> (default is implementation-defined)</sitem><sitem><code>enable-trace</code> (default is implementation-defined)</sitem><sitem><code>requested-properties</code> (default is an empty map)</sitem><sitem><code>vendor-options</code> (defaults to an empty map)</sitem><sitem><code>cache</code> (default is implementation-defined)</sitem></slist></item></olist></item></olist><p>The meanings of each option are defined in the table below.</p><table style="border-collapse: collapse"><thead><tr style="border-top: 2px solid black; border-bottom: 2px solid black"><th style="text-align:left; padding-right: 10px; " rowspan="1" colspan="1">Key</th><th style="text-align:left; padding-right: 10px; " rowspan="1" colspan="1">Applies to</th><th style="text-align:left; padding-right: 10px; " rowspan="1" colspan="1">Value</th><th style="text-align:left" rowspan="1" colspan="1">Meaning</th></tr></thead><tbody><tr><td style="white-space:nowrap; padding-right: 10px; vertical-align:top; border-bottom: 2px solid black" rowspan="1" colspan="1"><code>base-output-uri</code></td><td style="white-space:nowrap; padding-right: 10px; vertical-align:top; border-bottom: 2px solid black" rowspan="1" colspan="1">1.0, 2.0, 3.0</td><td style="vertical-align:top; border-bottom: 2px solid black" colspan="2" rowspan="1">The URI of the principal result document; also used as the base URI for
            resolving relative URIs of secondary result documents. If the value is a relative 
            reference, it is resolved against the static base URI of the <code>fn:transform</code> 
            function call. <ulist><item><p><term>Type: </term><code>xs:string</code></p></item><item><p><term>Default: </term><code>The effect of not
            supplying a base output URI is defined by the XSLT specification; the implementation
            may supply a default, for example the directory containing the
            stylesheet, or the current working directory. </code></p></item></ulist></td></tr><tr><td style="white-space:nowrap; padding-right: 10px; vertical-align:top; border-bottom: 2px solid black" rowspan="1" colspan="1"><code>cache</code></td><td style="white-space:nowrap; padding-right: 10px; vertical-align:top; border-bottom: 2px solid black" rowspan="1" colspan="1">1.0, 2.0, 3.0</td><td style="vertical-align:top; border-bottom: 2px solid black" colspan="2" rowspan="1">This option has no effect on the result of the transformation but may affect
            efficiency. The value <code>true</code> indicates an expectation that the same
            stylesheet is likely to be used for more than one transformation; the value
                <code>false</code> indicates an expectation that the stylesheet will be used once
            only.<ulist><item><p><term>Type: </term><code>xs:boolean</code></p></item><item><p><term>Default: </term><code>true()</code></p></item></ulist></td></tr><tr><td style="white-space:nowrap; padding-right: 10px; vertical-align:top; border-bottom: 2px solid black" rowspan="4" colspan="1"><code>delivery-format</code></td><td style="white-space:nowrap; padding-right: 10px; vertical-align:top; border-bottom: 2px solid black" rowspan="4" colspan="1">1.0, 2.0, 3.0</td><td style="vertical-align:top; border-bottom: 1px solid black" colspan="2" rowspan="1">The manner in which the transformation results should be delivered. Applies both to the
            principal result document and to secondary result documents created using
                <code>xsl:result-document</code>.<ulist><item><p><term>Type: </term><code>xs:string</code></p></item><item><p><term>Default: </term><code>document, unless the relevant
            xsl:output or xsl:result-document element specifies
            build-tree="no" (applies to XSLT 3.0 only), in which case the default
            is raw.</code></p></item></ulist></td></tr><tr><td style="white-space:nowrap; padding-right: 10px; vertical-align:top; border-bottom: 1px solid black" rowspan="1" colspan="1"><code>document</code></td><td style="vertical-align:top; border-bottom: 1px solid black" rowspan="1" colspan="1">The result is delivered as a
                        document node.</td></tr><tr><td style="white-space:nowrap; padding-right: 10px; vertical-align:top; border-bottom: 1px solid black" rowspan="1" colspan="1"><code>serialized</code></td><td style="vertical-align:top; border-bottom: 1px solid black" rowspan="1" colspan="1">The result is delivered as
                        a string, representing the results of serialization. Note that (as with the
                            <code>fn:serialize</code> function) the final encoding stage of
                        serialization (which turns a sequence of characters into a sequence of
                        octets) is either skipped, or reversed by decoding the octet stream back
                        into a character stream.</td></tr><tr><td style="white-space:nowrap; padding-right: 10px; vertical-align:top; border-bottom: 2px solid black" rowspan="1" colspan="1"><code>raw</code></td><td style="vertical-align:top; border-bottom: 2px solid black" rowspan="1" colspan="1">The result of the initial
                template or function is returned as an arbitrary XDM value (after conversion
                to the declared type, but without wrapping in a document node, and without
                serialization): when this option is chosen, the returned map contains the
                raw result.</td></tr><tr><td style="white-space:nowrap; padding-right: 10px; vertical-align:top; border-bottom: 2px solid black" rowspan="1" colspan="1"><code>enable-assertions</code></td><td style="white-space:nowrap; padding-right: 10px; vertical-align:top; border-bottom: 2px solid black" rowspan="1" colspan="1">3.0</td><td style="vertical-align:top; border-bottom: 2px solid black" colspan="2" rowspan="1">Indicates whether any <code>xsl:assert</code> instructions in the stylesheet
            are to be evaluated.<ulist><item><p><term>Type: </term><code>xs:boolean</code></p></item><item><p><term>Default: </term><code>false()</code></p></item></ulist></td></tr><tr><td style="white-space:nowrap; padding-right: 10px; vertical-align:top; border-bottom: 2px solid black" rowspan="1" colspan="1"><code>enable-messages</code></td><td style="white-space:nowrap; padding-right: 10px; vertical-align:top; border-bottom: 2px solid black" rowspan="1" colspan="1">1.0, 2.0, 3.0</td><td style="vertical-align:top; border-bottom: 2px solid black" colspan="2" rowspan="1">Indicates whether any <code>xsl:message</code> instructions in the stylesheet
            are to be evaluated. The destination and formatting of any such messages is
            implementation-defined.<ulist><item><p><term>Type: </term><code>xs:boolean</code></p></item><item><p><term>Default: </term><code>Implementation-defined</code></p></item></ulist></td></tr><tr><td style="white-space:nowrap; padding-right: 10px; vertical-align:top; border-bottom: 2px solid black" rowspan="1" colspan="1"><code>enable-trace</code></td><td style="white-space:nowrap; padding-right: 10px; vertical-align:top; border-bottom: 2px solid black" rowspan="1" colspan="1">2.0, 3.0</td><td style="vertical-align:top; border-bottom: 2px solid black" colspan="2" rowspan="1">Indicates whether any <code>fn:trace</code> functions in the stylesheet are to
            generate diagnostic messages. The destination and formatting of any such messages is
            implementation-defined.<ulist><item><p><term>Type: </term><code>xs:boolean</code></p></item><item><p><term>Default: </term><code>Implementation-defined</code></p></item></ulist></td></tr><tr><td style="white-space:nowrap; padding-right: 10px; vertical-align:top; border-bottom: 2px solid black" rowspan="1" colspan="1"><code>function-params</code></td><td style="white-space:nowrap; padding-right: 10px; vertical-align:top; border-bottom: 2px solid black" rowspan="1" colspan="1">3.0</td><td style="vertical-align:top; border-bottom: 2px solid black" colspan="2" rowspan="1">An array of values to be used as the arguments to the initial function call.
            The value is converted to the required type of the declared parameter using the function
            conversion rules.<ulist><item><p><term>Type: </term><code>array(item()*)</code></p></item><item><p><term>Default: </term><code>Empty array</code></p></item></ulist></td></tr><tr><td style="white-space:nowrap; padding-right: 10px; vertical-align:top; border-bottom: 2px solid black" rowspan="1" colspan="1"><code>global-context-item</code></td><td style="white-space:nowrap; padding-right: 10px; vertical-align:top; border-bottom: 2px solid black" rowspan="1" colspan="1">3.0</td><td style="vertical-align:top; border-bottom: 2px solid black" colspan="2" rowspan="1">The value of the global context item, as defined in XSLT 3.0<ulist><item><p><term>Type: </term><code>item()</code></p></item><item><p><term>Default: </term><code>The value of source-node</code></p></item></ulist></td></tr><tr><td style="white-space:nowrap; padding-right: 10px; vertical-align:top; border-bottom: 2px solid black" rowspan="1" colspan="1"><code>initial-function</code></td><td style="white-space:nowrap; padding-right: 10px; vertical-align:top; border-bottom: 2px solid black" rowspan="1" colspan="1">3.0</td><td style="vertical-align:top; border-bottom: 2px solid black" colspan="2" rowspan="1">The name of the initial function to be called for call-function invocation. The
            arity of the function is inferred from the length of
            <code>function-params</code>.<ulist><item><p><term>Type: </term><code>xs:QName</code></p></item><item><p><term>Default: </term><code>n/a</code></p></item></ulist></td></tr><tr><td style="white-space:nowrap; padding-right: 10px; vertical-align:top; border-bottom: 2px solid black" rowspan="1" colspan="1"><code>initial-match-selection</code></td><td style="white-space:nowrap; padding-right: 10px; vertical-align:top; border-bottom: 2px solid black" rowspan="1" colspan="1">3.0</td><td style="vertical-align:top; border-bottom: 2px solid black" colspan="2" rowspan="1">The value of the initial match selection, as defined in XSLT 3.0<ulist><item><p><term>Type: </term><code>item()*</code></p></item><item><p><term>Default: </term><code>The value of source-node</code></p></item></ulist></td></tr><tr><td style="white-space:nowrap; padding-right: 10px; vertical-align:top; border-bottom: 2px solid black" rowspan="1" colspan="1"><code>initial-mode</code></td><td style="white-space:nowrap; padding-right: 10px; vertical-align:top; border-bottom: 2px solid black" rowspan="1" colspan="1">1.0, 2.0, 3.0</td><td style="vertical-align:top; border-bottom: 2px solid black" colspan="2" rowspan="1">The name of the initial processing mode.<ulist><item><p><term>Type: </term><code>xs:QName</code></p></item><item><p><term>Default: </term><code/></p></item></ulist></td></tr><tr><td style="white-space:nowrap; padding-right: 10px; vertical-align:top; border-bottom: 2px solid black" rowspan="1" colspan="1"><code>initial-template</code></td><td style="white-space:nowrap; padding-right: 10px; vertical-align:top; border-bottom: 2px solid black" rowspan="1" colspan="1">2.0, 3.0</td><td style="vertical-align:top; border-bottom: 2px solid black" colspan="2" rowspan="1">The name of a named template in the stylesheet to act as the initial entry
            point.<ulist><item><p><term>Type: </term><code>xs:QName</code></p></item><item><p><term>Default: </term><code>xsl:initial-template</code></p></item></ulist></td></tr><tr><td style="white-space:nowrap; padding-right: 10px; vertical-align:top; border-bottom: 2px solid black" rowspan="1" colspan="1"><code>package-name</code></td><td style="white-space:nowrap; padding-right: 10px; vertical-align:top; border-bottom: 2px solid black" rowspan="1" colspan="1">3.0</td><td style="vertical-align:top; border-bottom: 2px solid black" colspan="2" rowspan="1">The name of the top-level stylesheet package to be invoked (an absolute
            URI)<ulist><item><p><term>Type: </term><code>xs:string</code></p></item><item><p><term>Default: </term><code>n/a</code></p></item></ulist></td></tr><tr><td style="white-space:nowrap; padding-right: 10px; vertical-align:top; border-bottom: 2px solid black" rowspan="1" colspan="1"><code>package-location</code></td><td style="white-space:nowrap; padding-right: 10px; vertical-align:top; border-bottom: 2px solid black" rowspan="1" colspan="1">3.0</td><td style="vertical-align:top; border-bottom: 2px solid black" colspan="2" rowspan="1">The location of the top-level stylesheet package, as a relative or absolute
            URI<ulist><item><p><term>Type: </term><code>xs:string</code></p></item><item><p><term>Default: </term><code>n/a</code></p></item></ulist></td></tr><tr><td style="white-space:nowrap; padding-right: 10px; vertical-align:top; border-bottom: 2px solid black" rowspan="1" colspan="1"><code>package-node</code></td><td style="white-space:nowrap; padding-right: 10px; vertical-align:top; border-bottom: 2px solid black" rowspan="1" colspan="1">3.0</td><td style="vertical-align:top; border-bottom: 2px solid black" colspan="2" rowspan="1">A document or element node containing the top-level stylesheet
            package<ulist><item><p><term>Type: </term><code>node()</code></p></item><item><p><term>Default: </term><code>n/a</code></p></item></ulist></td></tr><tr><td style="white-space:nowrap; padding-right: 10px; vertical-align:top; border-bottom: 2px solid black" rowspan="1" colspan="1"><code>package-text</code></td><td style="white-space:nowrap; padding-right: 10px; vertical-align:top; border-bottom: 2px solid black" rowspan="1" colspan="1">3.0</td><td style="vertical-align:top; border-bottom: 2px solid black" colspan="2" rowspan="1">The top-level stylesheet package in the form of unparsed lexical
            XML.<ulist><item><p><term>Type: </term><code>xs:string</code></p></item><item><p><term>Default: </term><code>n/a</code></p></item></ulist></td></tr><tr><td style="white-space:nowrap; padding-right: 10px; vertical-align:top; border-bottom: 2px solid black" rowspan="1" colspan="1"><code>package-version</code></td><td style="white-space:nowrap; padding-right: 10px; vertical-align:top; border-bottom: 2px solid black" rowspan="1" colspan="1">3.0</td><td style="vertical-align:top; border-bottom: 2px solid black" colspan="2" rowspan="1">The version of the top-level stylesheet package to be invoked.<ulist><item><p><term>Type: </term><code>xs:string</code></p></item><item><p><term>Default: </term><code>"*" (any version)</code></p></item></ulist></td></tr><tr><td style="white-space:nowrap; padding-right: 10px; vertical-align:top; border-bottom: 2px solid black" rowspan="1" colspan="1"><code>post-process</code></td><td style="white-space:nowrap; padding-right: 10px; vertical-align:top; border-bottom: 2px solid black" rowspan="1" colspan="1">1.0 2.0 3.0</td><td style="vertical-align:top; border-bottom: 2px solid black" colspan="2" rowspan="1">A function that is used to post-process each result document of
                  the transformation (both the principal result and secondary results), in whatever
                  form it would otherwise be delivered (document, serialized, or raw). The first 
                  argument of the function is the key used to identify the result in the map return
                  by the <code>fn:transform</code> function (for example, this will be the supplied 
                  base output URI in the case of the principal result, or the string "output" if no
                  base output URI was supplied). The second argument is the 
                  actual value. The value that is returned in the result of the <code>fn:transform</code> 
                  function is the result of applying this post-processing.
                  
                  <note><p>If the implementation provides a way of writing or invoking functions 
                        with side-effects, this post-processing function might be used to save 
                        a copy of the result document to persistent storage. For example, if the 
                        implementation provides access to the EXPath File library <bibref ref="expath"/>, 
                        then a serialized document might be written to filestore by calling the 
                        <code>file:write</code> function. Similar mechanisms might be used to issue 
                        an HTTP POST request that posts the result to an HTTP server, or to send 
                        the document to an email recipient. The semantics of calling functions 
                        with side-effects are entirely <termref def="implementation-defined">implementation-defined</termref>.</p><p>If the primary purpose of the post-processing function is achieved by 
                        means of such side-effects, and if the actual results are not needed by 
                        the caller of the <code>fn:transform</code> function, then it does not matter what 
                        the post-processing function actually returns (it could be an empty 
                        sequence, for example).</p><p>Calls to <code>fn:transform</code> can potentially have side-effects 
                        even in the absence of the post-processing option, because the XSLT 
                        specification allows a stylesheet to invoke extension functions 
                        that have side-effects. The semantics in this case are <termref def="implementation-defined">implementation-defined</termref>.</p></note><ulist><item><p><term>Type: </term><code>function(xs:string, item()*) as item()*</code></p></item><item><p><term>Default: </term><code>function($a, $b) { $b }</code></p></item></ulist></td></tr><tr><td style="white-space:nowrap; padding-right: 10px; vertical-align:top; border-bottom: 2px solid black" rowspan="1" colspan="1"><code>requested-properties</code></td><td style="white-space:nowrap; padding-right: 10px; vertical-align:top; border-bottom: 2px solid black" rowspan="1" colspan="1">1.0, 2.0, 3.0</td><td style="vertical-align:top; border-bottom: 2px solid black" colspan="2" rowspan="1">The keys in the map are QNames that could legitimately be supplied in a call to
            the XSLT <code>system-property</code> function; the values in the map are the requested
            settings of the corresponding property. The boolean values <code>true()</code> and
                <code>false()</code> are equivalent to the string values <code>yes</code> and
                <code>no</code>. As a special case, setting a value for <code>xsl:version</code> has
            no effect, because of the potential for conflict with other options. For example: <ulist><item><p>Setting <code>xsl:product-name</code> to a particular value requests a
                        particular XSLT software product.</p></item><item><p>Setting <code>xsl:product-version</code> requests a specific version of
                        that product.</p></item><item><p>Setting <code>xsl:is-schema-aware</code> to <code>true()</code> requests a
                        schema-aware processor.</p></item><item><p>Setting <code>xsl:xsd-version</code> to <code>"1.1"</code> requests a
                        processor that supports XML Schema version 1.1.</p></item></ulist> Setting a boolean property such as <code>xsl:supports-dynamic-evaluation</code>
            to <code>false()</code> is interpreted as an explicit request for a processor in which
            the value of the property is false. The effect if the requests cannot be precisely met
            is implementation-defined. In some cases it may be appropriate to ignore the request or
            to provide an alternative (for example, a later version of the product than the one
            requested); in other cases it may be more appropriate to raise an error <errorref class="XT" code="0001" type="dynamic"/> indicating that no suitable XSLT processor
            is available. <ulist><item><p><term>Type: </term><code>map(xs:QName, xs:anyAtomicType)</code></p></item><item><p><term>Default: </term><code>Empty map</code></p></item></ulist></td></tr><tr><td style="white-space:nowrap; padding-right: 10px; vertical-align:top; border-bottom: 2px solid black" rowspan="1" colspan="1"><code>serialization-params</code></td><td style="white-space:nowrap; padding-right: 10px; vertical-align:top; border-bottom: 2px solid black" rowspan="1" colspan="1">1.0, 2.0, 3.0</td><td style="vertical-align:top; border-bottom: 2px solid black" colspan="2" rowspan="1">Serialization parameters for the principal result document. The supplied map
            follows the same rules that apply to a map supplied as the second argument of
                <code>fn:serialize</code>. <ulist><item><p>When a parameter is supplied, the corresponding value overrides or augments
                        the value specified in the unnamed <code>xsl:output</code> declaration (or
                        its default), following the same rules as when one <code>xsl:output</code>
                        declaration overrides another with lower import precedence.</p></item><item><p>When a parameter is supplied and the corresponding value is an empty
                        sequence (for example, <code>map{"standalone":()}</code>), any value
                        specified in the unnamed <code>xsl:output</code> declaration is overridden
                        by the default value. </p></item><item><p>When a parameter is not supplied in <code>serialization-params</code> (that
                        is, when the key is absent) the value that applies is the value appearing in
                        the unnamed <code>xsl:output</code> declaration, or its default. </p></item></ulist><ulist><item><p><term>Type: </term><code>map(xs:anyAtomicType, item()*)</code></p></item><item><p><term>Default: </term><code>Empty map</code></p></item></ulist></td></tr><tr><td style="white-space:nowrap; padding-right: 10px; vertical-align:top; border-bottom: 2px solid black" rowspan="1" colspan="1"><code>source-node</code></td><td style="white-space:nowrap; padding-right: 10px; vertical-align:top; border-bottom: 2px solid black" rowspan="1" colspan="1">1.0, 2.0, 3.0</td><td style="vertical-align:top; border-bottom: 2px solid black" colspan="2" rowspan="1">When <code>source-node</code> is supplied then the
                <code>global-context-item</code> (the context item for evaluating global variables)
            is the root of the tree containing the supplied node. In addition, for apply-templates
            invocation, the <code>source-node</code> acts as the
                <code>initial-match-selection</code>, that is, stylesheet execution starts by
            applying templates to this node.<ulist><item><p><term>Type: </term><code>node()</code></p></item><item><p><term>Default: </term><code>n/a</code></p></item></ulist></td></tr><tr><td style="white-space:nowrap; padding-right: 10px; vertical-align:top; border-bottom: 2px solid black" rowspan="1" colspan="1"><code>static-params</code></td><td style="white-space:nowrap; padding-right: 10px; vertical-align:top; border-bottom: 2px solid black" rowspan="1" colspan="1">3.0</td><td style="vertical-align:top; border-bottom: 2px solid black" colspan="2" rowspan="1">The values of static parameters defined in the stylesheet; the keys are the
            names of the parameters, and the associated values are their values. The value is
            converted to the required type of the declared parameter using the function conversion
            rules.<ulist><item><p><term>Type: </term><code>map(xs:QName, item()*)</code></p></item><item><p><term>Default: </term><code>Empty map</code></p></item></ulist></td></tr><tr><td style="white-space:nowrap; padding-right: 10px; vertical-align:top; border-bottom: 2px solid black" rowspan="1" colspan="1"><code>stylesheet-base-uri</code></td><td style="white-space:nowrap; padding-right: 10px; vertical-align:top; border-bottom: 2px solid black" rowspan="1" colspan="1">1.0, 2.0, 3.0</td><td style="vertical-align:top; border-bottom: 2px solid black" colspan="2" rowspan="1">A string intended to be used as the static base URI of the principal stylesheet
            module. This value <rfc2119>must</rfc2119> be used if no other static base URI is
            available. If the supplied stylesheet already has a base URI (which will generally be
            the case if the stylesheet is supplied using <code>stylesheet-node</code> or
                <code>stylesheet-location</code>) then it is <termref def="dt-implementation-defined">implementation-defined</termref> whether this
            parameter has any effect. If the value is a relative reference, it is resolved against
            the static base URI of the <code>fn:transform</code> function call.<ulist><item><p><term>Type: </term><code>xs:string</code></p></item><item><p><term>Default: </term><code>n/a</code></p></item></ulist></td></tr><tr><td style="white-space:nowrap; padding-right: 10px; vertical-align:top; border-bottom: 2px solid black" rowspan="1" colspan="1"><code>stylesheet-location</code></td><td style="white-space:nowrap; padding-right: 10px; vertical-align:top; border-bottom: 2px solid black" rowspan="1" colspan="1">1.0, 2.0, 3.0</td><td style="vertical-align:top; border-bottom: 2px solid black" colspan="2" rowspan="1">URI that can be used to locate the principal stylesheet module. If relative, it
            is resolved against the static base URI of the <code>fn:transform</code> function call.
            The value also acts as the default for stylesheet-base-uri.<ulist><item><p><term>Type: </term><code>xs:string</code></p></item><item><p><term>Default: </term><code>n/a</code></p></item></ulist></td></tr><tr><td style="white-space:nowrap; padding-right: 10px; vertical-align:top; border-bottom: 2px solid black" rowspan="1" colspan="1"><code>stylesheet-node</code></td><td style="white-space:nowrap; padding-right: 10px; vertical-align:top; border-bottom: 2px solid black" rowspan="1" colspan="1">1.0, 2.0, 3.0</td><td style="vertical-align:top; border-bottom: 2px solid black" colspan="2" rowspan="1">Root of the tree containing the principal stylesheet module, as a document or
            element node. The base URI of the node acts as the default for
            stylesheet-base-uri.<ulist><item><p><term>Type: </term><code>node()</code></p></item><item><p><term>Default: </term><code>n/a</code></p></item></ulist></td></tr><tr><td style="white-space:nowrap; padding-right: 10px; vertical-align:top; border-bottom: 2px solid black" rowspan="1" colspan="1"><code>stylesheet-params</code></td><td style="white-space:nowrap; padding-right: 10px; vertical-align:top; border-bottom: 2px solid black" rowspan="1" colspan="1">1.0, 2.0, 3.0</td><td style="vertical-align:top; border-bottom: 2px solid black" colspan="2" rowspan="1">A map holding values to be supplied for stylesheet parameters. The keys are the
            parameter names; the values are the corresponding parameter values. The values are
            converted if necessary to the required type using the function conversion rules. The
            default is an empty map.<ulist><item><p><term>Type: </term><code>map(xs:QName, item()*)</code></p></item><item><p><term>Default: </term><code>Empty map</code></p></item></ulist></td></tr><tr><td style="white-space:nowrap; padding-right: 10px; vertical-align:top; border-bottom: 2px solid black" rowspan="1" colspan="1"><code>stylesheet-text</code></td><td style="white-space:nowrap; padding-right: 10px; vertical-align:top; border-bottom: 2px solid black" rowspan="1" colspan="1">1.0, 2.0, 3.0</td><td style="vertical-align:top; border-bottom: 2px solid black" colspan="2" rowspan="1">The principal stylesheet module in the form of unparsed lexical
            XML.<ulist><item><p><term>Type: </term><code>xs:string</code></p></item><item><p><term>Default: </term><code>n/a</code></p></item></ulist></td></tr><tr><td style="white-space:nowrap; padding-right: 10px; vertical-align:top; border-bottom: 2px solid black" rowspan="1" colspan="1"><code>template-params</code></td><td style="white-space:nowrap; padding-right: 10px; vertical-align:top; border-bottom: 2px solid black" rowspan="1" colspan="1">3.0</td><td style="vertical-align:top; border-bottom: 2px solid black" colspan="2" rowspan="1">The values of non-tunnel parameters to be supplied to the initial template,
            used with both apply-templates and call-template invocation. Each value is converted to
            the required type of the declared parameter using the function conversion
            rules.<ulist><item><p><term>Type: </term><code>map(xs:QName, item()*)</code></p></item><item><p><term>Default: </term><code/></p></item></ulist></td></tr><tr><td style="white-space:nowrap; padding-right: 10px; vertical-align:top; border-bottom: 2px solid black" rowspan="1" colspan="1"><code>tunnel-params</code></td><td style="white-space:nowrap; padding-right: 10px; vertical-align:top; border-bottom: 2px solid black" rowspan="1" colspan="1">3.0</td><td style="vertical-align:top; border-bottom: 2px solid black" colspan="2" rowspan="1">The values of tunnel parameters to be supplied to the initial template, used
            with both apply-templates and call-template invocation. Each value is converted to the
            required type of the declared parameter using the function conversion
            rules.<ulist><item><p><term>Type: </term><code>map(xs:QName, item()*)</code></p></item><item><p><term>Default: </term><code>Empty map</code></p></item></ulist></td></tr><tr><td style="white-space:nowrap; padding-right: 10px; vertical-align:top; border-bottom: 2px solid black" rowspan="1" colspan="1"><code>vendor-options</code></td><td style="white-space:nowrap; padding-right: 10px; vertical-align:top; border-bottom: 2px solid black" rowspan="1" colspan="1">1.0, 2.0, 3.0</td><td style="vertical-align:top; border-bottom: 2px solid black" colspan="2" rowspan="1">Values for vendor-defined configuration options for the XSLT processor used to
            process the request. The key is the name of an option, expressed as a QName: the
            namespace URI of the QName <rfc2119>should</rfc2119> be a URI controlled by the vendor
            of the XSLT processor. The meaning of the associated value is <termref def="implementation-defined">implementation-defined</termref>. Implementations
                <rfc2119>should</rfc2119> ignore options whose names are in an unrecognized
            namespace. Default is an empty map.<ulist><item><p><term>Type: </term><code>map{xs:QName, item()*}</code></p></item><item><p><term>Default: </term><code>Empty map</code></p></item></ulist></td></tr><tr><td style="white-space:nowrap; padding-right: 10px; vertical-align:top; border-bottom: 2px solid black" rowspan="1" colspan="1"><code>xslt-version</code></td><td style="white-space:nowrap; padding-right: 10px; vertical-align:top; border-bottom: 2px solid black" rowspan="1" colspan="1">1.0, 2.0, 3.0</td><td style="vertical-align:top; border-bottom: 2px solid black" colspan="2" rowspan="1">The minimum level of the XSLT language that the processor must support.<ulist><item><p><term>Type: </term><code>xs:decimal</code></p></item><item><p><term>Default: </term><code>The [xsl:]version attribute at the outermost level of the
            stylesheet.</code></p></item></ulist></td></tr></tbody></table><p>The result of the transformation is returned as a map. There is one entry in the map for the principal result document, and one
            for each secondary result document. The key is a URI in the form of an <code>xs:string</code> value. The key for the principal
            result document is the base output URI if specified, or the string <code>"output"</code> otherwise. The key for secondary
            result documents is the URI of the document, as an absolute URI. The associated value in each entry depends on the requested
            delivery format. If the delivery format is <code>document</code>, the value is a document node. If the delivery format is
            <code>serialized</code>, the value is a string containing the serialized result. If the delivery format is <code>saved</code>,
            the value is the absolute URI of the location where the serialized result has been saved. The saved document will not be accessible
            at this location within the current <termref def="execution-scope">execution scope</termref>
            (this is to prevent any dependency on order of execution).</p><p diff="chg" at="D">Where nodes are passed to or from the transformation, for example as the value of a stylesheet parameter or the result of a function, 
            they <rfc2119>should</rfc2119> if possible retain their node identity, their base URI, their type annotations, and their relationships to all other nodes 
            in the containing tree (including ancestors and siblings). If this is not possible, for example because the only way of passing nodes 
            to the chosen XSLT implementation is by serializing and re-parsing, then a node <rfc2119>may</rfc2119> be passed in the form of a deep 
            copy, which may lose information about the identity of the node, about its ancestors and siblings, about its base URI, about its type annotation, and about its 
            relationships to other nodes passed across the interface.</p><p diff="chg" at="D">It is <termref def="dt-implementation-defined">implementation-defined</termref> whether the XSLT transformation is executed
            within the same <termref def="execution-scope">execution scope</termref> as the calling code.</p><p>The function is <termref def="dt-nondeterministic">nondeterministic</termref> in that it is 
            <termref def="dt-implementation-dependent">implementation-dependent</termref> whether running the function twice against the same
         inputs produces identical results. The results of two invocations may differ in the identity of any returned nodes; they may also
         differ in other respects, for example because the value of <code>fn:current-dateTime</code> is different for the two invocations,
         or because the contents of external documents accessed using <code>fn:doc</code> or <code>xsl:source-document</code> change between
         one invocation and the next.</p><p>The delivery format <code>saved</code> indicates that the transformation should modify the state of the external environment. 
            This has two noteworthy consequences:
         </p><ulist><item><p>It creates a potential security risk.</p></item><item><p>The <code>fn:transform</code> function ceases to be a pure function, because it has side-effects.</p></item></ulist><p>Implementations <rfc2119>may</rfc2119> mitigate these problems in a number of ways, including the following:</p><olist><item><p>Use of the <code>delivery-format=saved</code> option <rfc2119>may</rfc2119> be disallowed, either 
               completely or at user option.
            </p></item><item><p>The environment that the <code>delivery-format=saved</code> option is allowed to modify <rfc2119>may</rfc2119> be 
               sand-boxed in some way. For example: resources that are created using this option may be accessible only 
               via some special interface; the resource may become available only on completion of the execution scope 
               in which the fn:transform function is evaluated; or the implementation may prevent the use functions 
               such as <code>fn:doc</code> and <code>fn:collection</code> to access such resources.
            </p></item><item><p>Creating multiple resources with the same URI <rfc2119>may</rfc2119> be disallowed.</p></item><item><p>The implementation may define circumstances in which the side-effect of 
               creating external resources is thwarted as a consequence of query optimization
               (for example, any situation in which a query calls fn:transform but has no functional 
               dependency on the result of the call). 
            </p></item><item><p>There <rfc2119>may</rfc2119> be restrictions on the URIs that can be used to identify saved resources</p></item></olist></def></gitem><gitem><label>Error Conditions</label><def><p>A dynamic error is raised <errorref class="XT" code="0001" type="dynamic"/> if the transformation cannot be invoked 
            because no suitable XSLT processor is available. This includes (but is not limited to) the following cases:</p><olist diff="add" at="D"><item><p>No XSLT processor is available;</p></item><item><p>No XSLT processor supporting the requested version of XSLT is available;</p></item><item><p>The XSLT processor API does not support some requested feature (for example, the ability to supply tunnel parameters externally);</p></item></olist><p>A dynamic error is raised <errorref class="XT" code="0002" type="dynamic"/> if an error is detected in the supplied
            parameters (for example if two mutually-exclusive parameters are supplied).</p><p>If a static or dynamic error is reported by the XSLT processor, this function fails with a dynamic error, retaining the XSLT error code.</p><p>A dynamic error is raised <errorref class="XT" code="0003" type="dynamic"/> if the XSLT transformation invoked by a call on
            <code>fn:transform</code> fails with a static or dynamic error, and no more specific error code is available. </p><note><p>XSLT 1.0 does not define any error codes, so this is the likely outcome with an XSLT 1.0 processor. XSLT 2.0 and 3.0 do
         define error codes, but some APIs do not expose them. If multiple errors are signaled by the transformation (which is most likely
         to happen with static errors) then the error code should where possible be that of one of these errors, chosen arbitrarily; the processor
         may make details of additional errors available to the application in an <termref def="dt-implementation-defined">implementation-defined</termref>
         way.</p></note><p>A dynamic error is raised <errorref class="XT" code="0004" type="dynamic"/> if the use of this function (or of selected options)
            has been externally disabled, for example for security reasons.</p><p>A dynamic error is raised <errorref class="XT" code="0005" type="dynamic"/> if <code>delivery-format</code> is <code>saved</code>
            and the results cannot be saved at the specified location.</p><p>A dynamic error is raised <errorref class="XT" code="0006" type="dynamic"/> if the transformation produces output containing
            characters available only in XML 1.1, and the calling processor cannot handle such characters.</p><p>A dynamic error is raised <errorref class="XT" code="0007" type="dynamic"/> if the option <code>delivery-format:saved</code>
            is used in a way that violates any implementation-defined restrictions on its use.</p><p>Recursive use of the <code>fn:transform</code> function may lead to catastrophic failures such as
         non-termination or stack overflow. No error code is assigned to such conditions, since they cannot necessarily
         be detected by the processor.</p></def></gitem><gitem><label>Notes</label><def><p role="note">As with all other functions in this specification, conformance requirements depend on the host language.
            For example, a host language might specify that provision of this function is optional, or that it is excluded entirely,
            or that implementations are required to support a particular set of values for the <code>xslt-version</code>
            parameter.</p><p role="note">Even where support for this function is mandatory, it is <rfc2119>recommended</rfc2119> for security reasons that implementations
            should provide a user option to disable its use, or to disable aspects of its functionality such as
            the ability to write to persistent resources.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The following example loads a stylesheet from the location <code>render.xsl</code>,
               applies it to a document loaded from <code>test.xml</code>, and uses an XPath expression
               to examine the result:</p><eg xml:space="preserve">
let $result := fn:transform(
  map {
    "stylesheet-location" : "render.xsl",
    "source-node"    : fn:doc('test.xml')
  })
return $result?output//body  
               </eg></def></gitem></glist></div3></div2></div1><div1 id="maps-and-arrays" diff="add" at="A"><head>Maps and Arrays</head><p>Maps and arrays are introduced as new datatypes in XDM 3.1. This section describes functions that
         operate on maps and arrays. It also describes functions that operate on JSON data structures, which make
         extensive use of maps and arrays.</p><div2 id="map-functions"><head>Functions that Operate on Maps</head><p>The functions defined in this section use a conventional namespace prefix <code>map</code>, which
               is assumed to be bound to the namespace URI <code>http://www.w3.org/2005/xpath-functions/map</code>.</p><p>A map is an additional kind of item.</p><p><termdef id="dt-map" term="map">A map consists of a set of entries. Each entry comprises a key 
               which is an arbitrary atomic value, and an arbitrary sequence called the associated value.</termdef></p><p><termdef id="dt-same-key" term="same key">Within a map, no two entries have the <term>same key</term>. 
               Two atomic values <code>K1</code> and <code>K2</code> are the <term>same key</term>
                  for this purpose if the (internal) function call <code>op:same-key($K1, $K2)</code>
               returns true.</termdef></p><p>It is not necessary that all the keys in a map should be
               of the same type (for example, they can include a mixture of integers and strings).</p><p diff="del" at="D">A map cannot contain among its keys both date/time values with a timezone and date/time values with no timezone. The term "date/time value"
               here means an instance of any of the types <code>xs:dateTime</code>, <code>xs:date</code>, <code>xs:time</code>, <code>xs:gYear</code>
               <code>xs:gYearMonth</code>, <code>xs:gMonth</code>, <code>xs:gMonthDay</code>, or <code>xs:gDay</code>. If a map contains such a value
               with a timezone, then adding an entry with no timezone results in a dynamic error; and conversely, if a map contains such a value
               with no timezone, then adding an entry with a timezone results in a dynamic error.</p><note diff="del" at="D"><p>The reason for this rule is that comparison of a date/time value with timezone to one without timezone depends on knowing the
               implicit timezone. If values with timezones and values without timezones could be mixed in the same map, such a map could become invalid
               when the implicit timezone changes. The rule therefore ensures that the constraint that no two entries have the <termref def="dt-same-key"/>
               applies regardless what timezone is used for the assessment.</p></note><p>As with all other values, the functions in this specification treat maps as immutable. 
               For example, the <code>map:remove</code> function <phrase diff="chg" at="C">returns a map that differs
                  from the supplied map by the omission (typically) of one entry, but the supplied map is not changed by the operation.
               Two calls on <code>map:remove</code> with the same arguments return maps that are
               indistinguishable from each other; there is no way of asking whether these are "the same map".</phrase></p><p>The function call <code>map:get($map, $key)</code> can be used to retrieve the value associated with a given key.</p><p>A map can also be viewed as a function from keys to associated values. To achieve this, a map is also a 
               function item. The function corresponding to the map has the signature 
               <code>function($key as xs:anyAtomicValue) as item()*</code>. Calling the function has the same effect as calling
               the <code>get</code> function: the expression
               <code>$map($key)</code> returns the same result as <code>get($map, $key)</code>. For example, if <code>$books-by-isbn</code>
               is a map whose keys are ISBNs and whose assocated values are <code>book</code> elements, then the expression
               <code>$books-by-isbn("0470192747")</code> returns the <code>book</code> element with the given ISBN.
               The fact that a map is a function item allows it to be passed as an argument to higher-order functions 
               that expect a function item as one of their arguments.</p><p>There is no operation to atomize a map or convert it to a string. The function <code>fn:serialize</code> can in some cases
            be used to produce a JSON representation of a map.</p><table class="index"><thead><tr><th rowspan="1" colspan="1">Function</th><th rowspan="1" colspan="1">Meaning</th></tr></thead><tbody><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">op:same-key</code></td><td rowspan="1" colspan="1">Determines whether two atomic values can coexist as separate keys within a map.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">map:merge</code></td><td rowspan="1" colspan="1">Returns a map that combines the entries from a number of existing maps.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">map:size</code></td><td rowspan="1" colspan="1">Returns the number of entries in the supplied map.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">map:keys</code></td><td rowspan="1" colspan="1">Returns a sequence containing all the keys present in a map</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">map:contains</code></td><td rowspan="1" colspan="1">Tests whether a supplied map contains an entry for a given key</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">map:get</code></td><td rowspan="1" colspan="1">Returns the value associated with a supplied key in a given map.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">map:find</code></td><td rowspan="1" colspan="1">Searches the supplied input sequence and any contained maps and arrays for a map entry with the supplied key,
            and returns the corresponding values.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">map:put</code></td><td rowspan="1" colspan="1">Returns a map containing all the contents of the supplied map, but with an additional entry, which replaces
         any existing entry for the same key.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">map:entry</code></td><td rowspan="1" colspan="1"><phrase diff="chg" at="C">Returns</phrase> a map that contains a single entry (a key-value pair).</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">map:remove</code></td><td rowspan="1" colspan="1">Returns a map containing all the entries from a supplied map, except <phrase diff="chg" at="E">those having a specified key</phrase>.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">map:for-each</code></td><td rowspan="1" colspan="1">Applies a supplied function to every entry in a map, returning the concatenation of the
            results.</td></tr></tbody></table><div3 id="func-same-key"><head>op:same-key</head><glist><gitem><label>Summary</label><def><p>Determines whether two atomic values can coexist as separate keys within a map.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="same-key" return-type="xs:boolean" isOp="no" prefix="op" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="k1" type="xs:anyAtomicType"/><arg name="k2" type="xs:anyAtomicType"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>The internal function <code>op:same-key</code> (which is not available at the user level) is used to assess whether two atomic
            values are considered to be duplicates when used as keys in a map. A map cannot
         contain two separate entries whose keys are <term>the same</term> as defined by this function. 
         The function is also used when matching keys in functions such as <code>map:get</code>
         and <code>map:remove</code>.</p><p>The function returns true if and only if one of the following conditions is true:</p><olist><item><p>All of the following conditions are true:</p><olist><item><p><code>$k1</code> is an instance of <code>xs:string</code>, <code>xs:anyURI</code>, or <code>xs:untypedAtomic</code></p></item><item><p><code>$k2</code> is an instance of <code>xs:string</code>, <code>xs:anyURI</code>, or <code>xs:untypedAtomic</code></p></item><item><p><code>fn:codepoint-equal($k1, $k2)</code></p></item></olist><note><p>Strings are compared without any dependency on collations.</p></note></item><item><p>All of the following conditions are true:</p><olist><item><p><code>$k1</code> is an instance of <code>xs:decimal</code>, <code>xs:double</code>, or <code>xs:float</code></p></item><item><p><code>$k2</code> is an instance of <code>xs:decimal</code>, <code>xs:double</code>, or <code>xs:float</code></p></item><item><p>One of the following conditions is true:</p><olist><item><p>Both <code>$k1</code> and <code>$k2</code> are <code>NaN</code></p><note><p><code>xs:double('NaN')</code> is the same key as <code>xs:float('NaN')</code></p></note></item><item><p>Both <code>$k1</code> and <code>$k2</code> are positive infinity</p><note><p><code>xs:double('INF')</code> is the same key as <code>xs:float('INF')</code></p></note></item><item><p>Both <code>$k1</code> and <code>$k2</code> are negative infinity</p><note><p><code>xs:double('-INF')</code> is the same key as <code>xs:float('-INF')</code></p></note></item><item><p><code>$k1</code> and <code>$k2</code> when converted to decimal numbers with no rounding or loss of precision
                           are mathematically equal.</p><note><p>Every instance of <code>xs:double</code>, <code>xs:float</code>, and <code>xs:decimal</code> can be represented
                              exactly as a decimal number provided enough digits are available both before and after the decimal point. Unlike the <code>eq</code>
                              relation, which converts both operands to <code>xs:double</code> values, possibly losing precision in the process, this
                              comparison is transitive.</p></note><note><p>Positive and negative zero are the same key.</p></note></item></olist></item></olist></item><item><p>All of the following conditions are true:</p><olist><item><p><code>$k1</code> is an instance of <code>xs:date</code>, <code>xs:time</code>, <code>xs:dateTime</code>,
                     <code>xs:gYear</code>, <code>xs:gYearMonth</code>, <code>xs:gMonth</code>, <code>xs:gMonthDay</code>, or <code>xs:gDay</code></p></item><item><p><code>$k2</code> is an instance of <code>xs:date</code>, <code>xs:time</code>, <code>xs:dateTime</code>,
                     <code>xs:gYear</code>, <code>xs:gYearMonth</code>, <code>xs:gMonth</code>, <code>xs:gMonthDay</code>, or <code>xs:gDay</code></p></item><item><p>One of the following conditions is true:</p><olist><item><p>Both <code>$k1</code> and <code>$k2</code> have a timezone</p></item><item><p>Neither <code>$k1</code> nor <code>$k2</code> has a timezone</p></item></olist></item><item><p><code>fn:deep-equal($k1, $k2)</code></p><note><p>The use of <code>deep-equal</code> rather than <code>eq</code> ensures that comparing values of different
                  types yields <code>false</code> rather than an error.</p></note></item></olist><note><p>Unlike the <code>eq</code> operator, this comparison has no dependency on the implicit timezone, which means that
                  the question of whether or not a map contains duplicate keys is not dependent on this aspect of the dynamic context.</p></note></item><item><p>All of the following conditions are true:</p><olist><item><p><code>$k1</code> is an instance of <code>xs:boolean</code>, <code>xs:hexBinary</code>, <code>xs:base64Binary</code>,
                     <code>xs:duration</code>, <code>xs:QName</code>, or <code>xs:NOTATION</code></p></item><item><p><code>$k2</code> is an instance of <code>xs:boolean</code>, <code>xs:hexBinary</code>, <code>xs:base64Binary</code>,
                     <code>xs:duration</code>, <code>xs:QName</code>, or <code>xs:NOTATION</code></p></item><item><p><code>fn:deep-equal($k1, $k2)</code></p><note><p>The use of <code>deep-equal</code> rather than <code>eq</code> ensures that comparing values of different
                        types yields <code>false</code> rather than an error.</p></note></item></olist></item></olist></def></gitem><gitem><label>Notes</label><def><p role="note">The rules for comparing keys in a map are chosen to ensure that the comparison is:</p><ulist role="note"><item><p><term>Context-free</term>: there is no dependency on the static or dynamic context</p></item><item><p><term>Error-free</term>: any two atomic values can be compared, and the result is either true or false, never an error</p></item><item><p><term>Transitive</term>: if <var>A</var> is the same key as <var>B</var>, and <var>B</var> is the same key as <var>C</var>, 
               then <var>A</var> is the same key as <var>C</var>.</p></item></ulist><p role="note">As always, any algorithm that delivers the right result is acceptable. For example, when testing whether an <code>xs:double</code>
         value <var>D</var> is the same key as an <code>xs:decimal</code> value that has <var>N</var> significant digits, it is not
         necessary to know all the digits in the decimal expansion of <var>D</var> to establish the result: computing the first <var>N+1</var> 
            significant digits (or indeed, simply knowing that there are more than <var>N</var> significant digits) is sufficient.</p></def></gitem></glist></div3><div3 id="func-map-merge"><head>map:merge</head><glist><gitem><label>Summary</label><def><p>Returns a map that combines the entries from a number of existing maps.</p></def></gitem><gitem><label>Signatures</label><def><example role="signature"><proto name="merge" return-type="map(*)" isOp="no" prefix="map" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="maps" type="map(*)*"/></proto></example><example role="signature"><proto name="merge" return-type="map(*)" isOp="no" prefix="map" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="maps" type="map(*)*"/><arg name="options" type="map(*)"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>The function <code>map:merge</code> <phrase diff="chg" at="C">returns a map</phrase> that
            is formed by combining the contents of the maps supplied in the <code>$maps</code>
            argument.</p><p>Informally, the supplied maps are combined as follows:</p><olist><item><p>There is one entry in the returned map for each distinct key present in the union
                  of the input maps, where two keys are distinct if they are not the <phrase diff="chg" at="N"><termref def="dt-same-key">same key</termref></phrase>.</p></item><item><p diff="chg" at="E">If there are duplicate keys, that is, if two or more maps contain entries having the
                  <termref def="dt-same-key">same key</termref>, then the way this is handled is
                  controlled by the second (<code>$options</code>) argument.</p></item></olist><p>The definitive specification is as follows.</p><olist><item><p>The effect of calling the single-argument function is the same as the effect of
            calling the two-argument function with an empty map as the value of <code>$options</code>.</p></item><item><p>The <code>$options</code> argument can be used to control the way in which duplicate keys are handled.
               The <termref def="dt-option-parameter-conventions">option parameter conventions</termref> apply.
            </p></item><item><p>The entries that may appear in the <code>$options</code> map are as follows:</p><table style="border-collapse: collapse"><thead><tr style="border-top: 2px solid black; border-bottom: 2px solid black"><th style="text-align:left; padding-right: 10px; " rowspan="1" colspan="1">Key</th><th style="text-align:left; padding-right: 10px; " rowspan="1" colspan="1">Value</th><th style="text-align:left" rowspan="1" colspan="1">Meaning</th></tr></thead><tbody><tr><td style="white-space:nowrap; padding-right: 10px; vertical-align:top; border-bottom: 2px solid black" rowspan="6" colspan="1"><code>duplicates</code></td><td style="vertical-align:top; border-bottom: 1px solid black" colspan="2" rowspan="1">Determines the policy for handling duplicate keys: specifically, the action to be
                        taken if two maps in the input sequence <code>$maps</code> contain entries with key values
                        <var>K1</var> and <var>K2</var> where <var>K1</var> and <var>K2</var> are the 
                        <termref def="same-key">same key</termref>.
                     <ulist><item><p><term>Type: </term><code>xs:string</code></p></item><item><p><term>Default: </term><code>use-first</code></p></item></ulist></td></tr><tr><td style="white-space:nowrap; padding-right: 10px; vertical-align:top; border-bottom: 1px solid black" rowspan="1" colspan="1"><code>reject</code></td><td style="vertical-align:top; border-bottom: 1px solid black" rowspan="1" colspan="1">
                           An error is raised <errorref class="JS" code="0003"/> if duplicate keys are encountered.
                        </td></tr><tr><td style="white-space:nowrap; padding-right: 10px; vertical-align:top; border-bottom: 1px solid black" rowspan="1" colspan="1"><code>use-first</code></td><td style="vertical-align:top; border-bottom: 1px solid black" rowspan="1" colspan="1">
                           If duplicate keys are present, all but the first of a set of duplicates are ignored, 
                           where the ordering is based on the order of maps in the <code>$maps</code> argument.
                        </td></tr><tr><td style="white-space:nowrap; padding-right: 10px; vertical-align:top; border-bottom: 1px solid black" rowspan="1" colspan="1"><code>use-last</code></td><td style="vertical-align:top; border-bottom: 1px solid black" rowspan="1" colspan="1">
                           If duplicate keys are present, all but the last of a set of duplicates are ignored, 
                           where the ordering is based on the order of maps in the <code>$maps</code> argument.
                        </td></tr><tr><td style="white-space:nowrap; padding-right: 10px; vertical-align:top; border-bottom: 1px solid black" rowspan="1" colspan="1"><code>use-any</code></td><td style="vertical-align:top; border-bottom: 1px solid black" rowspan="1" colspan="1">
                           If duplicate keys are present, all but one of a set of duplicates are ignored, 
                           and it is <termref def="implementation-dependent">implementation-dependent</termref>
                           which one is retained. 
                        </td></tr><tr><td style="white-space:nowrap; padding-right: 10px; vertical-align:top; border-bottom: 2px solid black" rowspan="1" colspan="1"><code>combine</code></td><td style="vertical-align:top; border-bottom: 2px solid black" rowspan="1" colspan="1">
                           If duplicate keys are present, the result map includes an entry for the key whose 
                           associated value is the sequence-concatenation of all the values associated with the key, 
                           retaining order based on the order of maps in the <code>$maps</code> argument.
                           The key value in the result map that corresponds to such a set of duplicates must
                           be the <termref def="same-key">same key</termref> as each of the duplicates, but it is
                           otherwise unconstrained: for example if the duplicate keys are <code>xs:byte(1)</code>
                           and <code>xs:short(1)</code>, the key in the result could legitimately be <code>xs:long(1)</code>.
                        </td></tr></tbody></table></item></olist><p>The result of the function call <code>map:merge($MAPS, $OPTIONS)</code>
         is defined to be consistent with the result of the expression:</p><eg xml:space="preserve">
let $FOJS0003 := QName("http://www.w3.org/2005/xqt-errors", "FOJS0003"),

$duplicates-handler := map {
  "use-first":   function($a, $b) {$a},
  "use-last":    function($a, $b) {$b},
  "combine":     function($a, $b) {$a, $b},
  "reject":      function($a, $b) {fn:error($FOJS0003)},
  "use-any": function($a, $b) {fn:random-number-generator()?permute(($a, $b))[1]}
},

$combine-maps := function($A as map(*), $B as map(*), $deduplicator as function(*)) {
    fn:fold-left(map:keys($B), $A, function($z, $k){ 
        if (map:contains($z, $k))
        then map:put($z, $k, $deduplicator($z($k), $B($k)))
        else map:put($z, $k, $B($k))
    })
}
return fn:fold-left($MAPS, map{}, 
    $combine-maps(?, ?, $duplicates-handler(($OPTIONS?duplicates, "use-first")[1]))
            
            </eg><note><p>By way of explanation, <code>$combine-maps</code> is a function that combines
            two maps by iterating over the keys of the second map, adding each key and its corresponding
            value to the first map as it proceeds. The second call of <code>fn:fold-left</code>
            in the <code>return</code> clause then iterates over the maps supplied in the call
            to <code>map:merge</code>, accumulating a single map that absorbs successive maps
            in the input sequence by calling <code>$combine-maps</code>.</p><p>This algorithm processes the supplied maps in a defined order, but processes the keys within
         each map in implementation-dependent order.</p><p>The use of <code>fn:random-number-generator</code> represents one possible conformant
         implementation for <code>"duplicates":"use-any"</code>, but it is not the only conformant
         implementation and is not intended to be a realistic implementation. The purpose of this
         option is to allow the implementation to use whatever strategy is most efficient; for example,
         if the input maps are processed in parallel, then specifying <code>"duplicates":"use-any"</code>
         means that the implementation does not need to keep track of the original order of the sequence of input
         maps.</p></note></def></gitem><gitem><label>Error Conditions</label><def><p>An error is raised <errorref spec="FO" class="JS" code="0003"/> if the value of 
          <code>$options</code> indicates that duplicates are to be rejected, and a duplicate key is encountered.</p><p>An error is raised <errorref spec="FO" class="JS" code="0005"/> if the value of 
          <code>$options</code> includes an entry whose key is defined 
          in this specification, and whose value is not a permitted value for that key.</p></def></gitem><gitem><label>Notes</label><def><p role="note">If the input is an empty sequence, the result is an empty map.</p><p role="note">If the input is a sequence of length one, the result map is 
            <phrase diff="chg" at="C">indistinguishable from the supplied map</phrase>.</p><p role="note">There is no requirement that the supplied input maps should have the same or compatible
            types. The type of a map (for example <code>map(xs:integer, xs:string)</code>) is
            descriptive of the entries it currently contains, but is not a constraint on how the map
            may be combined with other maps.</p></def></gitem><gitem><label>Examples</label><def role="example"><eg xml:space="preserve">let $week := map{0:"Sonntag", 1:"Montag", 2:"Dienstag",
     3:"Mittwoch", 4:"Donnerstag", 5:"Freitag", 6:"Samstag"}</eg><p>The expression <code>map:merge(())</code> returns <code>map{}</code>. <emph>(Returns an empty map).</emph></p><p>The expression <code>map:merge((map:entry(0, "no"), map:entry(1, "yes")))</code> returns <code>map{0:"no", 1:"yes"}</code>. <emph>(Returns a map with two entries).</emph></p><p>The expression <code>map:merge(($week, map{7:"Unbekannt"}))</code> returns <code>map{0:"Sonntag", 1:"Montag", 2:"Dienstag", 3:"Mittwoch", 4:"Donnerstag",
                  5:"Freitag", 6:"Samstag", 7:"Unbekannt"}</code>. <emph>(The value of the existing map is unchanged; the <phrase diff="chg" at="C">returned map 
                  contains</phrase> all the entries from <code>$week</code>, supplemented with an additional
                  entry.)</emph></p><p>The expression <code>map:merge(($week, map{6:"Sonnabend"}), map{"duplicates":"use-last"})</code> returns <code>map{0:"Sonntag", 1:"Montag", 2:"Dienstag", 3:"Mittwoch", 4:"Donnerstag",
                  5:"Freitag", 6:"Sonnabend"}</code>. <emph>(The value of the existing map is unchanged; the returned map
                  contains all the entries from <code>$week</code>, with one entry replaced by a
                  new entry. Both input maps contain an entry with the key <code>6</code>; the
                  one used in the result is the one that comes last in the input
                  sequence.)</emph></p><p>The expression <code>map:merge(($week, map{6:"Sonnabend"}), map{"duplicates":"use-first"})</code> returns <code>map{0:"Sonntag", 1:"Montag", 2:"Dienstag", 3:"Mittwoch", 4:"Donnerstag",
                  5:"Freitag", 6:"Samstag"}</code>. <emph>(The value of the existing map is unchanged; the returned map
                  contains all the entries from <code>$week</code>, with one entry replaced by a
                  new entry. Both input maps contain an entry with the key <code>6</code>; the
                  one used in the result is the one that comes first in the input
                  sequence.)</emph></p><p>The expression <code>map:merge(($week, map{6:"Sonnabend"}), map{"duplicates":"combine"})</code> returns <code>map{0:"Sonntag", 1:"Montag", 2:"Dienstag", 3:"Mittwoch", 4:"Donnerstag",
                  5:"Freitag", 6:("Samstag", "Sonnabend")}</code>. <emph>(The value of the existing map is unchanged; the returned map
                  contains all the entries from <code>$week</code>, with one entry replaced by a
                  new entry. Both input maps contain an entry with the key <code>6</code>; the
                  entry that appears in the result is the sequence-concatenation of the entries
                  in the input maps, retaining order.)</emph></p></def></gitem></glist></div3><div3 id="func-map-size"><head>map:size</head><glist><gitem><label>Summary</label><def><p>Returns the number of entries in the supplied map.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="size" return-type="xs:integer" isOp="no" prefix="map" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="map" type="map(*)"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>The function <code>map:size</code> takes any <termref def="dt-map">map</termref>
            as its <code>$map</code> argument and returns the number of entries that are present
            in the map.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>map:size(map{})</code> returns <code>0</code>.</p><p>The expression <code>map:size(map{"true":1, "false":0})</code> returns <code>2</code>.</p></def></gitem></glist></div3><div3 id="func-map-keys"><head>map:keys</head><glist><gitem><label>Summary</label><def><p>Returns a sequence containing all the keys present in a map</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="keys" return-type="xs:anyAtomicType*" isOp="no" prefix="map" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="map" type="map(*)"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-nondeterministic-wrt-ordering">nondeterministic-wrt-ordering</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>The function <code>map:keys</code> takes any <termref def="dt-map">map</termref>
            as its <code>$map</code> argument and returns the keys that are present in the map as
            a sequence of atomic values, in <termref def="dt-implementation-dependent">implementation-dependent</termref> order.</p><p diff="add" at="D">The function is <term>non-deterministic with respect to ordering</term>
            (see <specref ref="properties-of-functions"/>). This means that two calls with the same argument
            are not guaranteed to produce the results in the same order.</p></def></gitem><gitem><label>Notes</label><def><p role="note">The number of items in the result will be the same as the number of
            entries in the map, and the result sequence will contain no duplicate values.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>map:keys(map{1:"yes", 2:"no"})</code> returns some permutation of <code>(1,2)</code>. <emph>(The result is in <termref def="dt-implementation-dependent">implementation-dependent</termref> order.)</emph></p></def></gitem></glist></div3><div3 id="func-map-contains"><head>map:contains</head><glist><gitem><label>Summary</label><def><p>Tests whether a supplied map contains an entry for a given key</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="contains" return-type="xs:boolean" isOp="no" prefix="map" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="map" type="map(*)"/><arg name="key" type="xs:anyAtomicType"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>The function <code>map:contains</code> returns true if the <termref def="dt-map">map</termref> supplied as <code>$map</code> contains an entry with <phrase diff="chg" at="N">the <termref def="dt-same-key">same key</termref> as</phrase> the
            supplied value of <code>$key</code>; otherwise it returns false.</p></def></gitem><gitem><label>Examples</label><def role="example"><eg xml:space="preserve">let $week := map{0:"Sonntag", 1:"Montag", 2:"Dienstag",
     3:"Mittwoch", 4:"Donnerstag", 5:"Freitag", 6:"Samstag"}</eg><p>The expression <code>map:contains($week, 2)</code> returns <code>true()</code>.</p><p>The expression <code>map:contains($week, 9)</code> returns <code>false()</code>.</p><p>The expression <code>map:contains(map{}, "xyz")</code> returns <code>false()</code>.</p><p>The expression <code>map:contains(map{"xyz":23}, "xyz")</code> returns <code>true()</code>.</p><p>The expression <code>map:contains(map{"abc":23, "xyz":()}, "xyz")</code> returns <code>true()</code>.</p></def></gitem></glist></div3><div3 id="func-map-get"><head>map:get</head><glist><gitem><label>Summary</label><def><p>Returns the value associated with a supplied key in a given map.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="get" return-type="item()*" isOp="no" prefix="map" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="map" type="map(*)"/><arg name="key" type="xs:anyAtomicType"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>The function <code>map:get</code> attempts to find an entry within the <termref def="dt-map">map</termref> supplied as <code>$map</code> that has <phrase diff="chg" at="N">the <termref def="dt-same-key">same key</termref> as</phrase> the supplied
            value of <code>$key</code>. If there is such an entry, it returns the associated value;
            otherwise it returns an empty sequence.</p></def></gitem><gitem><label>Notes</label><def><p role="note">A return value of <code>()</code> from <code>map:get</code> could indicate that
            the key is present in the map with an associated value of <code>()</code>, or it could
            indicate that the key is not present in the map. The two cases can be distinguished by
            calling <code>map:contains</code>.</p><p role="note">Invoking the <termref def="dt-map">map</termref> as a function item has the same effect
            as calling <code>get</code>: that is, when <code>$map</code> is a map, the expression
               <code>$map($K)</code> is equivalent to <code>map:get($map, $K)</code>. Similarly, the
            expression <code>map:get(map:get(map:get($map, 'employee'), 'name'), 'first')</code> can
            be written as <code>$map('employee')('name')('first')</code>. </p></def></gitem><gitem><label>Examples</label><def role="example"><eg xml:space="preserve">let $week := map{0:"Sonntag", 1:"Montag", 2:"Dienstag",
     3:"Mittwoch", 4:"Donnerstag", 5:"Freitag", 6:"Samstag"}</eg><p>The expression <code>map:get($week, 4)</code> returns <code>"Donnerstag"</code>.</p><p>The expression <code>map:get($week, 9)</code> returns <code>()</code>. <emph>(When the key is not present, the function returns an empty
                  sequence.)</emph></p><p>The expression <code>map:get(map:entry(7,()), 7)</code> returns <code>()</code>. <emph>(An empty sequence as the result can also signify that the key is
                  present and the associated value is an empty sequence.)</emph></p></def></gitem></glist></div3><div3 id="func-map-find"><head>map:find</head><glist><gitem><label>Summary</label><def><p>Searches the supplied input sequence and any contained maps and arrays for a map entry with the supplied key,
            and returns the corresponding values.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="find" return-type="array(*)" isOp="no" prefix="map" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="input" type="item()*"/><arg name="key" type="xs:anyAtomicType"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>The function <code>map:find</code> searches the sequence supplied as <code>$input</code>
         looking for map entries whose key is the <termref def="dt-same-key">same key</termref>
         as <code>$key</code>. The associated value in any such map entry (each being in general a sequence)
         is returned as a member of the result array.</p><p>The search processes the <code>$input</code> sequence using the following recursively-defined rules 
            (any equivalent algorithm may be used provided it delivers
            the same result, respecting those rules that constrain the order of the result):</p><olist><item><p>To process a sequence, process each of its items in order.</p></item><item><p>To process an item that is an array, process each of the array's members in order 
               (each member is, in general, a sequence).</p></item><item><p>To process an item that is a map, then for each key-value entry (<var>K</var>, <var>V</var>)
               in the map (in <termref def="dt-implementation-dependent">implementation-dependent</termref> order)
               perform both of the following steps, in order:</p><olist><item><p>If <var>K</var> is the <termref def="dt-same-key">same key</termref> as <code>$key</code>, 
                  then add <var>V</var> as a new member to the end of the result array.</p></item><item><p>Process <var>V</var> (which is, in general, a sequence).</p></item></olist></item><item><p>To process an item that is neither a map nor an array, do nothing. (Such items are ignored).</p></item></olist></def></gitem><gitem><label>Notes</label><def><p role="note">If <code>$input</code> is an empty sequence, map, or array, or if the requested <code>$key</code> is not found,
            the result will be a zero-length array.</p></def></gitem><gitem><label>Examples</label><def role="example"><eg xml:space="preserve">let $responses := [map{0:'no', 1:'yes'}, map{0:'non', 1:'oui'}, 
                  map{0:'nein', 1:('ja', 'doch')}]</eg><p>The expression <code>map:find($responses, 0)</code> returns <code>['no', 'non', 'nein']</code>.</p><p>The expression <code>map:find($responses, 1)</code> returns <code>['yes', 'oui', ('ja', 'doch')]</code>.</p><p>The expression <code>map:find($responses, 2)</code> returns <code>[]</code>.</p><eg xml:space="preserve">let $inventory := map{"name":"car", "id":"QZ123", 
      "parts": [map{"name":"engine", "id":"YW678", "parts":[]}]}</eg><p>The expression <code>map:find($inventory, "parts")</code> returns <code>[[map{"name":"engine", "id":"YW678", "parts":[]}], []]</code>.</p></def></gitem></glist></div3><div3 id="func-map-put"><head>map:put</head><glist><gitem><label>Summary</label><def><p>Returns a map containing all the contents of the supplied map, but with an additional entry, which replaces
         any existing entry for the same key.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="put" return-type="map(*)" isOp="no" prefix="map" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="map" type="map(*)"/><arg name="key" type="xs:anyAtomicType"/><arg name="value" type="item()*"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>The function <code>map:put</code> returns <phrase diff="chg" at="C">a <termref def="dt-map">map</termref> that</phrase> contains all entries from the supplied <code>$map</code>,
            with the exception of any entry whose key is the <termref def="dt-same-key">same key</termref> as <code>$key</code>, together with a new
         entry whose key is <code>$key</code> and whose associated value is <code>$value</code>.</p><p>The effect of the function call <code>map:put($MAP, $KEY, $VALUE)</code> is equivalent
         to the result of the following steps:</p><olist><item><p><code>let $MAP2 := map:remove($MAP, $KEY)</code></p><p>This returns a map in which all entries with the same key as <code>$KEY</code> have been removed.</p></item><item><p>Construct and return a map containing:</p><olist><item><p>All the entries (key/value pairs) in <code>$MAP2</code>, and</p></item><item><p>The entry <code>map:entry($KEY, $VALUE)</code></p></item></olist></item></olist></def></gitem><gitem><label>Notes</label><def><p role="note">There is no requirement that the type of <code>$key</code> and <code>$value</code> be consistent with the types
         of any existing keys and values in the supplied map.</p></def></gitem><gitem><label>Examples</label><def role="example"><eg xml:space="preserve">let $week := map{0:"Sonntag", 1:"Montag", 2:"Dienstag",
       3:"Mittwoch", 4:"Donnerstag", 5:"Freitag", 6:"Samstag"}</eg><p>The expression <code>map:put($week, 6, "Sonnabend")</code> returns <code>map{0:"Sonntag", 1:"Montag", 2:"Dienstag", 3:"Mittwoch", 4:"Donnerstag",
                  5:"Freitag", 6:"Sonnabend"}</code>.</p><p>The expression <code>map:put($week, -1, "Unbekannt")</code> returns <code>map{0:"Sonntag", 1:"Montag", 2:"Dienstag", 3:"Mittwoch", 4:"Donnerstag",
                  5:"Freitag", 6:"Samstag", -1:"Unbekannt"}</code>.</p></def></gitem></glist></div3><div3 id="func-map-entry"><head>map:entry</head><glist><gitem><label>Summary</label><def><p><phrase diff="chg" at="C">Returns</phrase> a map that contains a single entry (a key-value pair).</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="entry" return-type="map(*)" isOp="no" prefix="map" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="key" type="xs:anyAtomicType"/><arg name="value" type="item()*"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>The function <code>map:entry</code> returns a <termref def="dt-map">map</termref> which <phrase diff="del" at="P">normally</phrase> contains a single
            entry. <phrase diff="del" at="N">The collation of the new map is the default collation
               from the static context. </phrase>The key of the entry in the new map is
               <code>$key</code>, and its associated value is <code>$value</code>.</p><p diff="del" at="N">If the supplied key is the <code>xs:float</code> or
               <code>xs:double</code> value <code>NaN</code>, the supplied <code>$map</code> is
            empty (that is, it contains no entries).</p><p diff="del" at="N">If the supplied key is <code>xs:untypedAtomic</code>, it is converted
            to <code>xs:string</code>.</p></def></gitem><gitem><label>Notes</label><def><p role="note">The function call <code>map:entry(K, V)</code> produces the same result as the
         expression <code>map{K : V}</code>.</p><p role="note">The function <code>map:entry</code> is intended primarily for use in conjunction with
            the function <code>map:merge</code>. For example, a map containing seven entries may be
            constructed like this:</p><eg role="note" xml:space="preserve">
map:merge((
   map:entry("Su", "Sunday"),
   map:entry("Mo", "Monday"),
   map:entry("Tu", "Tuesday"),
   map:entry("We", "Wednesday"),
   map:entry("Th", "Thursday"),
   map:entry("Fr", "Friday"),
   map:entry("Sa", "Saturday")
   ))</eg><p role="note">The <code>map:merge</code> function can be used to construct
            a map with a variable number of entries, for example:</p><eg role="note" xml:space="preserve">
map:merge(for $b in //book return map:entry($b/isbn, $b))</eg></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>map:entry("M", "Monday")</code> returns <code>map{"M":"Monday"}</code>.</p></def></gitem></glist></div3><div3 id="func-map-remove"><head>map:remove</head><glist><gitem><label>Summary</label><def><p diff="chg" at="C">Returns a map containing all the entries from a supplied map, except <phrase diff="chg" at="E">those having a specified key</phrase>.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="remove" return-type="map(*)" isOp="no" prefix="map" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="map" type="map(*)"/><arg name="keys" type="xs:anyAtomicType*"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>The function <code>map:remove</code> returns a <termref def="dt-map">map</termref> containing all the entries in <code>$map</code> except for any entry whose key is 
            the <termref def="dt-same-key">same key</termref> as <phrase diff="chg" at="E">an item in</phrase> <code>$keys</code>.</p><p>No failure occurs <phrase diff="chg" at="E">if an item in <code>$keys</code> does not correspond to any entry in <code>$map</code>;
            that key value is simply ignored</phrase>.</p><p>The effect of the function call <code>map:remove($MAP, $KEY)</code> can be described more formally as the result of the expression below:</p><eg xml:space="preserve">
map:merge (
    map:for-each (
       $MAP, function($k, $v) { 
               if (some $key in $KEY satisfies (op:same-key($k, $key)) 
               then () 
               else map:entry($k, $v)
             } ) ) </eg></def></gitem><gitem><label>Examples</label><def role="example"><eg xml:space="preserve">let $week := map{0:"Sonntag", 1:"Montag", 2:"Dienstag",
       3:"Mittwoch", 4:"Donnerstag", 5:"Freitag", 6:"Samstag"}</eg><p>The expression <code>map:remove($week, 4)</code> returns <code>map{0:"Sonntag", 1:"Montag", 2:"Dienstag", 3:"Mittwoch", 5:"Freitag",
                  6:"Samstag"}</code>.</p><p>The expression <code>map:remove($week, 23)</code> returns <code>map{0:"Sonntag", 1:"Montag", 2:"Dienstag", 3:"Mittwoch", 4:"Donnerstag",
                  5:"Freitag", 6:"Samstag"}</code>.</p><p>The expression <code>map:remove($week, (0, 6 to 7))</code> returns <code>map{1:"Montag", 2:"Dienstag", 3:"Mittwoch", 4:"Donnerstag", 5:"Freitag"}</code>.</p><p>The expression <code>map:remove($week, ())</code> returns <code>map{0:"Sonntag", 1:"Montag", 2:"Dienstag", 3:"Mittwoch", 4:"Donnerstag", 5:"Freitag",
                  6:"Samstag"}</code>.</p></def></gitem></glist></div3><div3 id="func-map-for-each"><head>map:for-each</head><glist><gitem><label>Summary</label><def><p>Applies a supplied function to every entry in a map, returning the concatenation of the
            results.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="for-each" return-type="item()*" isOp="no" prefix="map" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="map" type="map(*)"/><arg name="action" type="function(xs:anyAtomicType, item()*) as item()*"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-nondeterministic-wrt-ordering">nondeterministic-wrt-ordering</termref>, <termref def="dt-context-independent">context-independent</termref>, <termref def="dt-focus-independent">focus-independent</termref>,  and <termref def="dt-higher-order">higher-order</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>The function <code>map:for-each</code> takes any <termref def="dt-map">map</termref> as its <code>$map</code> argument and applies the supplied function
            to each entry in the map, in <termref def="dt-implementation-dependent">implementation-dependent</termref> order; the result is the sequence obtained by
            concatenating the results of these function calls.</p><p diff="add" at="D">The function is <term>non-deterministic with respect to ordering</term>
            (see <specref ref="properties-of-functions"/>). This means that two calls with the same arguments
            are not guaranteed to process the map entries in the same order.</p><p>The function supplied as <code>$action</code> takes two arguments. It is called
            supplying the key of the map entry as the first argument, and the associated value as
            the second argument.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>map:for-each(map{1:"yes", 2:"no"}, function($k,
                  $v){$k})</code> returns some permutation of <code>(1,2)</code>. <emph>(This function call is equivalent to calling <code>map:keys</code>. The
                  result is in implementation-dependent order.)</emph></p><p>The expression <code>distinct-values(map:for-each(map{1:"yes", 2:"no"}, function($k,
                  $v){$v}))</code> returns some permutation of <code>("yes", "no")</code>. <emph>(This function call returns the distinct values present in the map, in
                  implementation-dependent order.)</emph></p><p>The expression <code>map:merge(map:for-each(map{"a":1, "b":2}, function($k,
                  $v){map:entry($k, $v+1)}))</code> returns <code>map{"a":2, "b":3}</code>. <emph>(This function call returns a map with the same keys as the input map,
                  with the value of each entry increased by one.)</emph></p><p>This XQuery example converts the entries in a map to attributes on a newly constructed
                  element node:</p><eg xml:space="preserve">
let $dimensions := map{'height': 3, 'width': 4, 'depth': 5};
return
  &lt;box&gt;{
     map:for-each($dimensions, function ($k, $v) { attribute {$k} {$v} })
  }&lt;/box&gt;</eg><p>The result is the element <code>&lt;box height="3" width="4"
                  depth="5"/&gt;</code>.</p></def></gitem></glist></div3></div2><div2 id="map-operations"><head>Other Operations on Maps </head><p>Because a map is a function item, functions that apply to functions also apply
               to maps. A map is an anonymous function, so <code>fn:function-name</code> returns the empty
               sequence; <code>fn:function-arity</code> always returns <code>1</code>.</p><p>Maps may be compared using the <code>fn:deep-equal</code> function.</p><p>There is no function or operator to atomize a map or convert it to a string (other than <code>fn:serialize</code>,
               which can be used to serialize some maps as JSON texts).</p></div2><div2 id="array-functions"><head>Functions that Operate on Arrays</head><p>An array is an additional kind of item. An array of size <var>N</var> is a mapping from the integers
            (1 to <var>N</var>) to a set of values, called the members of the array, each of which is an arbitrary
            sequence. Because an array is an item, and therefore a sequence, arrays can be nested.</p><p>The functions defined in this section use a conventional namespace prefix <code>array</code>, which
               is assumed to be bound to the namespace URI <code>http://www.w3.org/2005/xpath-functions/array</code>.</p><p diff="chg" at="C">As with all other values, arrays are treated as immutable. 
               For example, the <code>array:reverse</code> function returns an array that differs from the supplied
               array in the order of its members, but the supplied array is not changed by the operation. Two calls
               on <code>array:reverse</code> with the same argument will return arrays that are indistinguishable from
               each other; there is no way of asking whether these are "the same array". Like sequences, arrays have no identity. </p><p>An array acts as a function from integer positions to associated values, so the
               function call <code>$array($index)</code> can be used to retrieve the array member at a given position.
               The function corresponding to the array has the signature 
               <code>function($index as xs:integer) as item()*</code>. 
               The fact that an array is a function item allows it to be passed as an argument to higher-order functions 
               that expect a function item as one of their arguments.</p><p>In the function definitions that follow, all the array functions are defined in terms of five primitives:</p><ulist><item><p><code>[]</code> represents the zero-length array (an array with no members).</p></item><item><p><code>$array($index)</code> returns the member at position <code>$index</code>.</p></item><item><p><code>array:size($array)</code> returns the number of members in the array.</p></item><item><p><code>op:array-singleton($seq)</code> returns an array of size one whose single member
                  is the supplied sequence <code>$seq</code>. This operation is not directly available
                  as a user-visible function, because the effect can easily be achieved using the syntax <code>[ $seq ]</code>.</p></item><item><p><code>op:array-concat($array1, $array2)</code> returns an array whose members are first the members of 
               <code>$array1</code> and then the members of <code>$array2</code>. This operation is not directly available
               as a user-visible function, because the effect can easily be achieved using <code>array:join</code>.</p></item></ulist><p>There are two operations on arrays for which the XPath language provides custom syntax:</p><ulist><item><p><code>array { $sequence }</code> constructs an array whose members are the items in <code>$sequence</code>.
                  Every member of this array will be a singleton item.
               This can be defined as <code>fn:fold-left($sequence, [], function($x, $y){ op:array-concat($x, op:array-singleton($y))</code></p></item><item><p><code>[ E1, E2, E3, ..., En]</code> constructs an array in which <code>E1</code> is the first member,
               <code>E2</code> is the second member, and so on. If <var>N=0</var>, the value is the empty array <code>[]</code>;
               if <var>N=1</var>, the value is <code>op:array-concat([], array { E1 })</code>, and if <var>N &gt; 1</var>,
               the value is <code>op:array-concat(op:array-singleton(E1), [ E2, ... En ])</code>.</p></item></ulist><table class="index"><thead><tr><th rowspan="1" colspan="1">Function</th><th rowspan="1" colspan="1">Meaning</th></tr></thead><tbody><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">array:size</code></td><td rowspan="1" colspan="1">Returns the number of members in the supplied array.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">array:get</code></td><td rowspan="1" colspan="1">Returns the value at the specified position in the supplied array (counting from 1).</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">array:put</code></td><td rowspan="1" colspan="1">Returns an array containing all the members of a supplied array, except for one member which is replaced with a new value.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">array:append</code></td><td rowspan="1" colspan="1">Returns an array containing all the members of a supplied array, plus one additional member at the end.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">array:subarray</code></td><td rowspan="1" colspan="1">Returns an array containing all members from a supplied array starting at a supplied
            position, up to a specified length.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">array:remove</code></td><td rowspan="1" colspan="1">Returns an array containing all the members of the supplied array, except for the <phrase diff="chg" at="E">members at specified positions</phrase>.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">array:insert-before</code></td><td rowspan="1" colspan="1">Returns an array containing all the members of the supplied array, with one additional member at a specified position.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">array:head</code></td><td rowspan="1" colspan="1">Returns the first member of an array, that is <code>$array(1)</code>.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">array:tail</code></td><td rowspan="1" colspan="1">Returns an array containing all members except the first from a supplied array.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">array:reverse</code></td><td rowspan="1" colspan="1">Returns an array containing all the members of a supplied array, but in reverse order.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">array:join</code></td><td rowspan="1" colspan="1">Concatenates the contents of several arrays into a single array.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">array:for-each</code></td><td rowspan="1" colspan="1">Returns an array whose size is the same as <code>array:size($array)</code>, in which
            each member is computed by applying <code>$function</code> to the corresponding member of
            <code>$array</code>.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">array:filter</code></td><td rowspan="1" colspan="1">Returns an array containing those members of the <code>$array</code> for which 
            <code>$function</code> returns true.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">array:fold-left</code></td><td rowspan="1" colspan="1">Evaluates the supplied function cumulatively on successive members of the supplied
            array.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">array:fold-right</code></td><td rowspan="1" colspan="1">Evaluates the supplied function cumulatively on successive values of the supplied
            array.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">array:for-each-pair</code></td><td rowspan="1" colspan="1">Returns an array obtained by evaluating the supplied function once for each pair of members at the same position in
            the two supplied arrays.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">array:sort</code></td><td rowspan="1" colspan="1">Returns an array containing all the members of the supplied array, sorted 
            according to the value of a sort key supplied as a function.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">array:flatten</code></td><td rowspan="1" colspan="1">Replaces any array appearing in a supplied sequence with the members of the array, recursively.</td></tr></tbody></table><div3 id="func-array-size"><head>array:size</head><glist><gitem><label>Summary</label><def><p>Returns the number of members in the supplied array.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="size" return-type="xs:integer" isOp="no" prefix="array" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="array" type="array(*)"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>If <code>$array</code> is empty the function returns zero.</p><p>Otherwise, the function returns the number of members in <code>$array</code>.</p></def></gitem><gitem><label>Notes</label><def><p role="note">Note that because an array is an item, the <code>fn:count</code> function when applied to an array always returns 1 (one).</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>array:size(["a", "b", "c"])</code> returns <code>3</code>.</p><p>The expression <code>array:size(["a", ["b", "c"]])</code> returns <code>2</code>.</p><p>The expression <code>array:size([ ])</code> returns <code>0</code>.</p><p>The expression <code>array:size([[ ]])</code> returns <code>1</code>.</p></def></gitem></glist></div3><div3 id="func-array-get" diff="add" at="C"><head>array:get</head><glist><gitem><label>Summary</label><def><p>Returns the value at the specified position in the supplied array (counting from 1).</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="get" return-type="item()*" isOp="no" prefix="array" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="array" type="array(*)"/><arg name="position" type="xs:integer"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>The result is the value of <code>$array($position)</code>.</p></def></gitem><gitem><label>Error Conditions</label><def><p>A dynamic error occurs <errorref class="AY" code="0001"/> if <code>$position</code> is not in the range <code>1 to
               array:size($array)</code> inclusive.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>["a", "b", "c"] =&gt; array:get(2)</code> returns <code>"b"</code>.</p><p>The expression <code>["a", ["b", "c"]] =&gt; array:get(2)</code> returns <code>["b", "c"]</code>.</p></def></gitem></glist></div3><div3 id="func-array-put" diff="add" at="E"><head>array:put</head><glist><gitem><label>Summary</label><def><p>Returns an array containing all the members of a supplied array, except for one member which is replaced with a new value.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="put" return-type="array(*)" isOp="no" prefix="array" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="array" type="array(*)"/><arg name="position" type="xs:integer"/><arg name="member" type="item()*"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>The result is an array whose size is <code>array:size($array)</code>, in which all
            members in positions other than <code>$position</code> are the same as the members in the corresponding position
            of <code>$array</code>, and the member in position <code>$position</code> is <code>$member</code>.</p><p>The result is equivalent to the result of the expression
            <code>$array =&gt; array:remove($position) =&gt; array:insert-before($position, $member)</code>.</p></def></gitem><gitem><label>Error Conditions</label><def><p>A dynamic error occurs <errorref class="AY" code="0001"/> if <code>$position</code> is not in the range <code>1 to
            array:size($array)</code> inclusive.</p><p>This error will always occur if <code>$array</code> is empty.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>array:put(["a", "b", "c"], 2, "d")</code> returns <code>["a", "d", "c"]</code>.</p><p>The expression <code>array:put(["a", "b", "c"], 2, ("d", "e"))</code> returns <code>["a", ("d", "e"), "c"]</code>.</p><p>The expression <code>array:put(["a"], 1, ["d", "e"])</code> returns <code>[["d", "e"]]</code>.</p></def></gitem></glist></div3><div3 id="func-array-append"><head>array:append</head><glist><gitem><label>Summary</label><def><p>Returns an array containing all the members of a supplied array, plus one additional member at the end.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="append" return-type="array(*)" isOp="no" prefix="array" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="array" type="array(*)"/><arg name="appendage" type="item()*"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>The result is an array whose size is <code>array:size($array) + 1</code>, in which all
            members in positions 1 to <code>array:size($array)</code> are the same as the members in the corresponding position
            of <code>$array</code>, and the member in position <code>array:size($array) + 1</code> is <code>$appendage</code>.</p><p>The result is equivalent to the result of the expression
            <code>op:array-concat( $array, [$appendage] )</code>.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>array:append(["a", "b", "c"], "d")</code> returns <code>["a", "b", "c", "d"]</code>.</p><p>The expression <code>array:append(["a", "b", "c"], ("d", "e"))</code> returns <code>["a", "b", "c", ("d", "e")]</code>.</p><p>The expression <code>array:append(["a", "b", "c"], ["d", "e"])</code> returns <code>["a", "b", "c", ["d", "e"]]</code>.</p></def></gitem></glist></div3><div3 id="func-array-subarray"><head>array:subarray</head><glist><gitem><label>Summary</label><def><p>Returns an array containing all members from a supplied array starting at a supplied
            position, up to a specified length.</p></def></gitem><gitem><label>Signatures</label><def><example role="signature"><proto name="subarray" return-type="array(*)" isOp="no" prefix="array" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="array" type="array(*)"/><arg name="start" type="xs:integer"/></proto></example><example role="signature"><proto name="subarray" return-type="array(*)" isOp="no" prefix="array" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="array" type="array(*)"/><arg name="start" type="xs:integer"/><arg name="length" type="xs:integer"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p><phrase diff="add" at="D">Except in error cases,</phrase> 
            the two-argument version of the function returns the same result as the three-argument
            version when called with <code>$length</code> equal to the value of <code>array:size($array) -
               $start + 1</code>.</p><p>The result of the three-argument version of the function is given by the expression
               <code>array:join( ($start to $start + $length - 1) ! [$array(.)] )</code></p></def></gitem><gitem><label>Error Conditions</label><def><p>A dynamic error is raised <errorref class="AY" code="0001"/> if <code>$start</code> is less than one
            <phrase diff="add" at="D">or greater than <code>array:size($array) + 1</code></phrase>.</p><p diff="add" at="D">For the three-argument version of the function:</p><ulist><item><p>A dynamic error is raised <errorref class="AY" code="0002"/> 
               if <code>$length</code> is less than zero.</p></item><item><p>A dynamic error is raised <errorref class="AY" code="0001"/> 
               if <code>$start + $length</code> is greater than <code>array:size($array) + 1</code>.</p></item></ulist></def></gitem><gitem><label>Notes</label><def><p role="note">The value of <code>$start</code> can be equal to <code>array:size($array) + 1</code> provided that <code>$length</code>
         is either equal to zero or omitted. In this case the result will be an empty array.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>array:subarray(["a", "b", "c", "d"], 2)</code> returns <code>["b", "c", "d"]</code>.</p><p>The expression <code>array:subarray(["a", "b", "c", "d"], 5)</code> returns <code>[ ]</code>.</p><p>The expression <code>array:subarray(["a", "b", "c", "d"], 2, 0)</code> returns <code>[ ]</code>.</p><p>The expression <code>array:subarray(["a", "b", "c", "d"], 2, 1)</code> returns <code>["b"]</code>.</p><p>The expression <code>array:subarray(["a", "b", "c", "d"], 2, 2)</code> returns <code>["b", "c"]</code>.</p><p>The expression <code>array:subarray(["a", "b", "c", "d"], 5, 0)</code> returns <code>[ ]</code>.</p><p>The expression <code>array:subarray([ ], 1, 0)</code> returns <code>[ ]</code>.</p></def></gitem></glist></div3><div3 id="func-array-remove"><head>array:remove</head><glist><gitem><label>Summary</label><def><p>Returns an array containing all the members of the supplied array, except for the <phrase diff="chg" at="E">members at specified positions</phrase>.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="remove" return-type="array(*)" isOp="no" prefix="array" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="array" type="array(*)"/><arg name="positions" type="xs:integer*"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>The function returns an array of size <phrase diff="chg" at="E"><code>array:size($array) - fn:count(fn:distinct-values($positions))</code></phrase> 
            containing all members from <code>$array</code>
         <phrase diff="chg" at="E">except the members whose position (counting from 1) is present in the sequence <code>$positions</code>.
         The order of the remaining members is preserved.</phrase></p><p>The result of the function, except in error cases, is given by the expression
            <code diff="chg" at="E">array:join(for $i in (1 to array:size($array))[not(. = $positions)] return [$array($i)])</code>
            </p></def></gitem><gitem><label>Error Conditions</label><def><p diff="chg" at="E">A dynamic error is raised <errorref class="AY" code="0001"/> if any integer in <code>$positions</code> is not in the range <code>1 to
         array:size($array)</code> inclusive. By implication, an error occurs if <code>$array</code> is empty, unless <code>$positions</code>
         is also empty.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>array:remove(["a", "b", "c", "d"], 1)</code> returns <code>["b", "c", "d"]</code>.</p><p>The expression <code>array:remove(["a", "b", "c", "d"], 2)</code> returns <code>["a", "c", "d" ]</code>.</p><p>The expression <code>array:remove(["a"], 1)</code> returns <code>[ ]</code>.</p><p>The expression <code>array:remove(["a", "b", "c", "d"], 1 to 3)</code> returns <code>["d"]</code>.</p><p>The expression <code>array:remove(["a", "b", "c", "d"], ())</code> returns <code>["a", "b", "c", "d"]</code>.</p></def></gitem></glist></div3><div3 id="func-array-insert-before"><head>array:insert-before</head><glist><gitem><label>Summary</label><def><p diff="chg" at="C">Returns an array containing all the members of the supplied array, with one additional member at a specified position.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="insert-before" return-type="array(*)" isOp="no" prefix="array" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="array" type="array(*)"/><arg name="position" type="xs:integer"/><arg name="member" type="item()*"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>The function returns an array of size <code>array:size($array) + 1</code> containing all members from <code>$array</code>
            whose position is less than <code>$position</code>, then a new member given by <code>$member</code>, and
            then all members from <code>$array</code> whose position is greater than or equal to <code>$position</code>. 
            Positions are counted from 1.</p><p>The result is equivalent to the result of the expression
         <code>array:join( (array:subarray($array, 1, $position - 1), [$member], array:subarray($array, $position)) )</code></p></def></gitem><gitem><label>Error Conditions</label><def><p>A dynamic error occurs <errorref class="AY" code="0001"/> if <code>$position</code> is not in the range <code>1 to
            array:size($array) + 1</code> inclusive.</p></def></gitem><gitem><label>Notes</label><def><p role="note">Setting <code>$position</code> to 1 has the effect of prepending the new member at the start of the array. Setting <code>$position</code>
         to the value <code>array:size($array) + 1</code> delivers the same result as <code>array:append($array, $member)</code>.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>array:insert-before(["a", "b", "c", "d"], 3, ("x", "y"))</code> returns <code>["a", "b", ("x", "y"), "c", "d"]</code>.</p><p>The expression <code>array:insert-before(["a", "b", "c", "d"], 5, ("x", "y"))</code> returns <code>["a", "b", "c", "d", ("x", "y")]</code>.</p><p>The expression <code>array:insert-before(["a", "b", "c", "d"], 3, ["x", "y"])</code> returns <code>["a", "b", ["x", "y"], "c", "d"]</code>.</p></def></gitem></glist></div3><div3 id="func-array-head"><head>array:head</head><glist><gitem><label>Summary</label><def><p>Returns the first member of an array, that is <code>$array(1)</code>.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="head" return-type="item()*" isOp="no" prefix="array" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="array" type="array(*)"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>The function returns first member of <code>$array</code>, that is the value of <code>$array(1)</code>.</p></def></gitem><gitem><label>Error Conditions</label><def><p>A dynamic error occurs <errorref class="AY" code="0001"/> if <code>$array</code> is empty.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>array:head([5, 6, 7, 8])</code> returns <code>5</code>.</p><p>The expression <code>array:head([["a", "b"], ["c", "d"]])</code> returns <code>["a", "b"]</code>.</p><p>The expression <code>array:head([("a", "b"), ("c", "d")])</code> returns <code>"a", "b"</code>.</p></def></gitem></glist></div3><div3 id="func-array-tail"><head>array:tail</head><glist><gitem><label>Summary</label><def><p>Returns an array containing all members except the first from a supplied array.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="tail" return-type="array(*)" isOp="no" prefix="array" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="array" type="array(*)"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>The function returns an array containing all members of the supplied array except the first,
            that is <code>array:remove($array, 1)</code>.</p></def></gitem><gitem><label>Error Conditions</label><def><p>A dynamic error occurs <errorref class="AY" code="0001"/> if <code>$array</code> is empty.</p></def></gitem><gitem><label>Notes</label><def><p role="note">If the supplied array contains exactly one member, the result will be an empty array.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>array:tail([5, 6, 7, 8])</code> returns <code>[6, 7, 8]</code>.</p><p>The expression <code>array:tail([5])</code> returns <code>[ ]</code>.</p></def></gitem></glist></div3><div3 id="func-array-reverse"><head>array:reverse</head><glist><gitem><label>Summary</label><def><p>Returns an array containing all the members of a supplied array, but in reverse order.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="reverse" return-type="array(*)" isOp="no" prefix="array" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="array" type="array(*)"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>The function returns the result of the expression:
         <code>array:join( fn:reverse(1 to array:size($array)) ! [$array(.)] )</code></p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>array:reverse(["a", "b", "c", "d"])</code> returns <code>["d", "c", "b", "a"]</code>.</p><p>The expression <code>array:reverse([("a", "b"), ("c", "d")])</code> returns <code>[("c", "d"), ("a", "b")]</code>.</p><p>The expression <code>array:reverse([(1 to 5)])</code> returns <code>[(1, 2, 3, 4, 5)]</code>.</p><p>The expression <code>array:reverse([])</code> returns <code>[]</code>.</p></def></gitem></glist></div3><div3 id="func-array-join"><head>array:join</head><glist><gitem><label>Summary</label><def><p>Concatenates the contents of several arrays into a single array.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="join" return-type="array(*)" isOp="no" prefix="array" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="arrays" type="array(*)*"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>The function can be expressed as follows in XQuery:</p><eg diff="chg" at="E" xml:space="preserve"><code>
declare function array:join($arrays as array(*)*) as array(*) {
   if (fn:empty($arrays))
      then []
   else if (fn:count($arrays) eq 1)
      then $arrays
   else 
      op:array-concat(fn:head($arrays), array:join(fn:tail($arrays)))
};</code></eg></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>array:join(())</code> returns <code>[ ]</code>.</p><p>The expression <code>array:join([1, 2, 3])</code> returns <code>[1, 2, 3]</code>.</p><p>The expression <code>array:join((["a", "b"], ["c", "d"]))</code> returns <code>["a", "b", "c", "d"]</code>.</p><p>The expression <code>array:join((["a", "b"], ["c", "d"], [ ]))</code> returns <code>["a", "b", "c", "d"]</code>.</p><p>The expression <code>array:join((["a", "b"], ["c", "d"], [["e", "f"]]))</code> returns <code>["a", "b", "c", "d", ["e", "f"]]</code>.</p></def></gitem></glist></div3><div3 id="func-array-for-each"><head>array:for-each</head><glist><gitem><label>Summary</label><def><p>Returns an array whose size is the same as <code>array:size($array)</code>, in which
            each member is computed by applying <code>$function</code> to the corresponding member of
            <code>$array</code>.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="for-each" return-type="array(*)" isOp="no" prefix="array" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="array" type="array(*)"/><arg name="action" type="function(item()*) as item()*"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>, <termref def="dt-focus-independent">focus-independent</termref>,  and <termref def="dt-higher-order">higher-order</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>Returns the result of the expression:
         <code>array:join( (1 to array:size($array)) ! [ $action($array(.)) ] )</code></p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>array:for-each(["A", "B", 1, 2], function($z) {$z instance of xs:integer})</code> returns <code>[false(), false(), true(), true()]</code>.</p><p>The expression <code>array:for-each(["the cat", "sat", "on the mat"], fn:tokenize#1)</code> returns <code>[("the", "cat"), "sat", ("on", "the", "mat")]</code>.</p></def></gitem></glist></div3><div3 id="func-array-filter"><head>array:filter</head><glist><gitem><label>Summary</label><def><p>Returns an array containing those members of the <code>$array</code> for which 
            <code>$function</code> returns true.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="filter" return-type="array(*)" isOp="no" prefix="array" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="array" type="array(*)"/><arg name="function" type="function(item()*) as xs:boolean"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>, <termref def="dt-focus-independent">focus-independent</termref>,  and <termref def="dt-higher-order">higher-order</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>The effect of the function is equivalent to the following recursive definition:</p><eg xml:space="preserve">
if (array:size($array) eq 0)
then [ ]
else op:array-concat(
        if ($function(array:head($array))) then array:head($array) else [ ],
        array:filter(array:tail($array))
     )
</eg></def></gitem><gitem><label>Error Conditions</label><def><p>As a consequence of the function signature and the function calling rules, a type error occurs if the supplied
            function <code>$function</code> returns anything other than a single <code>xs:boolean</code> item; there is no conversion 
            to an effective boolean value.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>array:filter(["A", "B", 1, 2], function($x) {$x instance of xs:integer})</code> returns <code>[1, 2]</code>.</p><p>The expression <code>array:filter(["the cat", "sat", "on the mat"], function($s){fn:count(fn:tokenize($s)) gt 1})</code> returns <code>["the cat", "on the mat"]</code>.</p><p>The expression <code>array:filter(["A", "B", "", 0, 1], boolean#1)</code> returns <code>["A", "B", 1]</code>.</p></def></gitem></glist></div3><div3 id="func-array-fold-left"><head>array:fold-left</head><glist><gitem><label>Summary</label><def><p>Evaluates the supplied function cumulatively on successive members of the supplied
            array.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="fold-left" return-type="item()*" isOp="no" prefix="array" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="array" type="array(*)"/><arg name="zero" type="item()*"/><arg name="function" type="function(item()*, item()*) as item()*"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>, <termref def="dt-focus-independent">focus-independent</termref>,  and <termref def="dt-higher-order">higher-order</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>The effect of the function is equivalent to the following recursive definition:</p><eg diff="chg" at="F-bug30045" xml:space="preserve">
if (array:size($array) eq 0)
then $zero
else array:fold-left(array:tail($array), 
                     $function($zero, array:head($array)), 
                     $function )
         </eg></def></gitem><gitem><label>Notes</label><def><p role="note">If the supplied array is empty, the function returns <code>$zero</code>.</p><p role="note">If the supplied array contains a single member <code>$m</code>, the function returns <code>$zero =&gt; $function($m)</code>.</p><p role="note">If the supplied array contains two members <code>$m</code> and <code>$n</code>, the function returns 
            <code>$zero =&gt; $function($m) =&gt; $function($n)</code>; and similarly for an input array with more than two members.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>array:fold-left([true(), true(), false()], true(), function($x, $y){$x and $y})</code> returns <code>false()</code>. <emph>(Returns true if every member of the input array has an effective boolean value of <code>true()</code>.)</emph></p><p>The expression <code>array:fold-left([true(), true(), false()], false(), function($x, $y){$x or $y})</code> returns <code>true()</code>. <emph>(Returns true if at least one member of the input array has an effective boolean value of <code>true()</code>.)</emph></p><p>The expression <code>array:fold-left([1,2,3], [], function($x, $y){[$x, $y]})</code> returns <code>[[[[], 1], 2], 3]</code>.</p></def></gitem></glist></div3><div3 id="func-array-fold-right"><head>array:fold-right</head><glist><gitem><label>Summary</label><def><p>Evaluates the supplied function cumulatively on successive values of the supplied
            array.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="fold-right" return-type="item()*" isOp="no" prefix="array" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="array" type="array(*)"/><arg name="zero" type="item()*"/><arg name="function" type="function(item()*, item()*) as item()*"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>, <termref def="dt-focus-independent">focus-independent</termref>,  and <termref def="dt-higher-order">higher-order</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>The effect of the function is equivalent to the following recursive definition:</p><eg diff="chg" at="F-bug30045" xml:space="preserve">
if (array:size($array) eq 0)
then $zero
else $function( array:head($array), 
                array:fold-right(array:tail($array), $zero, $function) 
              )
         </eg></def></gitem><gitem><label>Notes</label><def><p role="note">If the supplied array is empty, the function returns <code>$zero</code>.</p><p role="note">If the supplied array contains a single member <code>$m</code>, the function returns <code>$function($m, $zero)</code>.</p><p role="note">If the supplied array contains two members <code>$m</code> and <code>$n</code>, the function returns 
            <code>$function($m, $function($n, $zero))</code>; and similarly for an input array with more than two members.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>array:fold-right([true(), true(), false()], true(), function($x, $y){$x and $y})</code> returns <code>false()</code>. <emph>(Returns true if every member of the input array has an effective boolean value of <code>true()</code>.)</emph></p><p>The expression <code>array:fold-right([true(), true(), false()], false(), function($x, $y){$x or $y})</code> returns <code>true()</code>. <emph>(Returns true if at least one member of the input array has an effective boolean value of <code>true()</code>.)</emph></p><p>The expression <code>array:fold-right([1,2,3], [], function($x, $y){[$x, $y]})</code> returns <code>[1, [2, [3, []]]]</code>.</p></def></gitem></glist></div3><div3 id="func-array-for-each-pair"><head>array:for-each-pair</head><glist><gitem><label>Summary</label><def><p>Returns an array obtained by evaluating the supplied function once for each pair of members at the same position in
            the two supplied arrays.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="for-each-pair" return-type="array(*)" isOp="no" prefix="array" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="array1" type="array(*)"/><arg name="array2" type="array(*)"/><arg name="function" type="function(item()*, item()*) as item()*"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>, <termref def="dt-focus-independent">focus-independent</termref>,  and <termref def="dt-higher-order">higher-order</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>Returns the result of the recursive expression:</p><eg xml:space="preserve"><code>
if (array:size($array1) eq 0 or array:size($array2) eq 0)
then [ ]
else array:concat(
        $function(array:head($array1), array:head($array2)), 
        array:for-each-pair(array:tail($array1), array:tail($array2), $function)
     )
         </code></eg></def></gitem><gitem><label>Notes</label><def><p role="note">If the arrays have different size, excess members in the longer array are ignored.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>array:for-each-pair(["A", "B", "C"], [1, 2, 3], function($x, $y) { array {$x, $y}})</code> returns <code>[["A", 1], ["B", 2], ["C", 3]]</code>.</p><p>The expression <code>let $A := ["A", "B", "C", "D"] return array:for-each-pair($A, array:tail($A), concat#2)</code> returns <code>["AB", "BC", "CD"]</code>.</p></def></gitem></glist></div3><div3 id="func-array-sort"><head>array:sort</head><glist><gitem><label>Summary</label><def><p diff="chg" at="C">Returns an array containing all the members of the supplied array, sorted 
            according to the value of a sort key supplied as a function.</p></def></gitem><gitem><label>Signatures</label><def><example role="signature"><proto name="sort" return-type="array(*)" isOp="no" prefix="array" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="array" type="array(*)"/></proto></example><example role="signature"><proto name="sort" return-type="array(*)" isOp="no" prefix="array" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="array" type="array(*)"/><arg name="collation" type="xs:string?"/></proto></example><example role="signature"><proto name="sort" return-type="array(*)" isOp="no" prefix="array" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="array" type="array(*)"/><arg name="collation" type="xs:string?"/><arg name="key" type="function(item()*) as xs:anyAtomicType*"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>The one-argument form of this function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-dependent">context-dependent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>.  It depends on 
		collations.
	</p><p>The two-argument form of this function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-dependent">context-dependent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>.  It depends on 
		collations.
	</p><p>The two-argument form of this function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>, <termref def="dt-focus-independent">focus-independent</termref>,  and <termref def="dt-higher-order">higher-order</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>Calling the single-argument version of the function is equivalent to calling the two-argument form
            with <code>default-collation()</code> as the second argument: that is, it sorts the members of an array according
            to the typed value of the items, using the default collation to compare strings.</p><p>Calling the two-argument version of the function is equivalent to calling the three-argument form
            with <code>fn:data#1</code> as the third argument: that is, it sorts the members of an array according
            to the typed value of the items, using a specified collation to compare strings.</p><p>In the case of both <code>array:sort#2</code> and <code>array:sort#3</code>, supplying an empty
            sequence as the second argument is equivalent to supplying <code>fn:default-collation()</code>. For more
            information on collations see <specref ref="choosing-a-collation"/>.</p><p>The result of the function is obtained as follows:</p><ulist><item><p>For each member of the array <code>$array</code>, the function supplied as <code>$key</code> 
               is evaluated with that member as its argument. 
               The resulting values are the sort keys of the members of the array.
            </p></item><item><p>The result array contains the same members as the input array <code>$array</code>, but generally in a different order.</p></item><item><p>Let <var>$C</var> be the selected collation, or the default collation where applicable.</p></item><item><p>The order of items in the result is such that, given two items <code>$A</code> and <code>$B</code>:</p><ulist><item><p>If <code>(fn:deep-equal($key($A), $key($B), $C)</code>, then the relative order of <code>$A</code> and <code>$B</code> 
                     in the output is the same as their relative order in the input (that is, the sort is stable)
                  </p></item><item><p>Otherwise, if <code>(deep-less-than($key($A), $key($B), $C)</code>, then <code>$A</code> precedes <code>$B</code> in the output. 
                     The function <code>deep-less-than</code> is defined as the boolean result of the expression:
                  </p><eg diff="chg" at="D" xml:space="preserve"><code>if (fn:empty($A)) 
     then fn:exists($B)
else if (fn:deep-equal($A[1], $B[1], $C)) 
     then deep-less-than(fn:tail($A), fn:tail($B), $C)
else if ($A[1] ne $A[1] (:that is, $A[1] is NaN:)) 
     then fn:true()
else if (is-string($A[1]) and is-string($B[1]) 
     then fn:compare($A[1], $B[1], $C) lt 0
else $A[1] lt $B[1]</code></eg><p>where the function <code>is-string($X)</code> returns true if and only if <code>$X</code> is an instance of 
                        <code>xs:string</code>, <code>xs:anyURI</code>, or <code>xs:untypedAtomic</code>.</p><p>This ordering of sequences is referred to by mathematicians as "lexicographic ordering".
                     </p></item></ulist></item></ulist></def></gitem><gitem><label>Error Conditions</label><def><p>If the set of computed sort keys contains values that are not comparable using the <code>le</code> operator then the sort 
            operation will fail with a dynamic error.
         </p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>array:sort([1, 4, 6, 5, 3])</code> returns <code>[1, 3, 4, 5, 6]</code>.</p><p>The expression <code>array:sort([1, -2, 5, 10, -10, 10, 8], (), fn:abs#1)</code> returns <code>[1, -2, 5, 8, 10, -10, 10]</code>.</p><p>The expression <code>array:sort([(1,0), (1,1), (0,1), (0,0)])</code> returns <code>[(0,0), (0,1), (1,0), (1,1)]</code>.</p><p>To sort an array of strings <code>$in</code> using Swedish collation:</p><eg xml:space="preserve">
let $SWEDISH := "http://www.w3.org/2013/collation/UCA?lang=se"
return array:sort($in, $SWEDISH)
            </eg><p>To sort an array of maps representing employees, using last name as the major sort key and first name as the minor sort key,
               with the default collation:
            </p><eg xml:space="preserve">array:sort($employees, (), function($emp) {$emp?name?last, $emp?name?first})</eg></def></gitem></glist></div3><div3 id="func-array-flatten" diff="add" at="C"><head>array:flatten</head><glist><gitem><label>Summary</label><def><p>Replaces any array appearing in a supplied sequence with the members of the array, recursively.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto name="flatten" return-type="item()*" isOp="no" prefix="array" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="input" type="item()*"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>The function processes the items in the supplied sequence <code>$input</code> as follows:</p><ulist><item><p>An item that is an array is replaced by its members, retaining order.</p></item><item><p>Any other item is retained unchanged.</p></item></ulist><p>The process is then repeated so long as the sequence contains an array among its items.</p><p>The function is equivalent to the following XQuery implementation (assuming static typing is not in force):</p><eg xml:space="preserve"><code>declare function flatten ($S as item()*) {
    for $s in $S return (
      typeswitch($s)
        case $a as array(*) return flatten($a?*)
        default return $s
)}</code></eg></def></gitem><gitem><label>Notes</label><def><p role="note">The argument to the function will often be a single array item, but this is not essential.</p><p role="note">Unlike atomization, this function retains any nodes contained in the array.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>array:flatten([1, 4, 6, 5, 3])</code> returns <code>(1, 4, 6, 5, 3)</code>.</p><p>The expression <code>array:flatten(([1, 2, 5], [[10, 11], 12], [], 13))</code> returns <code>(1, 2, 5, 10, 11, 12, 13)</code>.</p><p>The expression <code>array:flatten([(1,0), (1,1), (0,1), (0,0)])</code> returns <code>(1, 0, 1, 1, 0, 1, 0, 0)</code>.</p></def></gitem></glist></div3></div2><div2 id="json"><head>Conversion to and from JSON</head><p>JSON is a popular format for exchange of structured data on the web: it is specified in <bibref ref="rfc7159"/>. 
                     This section describes facilities
                     allowing JSON data to be converted to and from XDM values.</p><p diff="add" at="D">This specification describes two ways of representing JSON data losslessly
                using XDM constructs. The first method uses XDM maps to represent JSON objects, and XDM arrays to
                represent JSON arrays. The second method represents all JSON constructs using XDM element and attribute nodes.</p><p diff="del" at="D">A number of mappings between JSON structures and XML documents have been proposed. Some of these
                  are lossless but complex; others are simpler but lose information. Because none of these mappings
                  is ideal in all circumstances, this specification does not define such a mapping, and instead converts
                  JSON structures losslessly to XDM maps and atomic values, which can then be further converted
                  to XML trees in any desired representation using XQuery or XSLT node construction operations.</p><div3 id="json-to-maps-and-arrays"><head>Representing JSON using maps and arrays</head><p>This section defines a mapping from JSON data to XDM maps and arrays. Two functions are available 
                   to support this mapping: <code>fn:parse-json</code> and <code>fn:serialize</code> (with options
                     selecting JSON as the output method).
                  The <code>fn:parse-json</code> function will accept any JSON text as input, and converts it 
                  to XDM data values. The <code>fn:serialize</code> function (with JSON as the output method) will accept any XDM
                  value produced using <code>fn:parse-json</code> and convert it back to the original JSON text
                  (subject to insignificant variations such as reordering the properties in a JSON object). </p><note diff="add" at="D"><p>The conversion is lossless if recommended JSON good practice is followed. Information may however be lost if
                   (a) JSON numbers are not exactly representable as double-precision floating point, or (b) duplicate key
                   values appear within a JSON object.</p></note><p>The representation of JSON data produced by the <code>fn:parse-json</code> function
                      has been chosen with ease of manipulation as a design aim. For example, a simple JSON object
                      such as <code>{"Sun":1, "Mon":2, "Tue":3, ...}</code> produces a simple map, so if the result
                      of parsing is held in <code>$weekdays</code>, the number for a given weekday can be extracted
                      using an expression such as <code>$weekdays?Tue</code>. Similarly, a simple array such as
                      <code>["Sun", "Mon", "Tue", ...]</code> produces an array that can be addressed as, for example,
                      <code>$weekdays(3)</code>. A more deeply nested structure can be addressed in a similar way:
                      for example if the JSON text is an array of person objects, each of which has a property named 
                      "phones" which is an array of strings containing phone numbers, then the first phone number of
                      each person in the data can be addressed as <code>$data?phones(1)</code>.</p></div3><div3 id="json-to-xml-mapping"><head>XML Representation of JSON</head><p>This section defines a mapping from JSON data to XML (specifically, to XDM element and attribute nodes). A
                  function <code>fn:json-to-xml</code> is provided to take a JSON string as input and convert it
                  to the XML representation, and a second function <code>fn:xml-to-json</code> performs the reverse operation.</p><p>The XML representation is designed to be capable of representing any valid JSON text including
                  one that uses characters which are not valid in XML. The transformation is normally lossless: that is,
                  distinct JSON texts convert to distinct XML representations. When converting JSON to XML, options are provided
                  to reject unsupported characters, to replace them with a substitute character, or to leave them in
                  backslash-escaped form.</p><note><p>The conversion is lossless if recommended JSON good practice is followed. Information may however be lost if
                  (a) JSON numbers are not exactly representable as double-precision floating point, or (b) duplicate key
                  values appear within a JSON object.</p></note><p>The following example demonstrates the correspondence of a JSON text and the corresponding XML
                  representation. </p><example><head>A JSON Text and its XML Representation</head><p>Consider the following JSON text:</p><eg xml:space="preserve">
 {
    "desc"    : "Distances between several cities, in kilometers.",
    "updated" : "2014-02-04T18:50:45",
    "uptodate": true,
    "author"  : null,
    "cities"  : {
        "Brussels": [
                      {"to": "London",    "distance": 322},
                      {"to": "Paris",     "distance": 265},
                      {"to": "Amsterdam", "distance": 173}
                    ],
        "London": [
                      {"to": "Brussels",  "distance": 322},
                      {"to": "Paris",     "distance": 344},
                      {"to": "Amsterdam", "distance": 358}
                  ],
        "Paris": [
                      {"to": "Brussels",  "distance": 265},
                      {"to": "London",    "distance": 344},
                      {"to": "Amsterdam", "distance": 431}
                 ],
        "Amsterdam": [
                      {"to": "Brussels",  "distance": 173},
                      {"to": "London",    "distance": 358},
                      {"to": "Paris",     "distance": 431}
                     ]
     }
}
                  </eg><p>The XML representation of this text is as follows. Whitespace is included in the XML representation for purposes of illustration, 
                     but it will not necessarily be present in the output of the 
                     <function>json-to-xml</function> function.</p><eg xml:space="preserve">
  &lt;map xmlns="http://www.w3.org/2005/xpath-functions"&gt;
    &lt;string key='desc'&gt;Distances between several cities, in kilometers.&lt;/string&gt;
    &lt;string key='updated'&gt;2014-02-04T18:50:45&lt;/string&gt;
    &lt;boolean key="uptodate"&gt;true&lt;/boolean&gt;
    &lt;null key="author"/&gt;
    &lt;map key='cities'&gt;
      &lt;array key="Brussels"&gt;
        &lt;map&gt;
            &lt;string key="to"&gt;London&lt;/string&gt;
            &lt;number key="distance"&gt;322&lt;/number&gt;
        &lt;/map&gt; 
        &lt;map&gt;
            &lt;string key="to"&gt;Paris&lt;/string&gt;
            &lt;number key="distance"&gt;265&lt;/number&gt;
        &lt;/map&gt; 
        &lt;map&gt;
            &lt;string key="to"&gt;Amsterdam&lt;/string&gt;
            &lt;number key="distance"&gt;173&lt;/number&gt;
        &lt;/map&gt; 
      &lt;/array&gt;
      &lt;array key="London"&gt;
        &lt;map&gt;
            &lt;string key="to"&gt;Brussels&lt;/string&gt;
            &lt;number key="distance"&gt;322&lt;/number&gt;
        &lt;/map&gt; 
        &lt;map&gt;
            &lt;string key="to"&gt;Paris&lt;/string&gt;
            &lt;number key="distance"&gt;344&lt;/number&gt;
        &lt;/map&gt; 
        &lt;map&gt;
            &lt;string key="to"&gt;Amsterdam&lt;/string&gt;
            &lt;number key="distance"&gt;358&lt;/number&gt;
        &lt;/map&gt; 
      &lt;/array&gt;
      &lt;array key="Paris"&gt;
        &lt;map&gt;
            &lt;string key="to"&gt;Brussels&lt;/string&gt;
            &lt;number key="distance"&gt;265&lt;/number&gt;
        &lt;/map&gt; 
        &lt;map&gt;
            &lt;string key="to"&gt;London&lt;/string&gt;
            &lt;number key="distance"&gt;344&lt;/number&gt;
        &lt;/map&gt; 
        &lt;map&gt;
            &lt;string key="to"&gt;Amsterdam&lt;/string&gt;
            &lt;number key="distance"&gt;431&lt;/number&gt;
        &lt;/map&gt;  
      &lt;/array&gt;
      &lt;array key="Amsterdam"&gt;
        &lt;map&gt;
            &lt;string key="to"&gt;Brussels&lt;/string&gt;
            &lt;number key="distance"&gt;173&lt;/number&gt;
        &lt;/map&gt; 
        &lt;map&gt;
            &lt;string key="to"&gt;London&lt;/string&gt;
            &lt;number key="distance"&gt;358&lt;/number&gt;
        &lt;/map&gt; 
        &lt;map&gt;
            &lt;string key="to"&gt;Paris&lt;/string&gt;
            &lt;number key="distance"&gt;431&lt;/number&gt;
        &lt;/map&gt;
      &lt;/array&gt;
    &lt;/map&gt;  
  &lt;/map&gt;</eg></example><p>An XSD 1.0 schema for the XML representation is provided in <specref ref="schema-for-json"/>.
                  It is not necessary to import this schema into the static context unless the stylesheet or query
                  makes explicit reference to the components defined in the schema. If the stylesheet or query does import a schema
                  for the namespace <code>http://www.w3.org/2005/xpath-functions</code>, then:</p><olist><item><p>Unless the host language specifies otherwise, the processor (if it is schema-aware) 
                     <rfc2119>must</rfc2119> recognize an import declaration for
                     this namespace, whether or not a schema location is supplied.</p></item><item><p>If a schema location is provided, then the schema document at that location <rfc2119>must</rfc2119>
                     be equivalent to the schema document at <specref ref="schema-for-json"/>; the effect if it is not equivalent is
                     <termref def="implementation-dependent"/></p></item></olist><p>The rules governing the mapping from JSON to XML are as follows. In these rules, the phrase 
                  "an element named N" is to be interpreted as meaning "an element node whose local name is N and whose
                  namespace URI is <code>http://www.w3.org/2005/xpath-functions</code>".</p><olist><item><p>The JSON value <code>null</code> is represented by an element named <code>null</code>, with empty content.</p></item><item><p>The JSON values <code>true</code> and <code>false</code> are represented by an element named <code>boolean</code>,
                     with content conforming to the type <code>xs:boolean</code>. When the element is created by the 
                     <code>fn:json-to-xml</code> function, the string value of the element will be <code>true</code> or <code>false</code>.
                     The <code>fn:xml-to-json</code> function also recognizes other strings that validate as <code>xs:boolean</code>,
                     for example <code>1</code> and <code>0</code>. Leading and trailing whitespace is accepted.
                  </p></item><item><p>A JSON number is represented by an element named <code>number</code>,
                     with content conforming to the type <code>xs:double</code>, with the additional restriction that the value
                     must not be positive or negative infinity, nor <code>NaN</code>. The
                  <code>fn:json-to-xml</code> function creates an element whose string value is lexically the same as the JSON representation
                  of the number. The <code>fn:xml-to-json</code> function generates a JSON representation that is the result of casting the
                  (typed or untyped) value of the node to <code>xs:double</code> and then casting the result to <code>xs:string</code>.
                     Leading and trailing whitespace is accepted.
                     Since JSON does not impose limits on the range or precision
                     of numbers, these rules mean that conversion from JSON to XML will always succeed, and will retain full precision
                     in the lexical representation unless the data model implementation is one that reconstructs the string value from 
                     the typed value. In the reverse direction, conversion from XML to JSON may fail if the value is infinity or <code>NaN</code>,
                     or if the string value is such that casting to <code>xs:double</code> produces positive or negative infinity.                    
                  </p></item><item><p>A JSON string is represented by an element named <code>string</code>, with
                     content conforming to the type <code>xs:string</code>. The <code>string</code> element has two
                  alternative representations: escaped form, and unescaped form.</p></item><item><p>A JSON array is represented by an element named <code>array</code>. The content is a sequence of
                     child elements representing the members of the array in order, each such element being the representation
                     of the array member obtained by applying these rules recursively.</p></item><item><p>A JSON object is represented by an element named <code>map</code>. The content is a sequence
                     of child elements each of which represents one of the name/value pairs in the object. The representation of the
                     name/value pair <var>N:V</var> is obtained by taking the element that represents the value <var>V</var> (by applying these
                     rules recursively) and adding an attribute with name <code>key</code> (in no namespace), whose
                     value is <var>N</var> as an instance of <code>xs:string</code>. The functions <code>fn:json-to-xml</code> and
                  <code>fn:xml-to-json</code> both retain the order of entries, subject to rules about how duplicate keys are handled. The
                  key may be represented in escaped or unescaped form.</p></item></olist><p>The attribute <code>escaped="true"</code> may be specified on a <code>string</code> element to indicate
                  that the string value contains backslash-escaped characters that are to be interpreted according to the JSON
                  rules. The attribute <code>escaped-key="true"</code> may be specified on any element with a <code>key</code> attribute to indicate
                  that the key contains backslash-escaped characters that are to be interpreted according to the JSON
                  rules. Both attributes have the default value <code>false</code>, signifying that the relevant value is in unescaped form.
               In unescaped form, the backslash character has no special significance (it represents itself).</p><p>The JSON grammar for <code>number</code> is a subset of the lexical space of
                  the XSD type <code>xs:double</code>. The mapping from JSON <code>number</code> values to <code>xs:double</code>
                  values is defined by the XPath rules for casting from <code>xs:string</code> to <code>xs:double</code>. Note that
                  these rules will never generate an error for out-of-range values; instead very large or very small values will be
                  converted to <code>+INF</code> or <code>-INF</code>. Since JSON does not impose limits on the range or precision
                  of numbers, the conversion is not guaranteed to retain full precision.</p><p>Although the order of entries in a JSON object is generally considered to have no significance, the functions
                  <code>json-to-xml</code> and <code>json-to-xml</code> both retain order.</p><p>The XDM representation of a JSON value may either be untyped (all elements annotated as <code>xs:untyped</code>, attributes
                  as <code>xs:untypedAtomic</code>), or it may be typed. If it is typed, then it <rfc2119>must</rfc2119> have the type
                  annotations obtained by validating the untyped representation against the schema given in <specref ref="schema-for-json"/>.
                  If it is untyped, then it <rfc2119>must</rfc2119> be an XDM instance such that validation against this schema would succeed;
                  with the proviso that all attributes other than those in no namespace or in namespace <code>http://www.w3.org/2005/xpath-functions</code>
                  are ignored, including attributes such as <code>xsi:type</code> and <code>xsi:nil</code> that would normally influence the process
                  of schema validation.</p><p>The namespace prefix associated with the namespace <code>http://www.w3.org/2005/xpath-functions</code> (if any) is immaterial.
               The effect of the <code>fn:xml-to-json</code> function does not depend on the choice of prefix, and the prefix (if any) generated by the
               <code>fn:json-to-xml</code> function is <termref def="implementation-dependent">implementation-dependent</termref>.</p></div3></div2><div2 id="json-functions"><head>Functions on JSON Data</head><p>The functions listed parse or serialize JSON data.</p><table class="index"><thead><tr><th rowspan="1" colspan="1">Function</th><th rowspan="1" colspan="1">Meaning</th></tr></thead><tbody><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:parse-json</code></td><td rowspan="1" colspan="1">Parses a string supplied in the form of a JSON text, returning the results typically in the form
            of a map or array.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:json-doc</code></td><td rowspan="1" colspan="1">Reads an external resource containing JSON, and returns the result of parsing the resource as JSON.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:json-to-xml</code></td><td rowspan="1" colspan="1">Parses a string supplied in the form of a JSON text, returning the results in the form
            of an XML <phrase diff="chg" at="P">document node</phrase>.</td></tr><tr><td style="white-space:nowrap; vertical-align:top" rowspan="1" colspan="1"><code style="padding-right: 10px">fn:xml-to-json</code></td><td rowspan="1" colspan="1">Converts an XML tree, whose format corresponds to the XML representation of JSON defined
            in this specification, into a string conforming to the JSON grammar.</td></tr></tbody></table><p>Note also that the function <code>fn:serialize</code> has an option to act as the inverse function to <code>fn:parse-json</code>.</p><div3 id="func-parse-json"><head>fn:parse-json</head><glist><gitem><label>Summary</label><def><p>Parses a string supplied in the form of a JSON text, returning the results typically in the form
            of a map or array.</p></def></gitem><gitem><label>Signatures</label><def><example role="signature"><proto name="parse-json" return-type="item()?" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="json-text" type="xs:string?"/></proto></example><example role="signature"><proto name="parse-json" return-type="item()?" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="json-text" type="xs:string?"/><arg name="options" type="map(*)"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>The effect of the one-argument form of this function is the same as calling the
            two-argument form with an empty map as the value of the <code>$options</code>
            argument.</p><p>The first argument is a JSON text as defined in <bibref ref="rfc7159"/>, in the form of a string. The function
            parses this string to return an XDM value.</p><p diff="add" at="B">If the value of <code>$json-text</code> is the empty sequence, the function returns the empty sequence.</p><note diff="add" at="B"><p>The result will also be an empty sequence if <code>$json-text</code> is the string <code>"null"</code>.</p></note><p diff="chg" at="D">The <code>$options</code> argument can be used to control the way in which the parsing
            takes place. The <termref def="option-parameter-conventions">option parameter conventions</termref> apply.</p><p>The entries that may appear in the <code>$options</code> map are as follows:</p><table style="border-collapse: collapse"><thead><tr style="border-top: 2px solid black; border-bottom: 2px solid black"><th style="text-align:left; padding-right: 10px; " rowspan="1" colspan="1">Key</th><th style="text-align:left; padding-right: 10px; " rowspan="1" colspan="1">Value</th><th style="text-align:left" rowspan="1" colspan="1">Meaning</th></tr></thead><tbody><tr><td style="white-space:nowrap; padding-right: 10px; vertical-align:top; border-bottom: 2px solid black" rowspan="3" colspan="1"><code>liberal</code></td><td style="vertical-align:top; border-bottom: 1px solid black" colspan="2" rowspan="1">Determines whether deviations from the syntax of RFC7159 are permitted.<ulist><item><p><term>Type: </term><code>xs:boolean</code></p></item><item><p><term>Default: </term><code>false</code></p></item></ulist></td></tr><tr><td style="white-space:nowrap; padding-right: 10px; vertical-align:top; border-bottom: 1px solid black" rowspan="1" colspan="1"><code>false</code></td><td style="vertical-align:top; border-bottom: 1px solid black" rowspan="1" colspan="1">
                     The input <rfc2119>must</rfc2119> consist of <phrase diff="add" at="D">an optional byte order mark (which is ignored) followed by</phrase> a string
                     that conforms to the grammar of <code>JSON-text</code> in <bibref ref="rfc7159"/>. An error <rfc2119>must</rfc2119> be raised
                     <errorref class="JS" code="0001"/> if the input does not conform to the grammar.
                  </td></tr><tr><td style="white-space:nowrap; padding-right: 10px; vertical-align:top; border-bottom: 2px solid black" rowspan="1" colspan="1"><code>true</code></td><td style="vertical-align:top; border-bottom: 2px solid black" rowspan="1" colspan="1">
                     The input <rfc2119>may</rfc2119> contain deviations from the grammar of <bibref ref="rfc7159"/>,
                     which are handled in an <termref def="implementation-defined">implementation-defined</termref> way. (Note: some popular
                     extensions include allowing quotes on keys to be omitted, allowing a comma
                     to appear after the last item in an array, allowing leading zeroes in numbers, and allowing control characters such as
                     tab and newline to be present in unescaped form.) Since the extensions accepted
                     are implementation-defined, an error <rfc2119>may</rfc2119> be raised
                     <errorref class="JS" code="0001"/> if the input does not conform to the grammar.
                  </td></tr><tr><td style="white-space:nowrap; padding-right: 10px; vertical-align:top; border-bottom: 2px solid black" rowspan="4" colspan="1"><code>duplicates</code></td><td style="vertical-align:top; border-bottom: 1px solid black" colspan="2" rowspan="1">Determines the policy for handling duplicate keys in a JSON object.
                  To determine whether keys are duplicates, they are compared using the Unicode codepoint collation, after expanding escape
                  sequences, unless the <phrase diff="chg" at="D"><code>escape</code> option is set to <code>true</code></phrase>, in which
                  case keys are compared in escaped form. 
               <ulist><item><p><term>Type: </term><code>xs:string</code></p></item><item><p><term>Default: </term><code>use-first</code></p></item></ulist></td></tr><tr><td style="white-space:nowrap; padding-right: 10px; vertical-align:top; border-bottom: 1px solid black" rowspan="1" colspan="1"><code>reject</code></td><td style="vertical-align:top; border-bottom: 1px solid black" rowspan="1" colspan="1">
                     An error is raised <errorref class="JS" code="0003"/> if duplicate keys are encountered.
                  </td></tr><tr><td style="white-space:nowrap; padding-right: 10px; vertical-align:top; border-bottom: 1px solid black" rowspan="1" colspan="1"><code>use-first</code></td><td style="vertical-align:top; border-bottom: 1px solid black" rowspan="1" colspan="1">
                     If duplicate keys are present in a JSON object, all but the first of a set of duplicates are ignored.
                  </td></tr><tr><td style="white-space:nowrap; padding-right: 10px; vertical-align:top; border-bottom: 2px solid black" rowspan="1" colspan="1"><code>use-last</code></td><td style="vertical-align:top; border-bottom: 2px solid black" rowspan="1" colspan="1">
                     If duplicate keys are present in a JSON object, all but the last of a set of duplicates are ignored.
                  </td></tr><tr><td style="white-space:nowrap; padding-right: 10px; vertical-align:top; border-bottom: 2px solid black" rowspan="3" colspan="1"><code>escape</code></td><td style="vertical-align:top; border-bottom: 1px solid black" colspan="2" rowspan="1">Determines whether special characters are represented in the XDM output in backslash-escaped form.<ulist><item><p><term>Type: </term><code>xs:boolean</code></p></item><item><p><term>Default: </term><code>true</code></p></item></ulist></td></tr><tr><td style="white-space:nowrap; padding-right: 10px; vertical-align:top; border-bottom: 1px solid black" rowspan="1" colspan="1"><code>false</code></td><td style="vertical-align:top; border-bottom: 1px solid black" rowspan="1" colspan="1">
                     All characters in the input that are valid
                     in the version of XML supported by the implementation, whether or not they are represented 
                     in the input by means of an escape sequence, are represented as unescaped characters in the result. Any
                     characters or codepoints that are not valid XML characters 
                     (for example, unpaired surrogates) <phrase diff="add" at="D">are passed to the <code>fallback</code> function
                        as described below; in the absence of a fallback function, they are replaced by
                        the Unicode <code>REPLACEMENT CHARACTER</code> (<code>xFFFD</code>)</phrase>.
                  </td></tr><tr><td style="white-space:nowrap; padding-right: 10px; vertical-align:top; border-bottom: 2px solid black" rowspan="1" colspan="1"><code>true</code></td><td style="vertical-align:top; border-bottom: 2px solid black" rowspan="1" colspan="1">
                     JSON escape sequences are used in the result to represent special characters in the JSON input, as defined below, 
                     whether or not they were represented using JSON escape sequences in the input.
                     The characters that are considered "special" for this purpose are:
                     <ulist><item><p>all codepoints in the range <code>x00</code> to <code>x1F</code> 
                           or <code>x7F</code> to <code>x9F</code>;</p></item><item><p>all codepoints that do not represent characters that are valid in the version of XML supported by the processor,
                           including codepoints representing unpaired surrogates;</p></item><item><p>the backslash character itself (<code>x5C</code>).</p></item></ulist>
                     
                     Such characters are represented using a two-character
                     escape sequence where available (for example, <code>\t</code>), or a six-character escape sequence otherwise
                     (for example <code>\uDEAD</code>). Characters other than these are not escaped in the result, even if they
                     were escaped in the input.
                  </td></tr><tr><td style="white-space:nowrap; padding-right: 10px; vertical-align:top; border-bottom: 2px solid black" rowspan="2" colspan="1"><code>fallback</code></td><td style="vertical-align:top; border-bottom: 1px solid black" colspan="2" rowspan="1">
                  Provides a function which is called when the input contains an escape sequence 
                  that represents a character that is not valid in the version of XML
                  supported by the implementation. 
                  
                  It is an error to supply the <code>fallback</code> option if the <code>escape</code> option is present
                  with the value <code>true</code>.
               <ulist><item><p><term>Type: </term><code>function(xs:string) as xs:string</code></p></item><item><p><term>Default: </term><code>The default is effectively the function function($s){"&amp;#xFFFD;"}: that is,
                  a function that replaces the escape sequence with the Unicode REPLACEMENT CHARACTER.</code></p></item></ulist></td></tr><tr><td style="white-space:nowrap; padding-right: 10px; vertical-align:top; border-bottom: 2px solid black" rowspan="1" colspan="1"><code>User-supplied function</code></td><td style="vertical-align:top; border-bottom: 2px solid black" rowspan="1" colspan="1">
                     The function is called when the JSON input contains a special character (as defined under 
                     the <code>escape</code> option) that is valid according to the JSON 
                     grammar, whether the special character is represented in the input directly or as an escape sequence. 
                     The function is called once for any surrogate
                     that is not properly paired with another surrogate. The string supplied as the argument will always be a two- or six- character escape
                     sequence, starting with a backslash, that conforms to the rules in the JSON grammar (as extended by the
                     implementation if <code>liberal:true()</code> is specified): for example
                     <code>\b</code> or <code>\uFFFF</code> or <code>\uDEAD</code>. The function is <emph>not</emph>
                     called for an escape sequence that is invalid against the grammar (for example <code>\x0A</code>). The function returns a string
                     which is inserted into the result in place of the invalid character. The
                     function also has the option of raising a dynamic error by calling <code>fn:error</code>.
                  </td></tr></tbody></table><p>The various structures that can occur in JSON are transformed recursively to XDM values
            as follows:</p><olist><item><p>A JSON <emph>object</emph> is converted to a map. 
                  The entries in the map correspond to the key/value
                  pairs in the JSON object. The key is always of type <code>xs:string</code>; the
                  associated value may be of any type, and is the result of converting the JSON
                  value by recursive application of these rules. For example, the JSON text
                     <code>{"x":2, "y":5}</code> is transformed to the value <code>map{"x":2,
                     "y":5}</code>.</p><p>If duplicate keys are encountered in a JSON <emph>object</emph>, they are handled
                  as determined by the <code>duplicates</code> option defined above.</p></item><item><p>A JSON <emph>array</emph> is transformed to an array whose members are the result of converting
                  the corresponding member of the array by recursive application of these rules. For
                  example, the JSON text <code>["a", "b", null]</code> is transformed to the value
                     <code>["a", "b", ()]</code>.</p></item><item><p>A JSON <emph>string</emph> is converted to an <code>xs:string</code> value. 
               <phrase diff="chg" at="E">The handling of special characters depends on the
               <code>escape</code> and <code>fallback</code> options, as described in the table above.</phrase></p></item><item><p>A JSON <emph>number</emph> is converted to an <code>xs:double</code> value using
                  the rules for casting from <code>xs:string</code> to <code>xs:double</code>.</p></item><item><p>The JSON <emph>boolean</emph> values <code>true</code> and <code>false</code> are
                  converted to the corresponding <code>xs:boolean</code> values.</p></item><item><p>The JSON value <emph>null</emph> is converted to the empty sequence.</p></item></olist></def></gitem><gitem><label>Error Conditions</label><def><p>A dynamic error <errorref class="JS" code="0001"/> occurs if the value of
               <code>$input</code> does not conform to the JSON grammar, unless the option
            <code>"liberal":true()</code> is present and the processor chooses to accept the deviation.</p><p>A dynamic error <errorref class="JS" code="0003"/> occurs if the option
            <code>"duplicates":"reject"</code> is present and the value of
            <code>$input</code> contains a JSON object with duplicate keys.</p><p diff="add" at="D">A dynamic error <errorref class="JS" code="0005"/> occurs if the <code>$options</code>
            map contains an entry whose key is defined in this specification and whose value is not valid for that key,
         or if it contains an entry with the key <code>fallback</code> when the option <code>"escape":true()</code>
         is also present.</p></def></gitem><gitem><label>Notes</label><def><p role="note">The result of the function will be an instance of one of the following types. An
               <code>instance of</code> test (or in XQuery, <code>typeswitch</code>) can be used to
            distinguish them:</p><ulist role="note"><item><p><code>map(xs:string, item()?)</code> for a JSON object</p></item><item><p><code>array(item()?)</code> for a JSON array</p></item><item><p><code>xs:string</code> for a JSON string</p></item><item><p><code>xs:double</code> for a JSON number</p></item><item><p><code>xs:boolean</code> for a JSON boolean</p></item><item><p><code>empty-sequence()</code> for a JSON null (or for empty input)</p></item></ulist><p role="note">If the input starts with a byte order mark, this function ignores it. The byte order mark may have been added
         to the data stream in order to facilitate decoding of an octet stream to a character string, but since this function
         takes a character string as input, the byte order mark serves no useful purpose.</p><p role="note">The possibility of the input containing characters that are not valid in XML (for example, unpaired surrogates)
            arises only when such characters are expressed using JSON escape sequences. The is because the input to the function
            is an instance of <code>xs:string</code>, which by definition can only contain characters that are valid in XML.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>parse-json('{"x":1, "y":[3,4,5]}')</code> returns <code>map{"x":1e0,"y":[3e0,4e0,5e0]}</code>.</p><p>The expression <code>parse-json('"abcd"')</code> returns <code>"abcd"</code>.</p><p>The expression <code>parse-json('{"x":"\\", "y":"\u0025"}')</code> returns <code>map{"x":"\","y":"%"}</code>.</p><p>The expression <code>parse-json('{"x":"\\", "y":"\u0025"}', map{'escape':true()})</code> returns <code>map{"x":"\\","y":"%"}</code>.</p><p>The expression <code>parse-json('{"x":"\\", "y":"\u0000"}')</code> returns <code>map{"x":"\","y":codepoints-to-string(65533)}</code>.</p><p>The expression <code>parse-json('{"x":"\\", "y":"\u0000"}', map{'escape':true()})</code> returns <code>map{"x":"\\","y":"\u0000"}</code>.</p><p>The expression <code>parse-json('{"x":"\\", "y":"\u0000"}', map{'fallback':function($s){'['||$s||']'}})</code> returns <code>map{"x":"\","y":"[\u0000]"}</code>.</p></def></gitem></glist></div3><div3 id="func-json-doc"><head>fn:json-doc</head><glist><gitem><label>Summary</label><def><p>Reads an external resource containing JSON, and returns the result of parsing the resource as JSON.</p></def></gitem><gitem><label>Signatures</label><def><example role="signature"><proto name="json-doc" return-type="item()?" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="href" type="xs:string?"/></proto></example><example role="signature"><proto name="json-doc" return-type="item()?" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="href" type="xs:string?"/><arg name="options" type="map(*)"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-dependent">context-dependent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>.  It depends on 
		static base URI.
	</p></def></gitem><gitem><label>Rules</label><def><p>The effect of the single-argument call <code>fn:json-doc($H)</code> is the same as the effect of the two-argument call
            <code>fn:json-doc($H, map{})</code> where an empty map is supplied as the second argument.</p><p>The effect of the two-argument function call <code>fn:json-doc($H, $M)</code>is equivalent to the function composition
            <code>fn:unparsed-text($H) =&gt; fn:parse-json($M)</code>; except that:</p><olist><item><p diff="chg" at="B">The function <rfc2119>may</rfc2119> accept a resource in any encoding. <bibref ref="rfc7159"/> requires
               UTF-8, UTF-16, or UTF-32 to be accepted, but it is not an error if a different encoding is used. 
               Unless external encoding information is available, the function <rfc2119>must</rfc2119>
               assume that the encoding is one of UTF-8, UTF-16, or UTF-32, and <rfc2119>must</rfc2119> distinguish these cases by examination 
               of the initial octets of the resource.</p></item><item><p diff="chg" at="E">If the resource contains characters that are not valid in the version of XML used by the processor,
            then rather than raising an error as <code>fn:unparsed-text#1</code> does, the function replaces such characters by the equivalent
            JSON escape sequence prior to parsing.</p><note><p diff="add" at="E">Equivalently, the implementation can use some other internal representation of strings that allows non-XML characters to
            be manipulated.</p></note></item></olist><p diff="chg" at="B">If the value of <code>$href</code> is the empty sequence, the function returns the empty sequence.</p></def></gitem><gitem><label>Error Conditions</label><def><p>The function may raise any error defined for the <code>fn:unparsed-text</code> or <code>fn:parse-json</code>
         functions.</p></def></gitem><gitem><label>Notes</label><def><p role="note">If the input cannot be decoded (that is, converted into a sequence of Unicode codepoints, which may or may not represent characters),
            then a dynamic error occurs as with the <code>fn:unparsed-text</code> function.</p><p role="note">If the input can be decoded,
            then the possibility still arises that the resulting sequence of codepoints includes codepoints that do not represent characters that are valid in the
            version of XML that the processor supports. Such codepoints are translated into JSON escape sequences (for example, <code>\uFFFF</code>),
            and the JSON escape sequence is then passed to the fallback function specified in the <code>$options</code> argument, which in turn
            defaults to a function that returns the Unicode <code>REPLACEMENT CHARACTER</code> (<code>xFFFD</code>).</p></def></gitem></glist></div3><div3 id="func-json-to-xml" diff="add" at="D"><head>fn:json-to-xml</head><glist><gitem><label>Summary</label><def><p>Parses a string supplied in the form of a JSON text, returning the results in the form
            of an XML <phrase diff="chg" at="P">document node</phrase>.</p></def></gitem><gitem><label>Signatures</label><def><example role="signature"><proto name="json-to-xml" return-type="document-node()?" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="json-text" type="xs:string?"/></proto></example><example role="signature"><proto name="json-to-xml" return-type="document-node()?" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="json-text" type="xs:string?"/><arg name="options" type="map(*)"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-nondeterministic">nondeterministic</termref>, <termref def="dt-context-dependent">context-dependent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>.  It depends on 
		static base URI.
	</p></def></gitem><gitem><label>Rules</label><def><p>The effect of the one-argument form of this function is the same as calling the
            two-argument form with an empty map as the value of the <code>$options</code>
            argument.</p><p>The first argument is a JSON-text as defined in <bibref ref="rfc7159"/>, in the form of a string. The function
            parses this string to return an XDM node.</p><p>If <code>$json-text</code> is an empty sequence, the function returns the empty sequence.</p><p diff="chg" at="D">The <code>$options</code> argument can be used to control the way in which the parsing
            takes place. The <termref def="option-parameter-conventions">option parameter conventions</termref> apply.</p><p>The entries that may appear in the <code>$options</code> map are as follows:</p><table style="border-collapse: collapse"><thead><tr style="border-top: 2px solid black; border-bottom: 2px solid black"><th style="text-align:left; padding-right: 10px; " rowspan="1" colspan="1">Key</th><th style="text-align:left; padding-right: 10px; " rowspan="1" colspan="1">Value</th><th style="text-align:left" rowspan="1" colspan="1">Meaning</th></tr></thead><tbody><tr><td style="white-space:nowrap; padding-right: 10px; vertical-align:top; border-bottom: 2px solid black" rowspan="3" colspan="1"><code>liberal</code></td><td style="vertical-align:top; border-bottom: 1px solid black" colspan="2" rowspan="1">Determines whether deviations from the syntax of RFC7159 are permitted.<ulist><item><p><term>Type: </term><code>xs:boolean</code></p></item><item><p><term>Default: </term><code>false</code></p></item></ulist></td></tr><tr><td style="white-space:nowrap; padding-right: 10px; vertical-align:top; border-bottom: 1px solid black" rowspan="1" colspan="1"><code>false</code></td><td style="vertical-align:top; border-bottom: 1px solid black" rowspan="1" colspan="1">
                     The input <rfc2119>must</rfc2119> consist of <phrase diff="add" at="D">an optional byte order mark (which is ignored) followed by</phrase> a string
                     that conforms to the grammar of <code>JSON-text</code> in <bibref ref="rfc7159"/>. An error <rfc2119>must</rfc2119> be raised
                     (see below) if the input does not conform to the grammar.
                  </td></tr><tr><td style="white-space:nowrap; padding-right: 10px; vertical-align:top; border-bottom: 2px solid black" rowspan="1" colspan="1"><code>true</code></td><td style="vertical-align:top; border-bottom: 2px solid black" rowspan="1" colspan="1">
                     The input <rfc2119>may</rfc2119> contain deviations from the grammar of <bibref ref="rfc7159"/>,
                     which are handled in an <termref def="implementation-defined">implementation-defined</termref> way. (Note: some popular
                     extensions include allowing quotes on keys to be omitted, allowing a comma
                     to appear after the last item in an array, allowing leading zeroes in numbers, and allowing control characters such as
                     tab and newline to be present in unescaped form.) Since the extensions accepted
                     are implementation-defined, an error <rfc2119>may</rfc2119> be raised
                     (see below) if the input does not conform to the grammar.
                  </td></tr><tr><td style="white-space:nowrap; padding-right: 10px; vertical-align:top; border-bottom: 2px solid black" rowspan="4" colspan="1"><code>duplicates</code></td><td style="vertical-align:top; border-bottom: 1px solid black" colspan="2" rowspan="1">Determines the policy for handling duplicate keys in a JSON object.
                  To determine whether keys are duplicates, they are compared using the Unicode codepoint collation, after expanding escape
                  sequences, unless the <phrase diff="chg" at="D"><code>escape</code> option is set to <code>true</code></phrase>, in which
                  case keys are compared in escaped form. 
               <ulist><item><p><term>Type: </term><code>xs:string</code></p></item><item><p><term>Default: </term><code>If validate is true then reject, otherwise retain.</code></p></item></ulist></td></tr><tr><td style="white-space:nowrap; padding-right: 10px; vertical-align:top; border-bottom: 1px solid black" rowspan="1" colspan="1"><code>reject</code></td><td style="vertical-align:top; border-bottom: 1px solid black" rowspan="1" colspan="1">
                     An error is raised <errorref class="JS" code="0003"/> if duplicate keys are encountered.
                  </td></tr><tr><td style="white-space:nowrap; padding-right: 10px; vertical-align:top; border-bottom: 1px solid black" rowspan="1" colspan="1"><code>use-first</code></td><td style="vertical-align:top; border-bottom: 1px solid black" rowspan="1" colspan="1">
                     If duplicate keys are present in a JSON object, all but the first of a set of duplicates are ignored.
                  </td></tr><tr><td style="white-space:nowrap; padding-right: 10px; vertical-align:top; border-bottom: 2px solid black" rowspan="1" colspan="1"><code>retain</code></td><td style="vertical-align:top; border-bottom: 2px solid black" rowspan="1" colspan="1">
                     If duplicate keys are present in a JSON object, the XML result of the function will also contain duplicates (making
                     it invalid against the schema). This value is therefore incompatible with the option <code>validate=true</code> 
                     <errorref class="JS" code="0005"/>
                  </td></tr><tr><td style="white-space:nowrap; padding-right: 10px; vertical-align:top; border-bottom: 2px solid black" rowspan="3" colspan="1"><code>validate</code></td><td style="vertical-align:top; border-bottom: 1px solid black" colspan="2" rowspan="1">Determines whether the generated XML tree is schema-validated.<ulist><item><p><term>Type: </term><code>xs:boolean</code></p></item><item><p><term>Default: </term><code>Implementation-defined.</code></p></item></ulist></td></tr><tr><td style="white-space:nowrap; padding-right: 10px; vertical-align:top; border-bottom: 1px solid black" rowspan="1" colspan="1"><code>true</code></td><td style="vertical-align:top; border-bottom: 1px solid black" rowspan="1" colspan="1">
                     Indicates that the resulting XDM instance must be typed; that is, the element
                     and attribute nodes must carry the type annotations that result from validation
                     against the schema given at <specref ref="schema-for-json"/>, or against an
                     <termref def="dt-implementation-defined">implementation-defined</termref> schema 
                     if the <code>liberal</code> option has the value <code>true</code>.
                  </td></tr><tr><td style="white-space:nowrap; padding-right: 10px; vertical-align:top; border-bottom: 2px solid black" rowspan="1" colspan="1"><code>false</code></td><td style="vertical-align:top; border-bottom: 2px solid black" rowspan="1" colspan="1">
                     Indicates that the resulting XDM instance must be untyped.
                  </td></tr><tr><td style="white-space:nowrap; padding-right: 10px; vertical-align:top; border-bottom: 2px solid black" rowspan="3" colspan="1"><code>escape</code></td><td style="vertical-align:top; border-bottom: 1px solid black" colspan="2" rowspan="1">Determines whether special characters are represented in the XDM output 
                  in backslash-escaped form. <ulist><item><p><term>Type: </term><code>xs:boolean</code></p></item><item><p><term>Default: </term><code>false</code></p></item></ulist></td></tr><tr><td style="white-space:nowrap; padding-right: 10px; vertical-align:top; border-bottom: 1px solid black" rowspan="1" colspan="1"><code>false</code></td><td style="vertical-align:top; border-bottom: 1px solid black" rowspan="1" colspan="1">
                     All characters in the input that are valid
                     in the version of XML supported by the implementation, whether or not they are represented 
                     in the input by means of an escape sequence, are represented as unescaped characters in the result. Any
                     characters or codepoints that are not valid XML characters 
                     (for example, unpaired surrogates) <phrase diff="add" at="D">are passed to the <code>fallback</code> function
                        as described below; in the absence of a fallback function, they are replaced by
                        the Unicode <code>REPLACEMENT CHARACTER</code> (<code>xFFFD</code>)</phrase>.
                     The attributes <code>escaped</code> and <code>escaped-key</code> will not be present in the XDM output.
                  </td></tr><tr><td style="white-space:nowrap; padding-right: 10px; vertical-align:top; border-bottom: 2px solid black" rowspan="1" colspan="1"><code>true</code></td><td style="vertical-align:top; border-bottom: 2px solid black" rowspan="1" colspan="1">
                     JSON escape sequences are used in the result to represent special characters in the JSON input, as defined below, 
                     whether or not they were represented using JSON escape sequences in the input.
                     The characters that are considered "special" for this purpose are:
                     <ulist><item><p>all codepoints in the range <code>x00</code> to <code>x1F</code> 
                           or <code>x7F</code> to <code>x9F</code>;</p></item><item><p>all codepoints that do not represent characters that are valid in the version of XML supported by the processor,
                           including codepoints representing unpaired surrogates;</p></item><item><p>the backslash character itself (<code>x5C</code>).</p></item></ulist>
                     
                     Such characters are represented using a two-character
                     escape sequence where available (for example, <code>\t</code>), or a six-character escape sequence otherwise
                     (for example <code>\uDEAD</code>). Characters other than these will not be escaped in the result,
                     even if they were escaped in the input. In the result:
                     
                     <ulist><item><p>Any <code>string</code> element whose string value contains a
                           backslash character must have the attribute value <code>escaped="true"</code>.</p></item><item><p>Any element that contains a <code>key</code> attribute whose string value
                           contains a backslash character must have the attribute
                           <code>escaped-key="true"</code>.</p></item><item><p>The values of the <code>escaped</code> and
                           <code>escaped-key</code> attributes are immaterial when there is no backslash
                           present, and it is never necessary to include either attribute when its value
                           is <code>false</code>.</p></item></ulist>
                  </td></tr><tr><td style="white-space:nowrap; padding-right: 10px; vertical-align:top; border-bottom: 2px solid black" rowspan="2" colspan="1"><code>fallback</code></td><td style="vertical-align:top; border-bottom: 1px solid black" colspan="2" rowspan="1">
                  Provides a function which is called when the input contains an escape sequence 
                  that represents a character that is not valid in the version of XML
                  supported by the implementation. 
                  
                  It is an error to supply the <code>fallback</code> option if the <code>escape</code> option is present
                  with the value <code>true</code>.
               <ulist><item><p><term>Type: </term><code>function(xs:string) as xs:string</code></p></item><item><p><term>Default: </term><code>The default is effectively the function function($s){"&amp;#xFFFD;"}: that is,
                  a function that replaces the escape sequence with the Unicode REPLACEMENT CHARACTER.</code></p></item></ulist></td></tr><tr><td style="white-space:nowrap; padding-right: 10px; vertical-align:top; border-bottom: 2px solid black" rowspan="1" colspan="1"><code>User-supplied function</code></td><td style="vertical-align:top; border-bottom: 2px solid black" rowspan="1" colspan="1">
                     The function is called when the JSON input contains an escape sequence that is valid according to the JSON 
                     grammar, but which does not represent a character that is valid in the version of XML supported
                     by the processor. In the case of surrogates, the function is called once for any six-character escape sequence
                     that is not properly paired with another surrogate. The string supplied 
                     as the argument will always be a two- or six- character escape
                     sequence, starting with a backslash, that conforms to the rules in the JSON grammar (as extended by the
                     implementation if <code>liberal:true()</code> is specified): for example
                     <code>\b</code> or <code>\uFFFF</code> or <code>\uDEAD</code>. The function is <emph>not</emph>
                     called for an escape sequence that is invalid against the grammar (for example <code>\x0A</code>). 
                     The function returns a string
                     which is inserted into the result in place of the invalid character. The
                     function also has the option of raising a dynamic error by calling <code>fn:error</code>.
                  </td></tr></tbody></table><p>The various structures that can occur in JSON are transformed recursively to XDM values
            according to the rules given in <specref ref="json-to-xml-mapping"/>.</p><p>The function returns a document node, whose only child
               is the element node representing the outermost construct in the JSON
            text.</p><p>The function is <termref ref="dt-nondeterministic">non-deterministic with respect to node identity</termref>: that is, if the function is called twice with the same
            arguments, it is <termref def="implementation-dependent">implementation-dependent</termref> whether the same node is returned on both
            occasions.</p><p>The base URI of the returned document node is taken from the static base URI of the
            function call.</p><p>The choice of namespace prefix (or absence of a prefix) in the names of constructed
         nodes is <termref def="implementation-dependant">implementation-dependant</termref>.</p><p>The XDM tree returned by the function does not contain any
         unnecessary (albeit valid) nodes such as whitespace text nodes, comments, or processing instructions.
         It does not include any whitespace in the value of <code>number</code> or <code>boolean</code> 
            element nodes, <phrase diff="add" at="D">or in the value of <code>escaped</code> or <code>escaped-key</code>
         attribute nodes.</phrase></p><p diff="add" at="D">If the result is typed, every element named <code>string</code> will have an attribute named 
            <code>escaped</code> whose value is either <code>true</code> or <code>false</code>, and every element having 
            an attribute named <code>key</code> will also have an attribute named <code>escaped-key</code> whose value is either 
            <code>true</code> or <code>false</code>.
         </p><p diff="add" at="D">If the result is untyped, the attributes <code>escaped</code> and <code>escaped-key</code> will 
            either be present with the value <code>true</code>, or will be absent. They will never be present with the value <code>false</code>.</p></def></gitem><gitem><label>Error Conditions</label><def><p>An error is raised <errorref spec="FO" class="JS" code="0001"/> if the value of
            <code>$input</code> does not conform to the JSON grammar as defined
            by <bibref ref="rfc7159"/>, unless the option <code>"liberal":true()</code> is present and
            the processor chooses to accept the deviation. </p><p>An error is raised <errorref spec="FO" class="JS" code="0004"/> if the value of
            the <code>validate</code> option is <code>true</code> and the processor does not support
            schema validation or typed data.</p><p>An error is raised <errorref spec="FO" class="JS" code="0005"/> if the value of
            <code>$options</code> includes an entry whose key is defined in this specification,
               and whose value is not a permitted value for that key.</p></def></gitem><gitem><label>Notes</label><def><p role="note">To read a JSON file, this function can be used in conjunction with the
               <code>fn:unparsed-text</code> function.</p><p role="note">Many JSON implementations allow commas to be used after the last item in an object or
            array, although the specification does not permit it. The option
               <code>spec="liberal"</code> is provided to allow such deviations from the
            specification to be accepted. Some JSON implementations also allow constructors such as
               <code>new Date("2000-12-13")</code> to appear as values: specifying
               <code>spec="liberal"</code> allows such extensions to be accepted, but does not
            guarantee it. If such extensions are accepted, the resulting value is
            implementation-defined, and will not necessarily conform to the schema at <specref ref="schema-for-json"/>.</p><p role="note">If the input starts with a byte order mark, this function ignores it. The byte order mark may have been added
            to the data stream in order to facilitate decoding of an octet stream to a character string, but since this function
            takes a character string as input, the byte order mark serves no useful purpose.</p><p role="note">The possibility of the input containing characters that are not valid in XML (for example, unpaired surrogates)
         arises only when such characters are expressed using JSON escape sequences. The is because the input to the function
         is an instance of <code>xs:string</code>, which by definition can only contain characters that are valid in XML.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The expression <code>json-to-xml('{"x": 1, "y": [3,4,5]}')</code> returns (with whitespace added for legibility):</p><eg xml:space="preserve">
&lt;map xmlns="http://www.w3.org/2005/xpath-functions"&gt;
  &lt;number key="x"&gt;1&lt;/number&gt;
  &lt;array key="y"&gt;
   &lt;number&gt;3&lt;/number&gt;
   &lt;number&gt;4&lt;/number&gt;
   &lt;number&gt;5&lt;/number&gt;
  &lt;/array&gt;
&lt;/map&gt;</eg><p>The expression <code>json-to-xml('"abcd"', map{'liberal': false()})</code> returns <code>&lt;string xmlns="http://www.w3.org/2005/xpath-functions"&gt;abcd&lt;/string&gt;</code>.</p><p>The expression <code>json-to-xml('{"x": "\\", "y": "\u0025"}')</code> returns (with whitespace added for legibility):</p><eg xml:space="preserve">
&lt;map xmlns="http://www.w3.org/2005/xpath-functions"&gt;
  &lt;string key="x"&gt;\&lt;/string&gt;
  &lt;string key="y"&gt;%&lt;/string&gt;
&lt;/map&gt;</eg><p>The expression <code>json-to-xml('{"x": "\\", "y": "\u0025"}', map{'escape':
                  true()})</code> returns (with whitespace added for legibility):</p><eg xml:space="preserve">
&lt;map xmlns="http://www.w3.org/2005/xpath-functions"&gt;
  &lt;string escaped="true" key="x"&gt;\\&lt;/string&gt;
  &lt;string key="y"&gt;%&lt;/string&gt;
&lt;/map&gt;</eg><p>The following example illustrates use of the <code>fallback</code> function to
               handle characters that are invalid in XML.</p><eg diff="add" at="D" xml:space="preserve">
 let 
   $jsonstr := unparsed-text('http://example.com/endpoint'),
   $options := map {
     'liberal': true(),
     'fallback': function($char as xs:string) as xs:string {
       let 
         $c0chars := map {
           '\u0000':'[NUL]',
           '\u0001':'[SOH]',
           '\u0002':'[STX]',
           ...
           '\u001E':'[RS]',
           '\u001F':'[US]'
         },
         $replacement := $c0chars($char)
      return 
        if (exists($replacement))
        then $replacement
        else error(xs:QName('err:invalid-char'), 
          'Error: ' || $char || ' is not a C0 control character.')
     }
   }
 return json-to-xml($jsonstr, $options)</eg></def></gitem></glist></div3><div3 id="func-xml-to-json" diff="add" at="D"><head>fn:xml-to-json</head><glist><gitem><label>Summary</label><def><p>Converts an XML tree, whose format corresponds to the XML representation of JSON defined
            in this specification, into a string conforming to the JSON grammar.</p></def></gitem><gitem><label>Signatures</label><def><example role="signature"><proto name="xml-to-json" return-type="xs:string?" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="input" type="node()?"/></proto></example><example role="signature"><proto name="xml-to-json" return-type="xs:string?" isOp="no" prefix="fn" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="input" type="node()?"/><arg name="options" type="map(*)"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <termref def="dt-deterministic">deterministic</termref>, <termref def="dt-context-independent">context-independent</termref>,  and <termref def="dt-focus-independent">focus-independent</termref>. </p></def></gitem><gitem><label>Rules</label><def><p>The effect of the one-argument form of this function is the same as calling the
            two-argument form with an empty map as the value of the <code>$options</code>
            argument.</p><p>The first argument <code>$input</code> is a node; the subtree rooted at this node will typically be
            the XML representation of a JSON document as defined in <specref ref="json-to-xml-mapping"/>.</p><p>If <code>$input</code> is the empty sequence, the function returns the empty sequence.</p><p diff="chg" at="D">The <code>$options</code> argument can be used to control the way in which the conversion
            takes place. The <termref def="option-parameter-conventions">option parameter conventions</termref> apply.</p><p>The entries that may appear in the <code>$options</code> map are as follows:</p><table style="border-collapse: collapse"><thead><tr style="border-top: 2px solid black; border-bottom: 2px solid black"><th style="text-align:left; padding-right: 10px; " rowspan="1" colspan="1">Key</th><th style="text-align:left; padding-right: 10px; " rowspan="1" colspan="1">Value</th><th style="text-align:left" rowspan="1" colspan="1">Meaning</th></tr></thead><tbody><tr><td style="white-space:nowrap; padding-right: 10px; vertical-align:top; border-bottom: 2px solid black" rowspan="3" colspan="1"><code>indent</code></td><td style="vertical-align:top; border-bottom: 1px solid black" colspan="2" rowspan="1">Determines whether additional whitespace should be added to the output to improve readability.<ulist><item><p><term>Type: </term><code>xs:boolean</code></p></item><item><p><term>Default: </term><code>false</code></p></item></ulist></td></tr><tr><td style="white-space:nowrap; padding-right: 10px; vertical-align:top; border-bottom: 1px solid black" rowspan="1" colspan="1"><code>false</code></td><td style="vertical-align:top; border-bottom: 1px solid black" rowspan="1" colspan="1">
                     The processor must not insert any insignificant whitespace between JSON tokens.
                  </td></tr><tr><td style="white-space:nowrap; padding-right: 10px; vertical-align:top; border-bottom: 2px solid black" rowspan="1" colspan="1"><code>true</code></td><td style="vertical-align:top; border-bottom: 2px solid black" rowspan="1" colspan="1">
                     The processor <rfc2119>may</rfc2119> insert whitespace between JSON tokens in order to improve readability.
                     The specification imposes no constraints on how this is done.
                  </td></tr></tbody></table><p>The node supplied as <code>$input</code> must be one of the following: <errorref spec="FO" class="JS" code="0006"/></p><olist diff="chg" at="E"><item><p>An element node whose name matches the name of a global element declaration in the schema given in 
               <specref ref="schema-for-json"/> ("the schema") and that is valid as defined below:</p><olist><item><p>If the type annotation of the element matches the type of the relevant element declaration 
                     in the schema (indicating that the element has been validated against the schema), then the element 
                     is considered valid.
                  </p></item><item><p>Otherwise, the processor <rfc2119>may</rfc2119> attempt to validate the element against
                     the schema, in which case it is treated as valid if and only if the outcome of validation is
                     <term>valid</term>.
                  </p></item><item><p>Otherwise (if the processor does not attempt validation using the schema), 
                     the processor <rfc2119>must</rfc2119> ensure that the content of the element, 
                     after stripping all attributes (at any depth) in namespaces other than 
                     <code>http://www.w3.org/2005/xpath-functions</code>, is such that validation 
                     against the schema would have an outcome of <term>valid</term>.
                  </p><note><p>The process described here is not precisely equivalent to schema validation. 
                        For example, schema validation will fail if there is an invalid <code>xsi:type</code> 
                        or <code>xsi:nil</code> attribute, whereas this process will ignore such attributes.
                     </p></note></item></olist></item><item><p>An element node <var>E</var> having a <code>key</code> attribute and/or an <code>escaped-key</code> attribute 
               provided that <var>E</var> would satisfy one of the above
            conditions if the <code>key</code> and/or <code>escaped-key</code> attributes were removed.</p></item><item><p>A document node having exactly one element child and no text node children, 
               where the element child satisfies one of the conditions above.</p></item></olist><p diff="add" at="E">Furthermore, <code>$input</code> must satisfy the following constraint
            (which cannot be conveniently expressed in the schema). Every element <var>M</var> that is a descendant-or-self of 
            <code>$input</code> and has local name <code>map</code> and namespace URI <code>http://www.w3.org/2005/xpath-functions</code>
            must satisfy the following rule: there must not be two distinct children of <var>M</var> (say <var>C/1</var> and <var>C/2</var>) 
            such that the normalized key of <var>C/1</var> is equal to the normalized key of <var>C/2</var>. The normalized key 
            of an element <var>C</var> is as follows:</p><ulist diff="add" at="E"><item><p>If <var>C</var> has the attribute value <code>escaped-key="true"</code>, then the value of the 
               <code>key</code> attribute of <var>C</var>, with all JSON escape sequences replaced by the corresponding Unicode characters 
               according to the JSON escaping rules.
            </p></item><item><p>Otherwise (the <code>escaped-key</code> attribute of <var>C</var> is absent or set to false), 
               the value of the <code>key</code> attribute of <var>C</var>.</p></item></ulist><p>Nodes in the input tree are handled by applying the following rules, recursively. In these rules the term
            "an element named <var>N</var>" means "an element node whose local name is <var>N</var> and whose namespace URI is 
            <code>http://www.w3.org/2005/xpath-functions</code>".</p><olist><item><p>A document node having a single element node child is processed by processing that child.</p></item><item><p>An element named <code>null</code> results in the output <code>null</code>.</p></item><item><p>An element <code>$E</code> named <code>boolean</code> results in the output <code>true</code> or <code>false</code>
            depending on the result of <phrase diff="chg" at="D"><code>xs:boolean(fn:string($E))</code></phrase>.</p></item><item><p>An element <code>$E</code> named <code>number</code> results in the output of the string 
               <phrase diff="chg" at="D">result of <code>xs:string(xs:double(fn:string($E)))</code></phrase>
            </p></item><item><p>An element named <code>string</code> results in the output of the string value of the element, enclosed in
            quotation marks, with any special characters in the string escaped as described below.</p></item><item><p>An element named <code>array</code> results in the output of the children of the <code>array</code> element, 
               each processed by applying these rules recursively: the items in the resulting list are enclosed between square brackets, 
               and separated by commas.</p></item><item><p>An element named <code>map</code> results in the output of a sequence of map entries corresponding to 
               the children of the <code>map</code> element, enclosed between curly braces and separated by commas. 
               Each entry comprises the value of the <code>key</code> attribute of the child element, enclosed in quotation marks 
               and escaped as described below, followed by a colon, followed by the result of processing the child element 
               by applying these rules recursively.</p></item><item><p>Comments, processing instructions, and whitespace text node children of <code>map</code> and <code>array</code>
               are ignored.</p></item></olist><p>Strings are escaped as follows:</p><olist><item><p>If the attribute <code>escaped="true"</code> is present for a string value, or <code>escaped-key="true"</code> for a key value, then:</p><olist><item><p>any valid JSON escape sequence present in the string is copied unchanged to the output;</p></item><item><p>any invalid JSON escape sequence results in a dynamic error <errorref spec="FO" class="JS" code="0007"/>;</p></item><item><p>any unescaped occurrence of quotation mark, backspace, form-feed, newline, carriage return, tab, <phrase diff="add" at="E">or solidus</phrase> is replaced by
                  <code>\"</code>, <code>\b</code>, <code>\f</code>, <code>\n</code>, <code>\r</code>, <code>\t</code>, <phrase diff="add" at="E">or <code>\/</code></phrase> respectively; </p></item><item><p>any other codepoint in the range 1-31 or 127-159 is replaced by an escape in the form \uHHHH where HHHH 
                  is the upper-case hexadecimal representation of the codepoint value.</p></item></olist></item><item><p>Otherwise (that is, in the absence of the attribute <code>escaped="true"</code> for a string value, 
            or <code>escaped-key="true"</code> for a key value):</p><olist><item><p>any occurrence of backslash is replaced by <code>\\</code></p></item><item><p>any occurrence of quotation mark, backspace, form-feed, newline, carriage return, or tab is 
               replaced by <code>\"</code>, <code>\b</code>, <code>\f</code>, <code>\n</code>, <code>\r</code>, or <code>\t</code> respectively; </p></item><item><p>any other codepoint in the range 1-31 or 127-159 is replaced by an escape in 
            the form <code>\uHHHH</code> where <code>HHHH</code> is the upper-case hexadecimal representation of the codepoint value.</p></item></olist></item></olist></def></gitem><gitem><label>Error Conditions</label><def><p>A dynamic error is raised <errorref spec="FO" class="JS" code="0005"/> if the value of
            <code>$options</code> includes an entry whose key is defined in this specification, 
            and whose value is not a permitted value for that key.</p><p>A dynamic error is raised <errorref spec="FO" class="JS" code="0006"/> if the value of
            <code>$input</code> is not a document or element node or is not valid according to the schema for the XML representation of
            JSON<phrase diff="add" at="E">, or if a <code>map</code> element has two children whose normalized key values are the same.</phrase></p><p>A dynamic error is raised <errorref spec="FO" class="JS" code="0007"/> if the value of
            <code>$input</code> includes a string labeled with <code>escaped="true"</code>, or
            a key labeled with <code>escaped-key="true"</code>, where the content of the string or key
            contains an invalid JSON escape sequence: specifically, where it contains a backslash (<code>\</code>) that is not followed by one
            of the characters <code>"</code>, <code>\</code>, <code>/</code>, <code>b</code>, <code>f</code>, <code>n</code>, 
            <code>r</code>, <code>t</code>, or <code>u</code>, or where it contains the characters <code>\u</code>
            not followed by four hexadecimal digits (that is <code>[0-9A-Fa-f]{4}</code>).
        </p></def></gitem><gitem><label>Notes</label><def><p role="note">The rule requiring schema validity has a number of consequences, including the following:</p><olist role="note"><item><p>The input cannot contain no-namespace attributes, or attributes in the namespace <code>http://www.w3.org/2005/xpath-functions</code>,
            except where explicitly allowed by the schema. Attributes in other namespaces, however, are ignored.</p></item><item><p>Nodes that do not affect schema validity, such as comments, processing instructions, namespace nodes, and whitespace text node
            children of <code>map</code> and <code>array</code>, are ignored.</p></item><item><p>Numeric values are restricted to those that are valid in JSON: 
            the schema disallows positive and negative infinity and NaN.</p></item><item><p>Duplicate key values are not permitted. <phrase diff="add" at="E">Most cases of duplicate keys are prevented by the rules in the schema; 
            additional cases (where the keys are equal only after expanding JSON escape sequences) are prevented by the prose rules 
            of this function. For example, the key values <code>\n</code> and <code>\u000A</code> are treated as duplicates even though
            the rules in the schema do not treat them as such.</phrase></p></item></olist><p role="note">The rule allowing the top-level element to have a <code>key</code> attribute (which is ignored)
         allows any element in the output of the <code>fn:json-to-xml</code> function
         to be processed: for example, it is possible to take a JSON document, convert it to XML, select
         a subtree based on the value of a <code>key</code> attribute, and then convert this subtree
         back to JSON, perhaps after a transformation. The rule means that an element with the appropriate name will be 
            accepted if it has been validated against one of the 
            types <code>mapWithinMapType</code>, <code>arrayWithinMapType</code>, <code>stringWithinMapType</code>, 
            <code>numberWithinMapType</code>, <code>booleanWithinMapType</code>, or <code>nullWithinMapType</code>.</p></def></gitem><gitem><label>Examples</label><def role="example"><p>The input <code>&lt;array xmlns="http://www.w3.org/2005/xpath-functions"&gt;&lt;number&gt;1&lt;/number&gt;&lt;string&gt;is&lt;/string&gt;&lt;boolean&gt;1&lt;/boolean&gt;&lt;/array&gt;</code>
         produces the result <code>[1,"is",true]</code>.</p><p>The input <code>&lt;map xmlns="http://www.w3.org/2005/xpath-functions"&gt;&lt;number key="Sunday"&gt;1&lt;/number&gt;&lt;number key="Monday"&gt;2&lt;/number&gt;&lt;/map&gt;</code>
            produces the result <code>{"Sunday":1,"Monday":2}</code>.</p></def></gitem></glist></div3></div2></div1><div1 id="constructor-functions"><head>Constructor functions</head><p diff="add" at="E">
              This section describes constructor functions corresponding to simple types defined in <bibref ref="xmlschema-2"/>. 
              Constructor functions are used to convert a supplied value to a given type. They always take a single argument, 
              and the name of the function is the same as the name of the target type.
           </p><p diff="add" at="E">
              Constructor functions are defined for all user-defined named simple types, and for most built-in atomic, list, 
              and union types. The only named simple types that have no constructor function are those that have no instances 
              other than instances of their derived types: specifically, <code>xs:anySimpleType</code>, <code>xs:anyAtomicType</code>, 
              and <code>xs:NOTATION</code>. 
           </p><div2 id="constructor-functions-for-xsd-types"><head>Constructor functions for XML Schema built-in atomic types</head><p>Every built-in atomic 
                   type that is defined in <bibref ref="xmlschema-2"/>,
                   except <code>xs:anyAtomicType</code> and <code>xs:NOTATION</code>, has an
                    associated constructor function. The type <code>xs:untypedAtomic</code>, defined
                    in <xspecref spec="DM31" ref="types"/> and the two derived types
                    <code>xs:yearMonthDuration</code> and <code>xs:dayTimeDuration</code> defined
                    in <xspecref spec="DM31" ref="types"/> also have associated constructor functions.
                Implementations <rfc2119>may</rfc2119> additionally provide
                a constructor functions for the new datatype <code>xs:dateTimeStamp</code> introduced in <bibref ref="xmlschema11-2"/>.</p><p>
A constructor function is not defined for <code>xs:anyAtomicType</code> as there are no atomic values with type annotation <code>xs:anyAtomicType</code> at runtime, although this can be a statically inferred type.
A constructor function is not defined for <code>xs:NOTATION</code> since it is defined as an abstract type in <bibref ref="xmlschema-2"/>.  If the static context (See <xspecref spec="XP31" ref="static_context"/>) contains a type derived from
<code>xs:NOTATION</code> then a constructor function is defined for it.
See <specref ref="constructor-functions-for-user-defined-types"/>.
</p><p> 
The form of the constructor function for an atomic type
                    <emph>eg:TYPE</emph> is:</p><example role="signature"><proto name="TYPE" prefix="eg" return-type="eg:TYPE" role="example" returnEmptyOk="yes" isSpecial="yes" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isOp="no"><arg name="arg" type="xs:anyAtomicType" emptyOk="yes"/></proto></example><p>If <code>$arg</code> is the empty sequence, the empty sequence is returned. For
                    example, the signature of the constructor function corresponding to the
                    <code>xs:unsignedInt</code> type defined in <bibref ref="xmlschema-2"/> is:</p><example role="signature"><proto name="unsignedInt" return-type="xs:unsignedInt" isSchema="yes" prefix="xs" returnEmptyOk="yes" role="example" returnSeq="no" returnVaries="no" isDatatype="no" isSpecial="no" isOp="no"><arg name="arg" type="xs:anyAtomicType" emptyOk="yes"/></proto></example><p>Calling the constructor function <code>xs:unsignedInt(12)</code> returns
                    the <code> xs:unsignedInt</code> value 12. Another call of that constructor
                    function that returns the same <code>xs:unsignedInt</code> value is
                    <code>xs:unsignedInt("12")</code>. The same result would also be returned if the
                    constructor function were to be called with a node that had a typed value equal
                    to the <code>xs:unsignedInt</code> 12. The standard features described in
                        <xspecref spec="XP31" ref="id-atomization"/> would atomize the node to
                    extract its typed value and then call the constructor with that value. If the
                    value passed to a constructor is not in the lexical space of the datatype to be constructed, 
                    and cannot be converted to a value in the value space of the datatype under the rules in this
                    specification, then an
                   dynamic error is raised <errorref class="RG" code="0001"/>.</p><p>The semantics of the constructor function 
                        <code>xs:TYPE(arg)</code>
                     are identical to the semantics of 
                        <code>arg</code> cast as <code>xs:TYPE?</code>
                    . See <specref ref="casting"/>.</p><p>If the argument to a constructor function is a literal, the result of the
                    function <rfc2119>may</rfc2119> be evaluated statically; if an error is found during such
                    evaluation, it may be reported as a static error. </p><p>Special rules apply to constructor functions for <code>xs:QName</code> and types derived from <code>xs:QName</code> and <code>xs:NOTATION</code>. See 
<specref ref="constructor-qname-notation"/>.
</p><p>The following constructor functions for the built-in atomic types are supported:</p><ulist><item><proto name="string" return-type="xs:string" returnEmptyOk="yes" isSchema="yes" prefix="xs" role="example" returnSeq="no" returnVaries="no" isDatatype="no" isSpecial="no" isOp="no"><arg name="arg" type="xs:anyAtomicType" emptyOk="yes"/></proto></item><item><proto name="boolean" return-type="xs:boolean" returnEmptyOk="yes" isSchema="yes" prefix="xs" role="example" returnSeq="no" returnVaries="no" isDatatype="no" isSpecial="no" isOp="no"><arg name="arg" type="xs:anyAtomicType" emptyOk="yes"/></proto></item><item><proto name="decimal" return-type="xs:decimal" returnEmptyOk="yes" isSchema="yes" prefix="xs" role="example" returnSeq="no" returnVaries="no" isDatatype="no" isSpecial="no" isOp="no"><arg name="arg" type="xs:anyAtomicType" emptyOk="yes"/></proto></item><item><proto name="float" return-type="xs:float" returnEmptyOk="yes" isSchema="yes" prefix="xs" role="example" returnSeq="no" returnVaries="no" isDatatype="no" isSpecial="no" isOp="no"><arg name="arg" type="xs:anyAtomicType" emptyOk="yes"/></proto><p>Implementations <rfc2119>should</rfc2119> return negative zero for <code>xs:float("-0.0E0")</code>.  
                           But because <bibref ref="xmlschema-2"/> does not distinguish between the values positive zero and negative zero,
                           implementations <rfc2119>may</rfc2119> return positive zero in this case.</p></item><item><proto name="double" return-type="xs:double" returnEmptyOk="yes" isSchema="yes" prefix="xs" role="example" returnSeq="no" returnVaries="no" isDatatype="no" isSpecial="no" isOp="no"><arg name="arg" type="xs:anyAtomicType" emptyOk="yes"/></proto><p>Implementations <rfc2119>should</rfc2119> return negative zero for <code>xs:double("-0.0E0")</code>.  
                          But because <bibref ref="xmlschema-2"/> does not distinguish between the values positive zero and negative zero,
                          implementations <rfc2119>may</rfc2119> return positive zero in this case.</p></item><item><proto name="duration" return-type="xs:duration" returnEmptyOk="yes" isSchema="yes" prefix="xs" role="example" returnSeq="no" returnVaries="no" isDatatype="no" isSpecial="no" isOp="no"><arg name="arg" type="xs:anyAtomicType" emptyOk="yes"/></proto></item><item><proto name="dateTime" return-type="xs:dateTime" returnEmptyOk="yes" isSchema="yes" prefix="xs" role="example" returnSeq="no" returnVaries="no" isDatatype="no" isSpecial="no" isOp="no"><arg name="arg" type="xs:anyAtomicType" emptyOk="yes"/></proto></item><item><proto name="time" return-type="xs:time" returnEmptyOk="yes" isSchema="yes" prefix="xs" role="example" returnSeq="no" returnVaries="no" isDatatype="no" isSpecial="no" isOp="no"><arg name="arg" type="xs:anyAtomicType" emptyOk="yes"/></proto></item><item><proto name="date" return-type="xs:date" returnEmptyOk="yes" isSchema="yes" prefix="xs" role="example" returnSeq="no" returnVaries="no" isDatatype="no" isSpecial="no" isOp="no"><arg name="arg" type="xs:anyAtomicType" emptyOk="yes"/></proto></item><item><proto name="gYearMonth" return-type="xs:gYearMonth" returnEmptyOk="yes" isSchema="yes" prefix="xs" role="example" returnSeq="no" returnVaries="no" isDatatype="no" isSpecial="no" isOp="no"><arg name="arg" type="xs:anyAtomicType" emptyOk="yes"/></proto></item><item><proto name="gYear" return-type="xs:gYear" returnEmptyOk="yes" isSchema="yes" prefix="xs" role="example" returnSeq="no" returnVaries="no" isDatatype="no" isSpecial="no" isOp="no"><arg name="arg" type="xs:anyAtomicType" emptyOk="yes"/></proto></item><item><proto name="gMonthDay" return-type="xs:gMonthDay" returnEmptyOk="yes" isSchema="yes" prefix="xs" role="example" returnSeq="no" returnVaries="no" isDatatype="no" isSpecial="no" isOp="no"><arg name="arg" type="xs:anyAtomicType" emptyOk="yes"/></proto></item><item><proto name="gDay" return-type="xs:gDay" returnEmptyOk="yes" isSchema="yes" prefix="xs" role="example" returnSeq="no" returnVaries="no" isDatatype="no" isSpecial="no" isOp="no"><arg name="arg" type="xs:anyAtomicType" emptyOk="yes"/></proto></item><item><proto name="gMonth" return-type="xs:gMonth" returnEmptyOk="yes" isSchema="yes" prefix="xs" role="example" returnSeq="no" returnVaries="no" isDatatype="no" isSpecial="no" isOp="no"><arg name="arg" type="xs:anyAtomicType" emptyOk="yes"/></proto></item><item><proto name="hexBinary" return-type="xs:hexBinary" returnEmptyOk="yes" isSchema="yes" prefix="xs" role="example" returnSeq="no" returnVaries="no" isDatatype="no" isSpecial="no" isOp="no"><arg name="arg" type="xs:anyAtomicType" emptyOk="yes"/></proto></item><item><proto name="base64Binary" return-type="xs:base64Binary" returnEmptyOk="yes" isSchema="yes" prefix="xs" role="example" returnSeq="no" returnVaries="no" isDatatype="no" isSpecial="no" isOp="no"><arg name="arg" type="xs:anyAtomicType" emptyOk="yes"/></proto></item><item><proto name="anyURI" return-type="xs:anyURI" returnEmptyOk="yes" isSchema="yes" prefix="xs" role="example" returnSeq="no" returnVaries="no" isDatatype="no" isSpecial="no" isOp="no"><arg name="arg" type="xs:anyAtomicType" emptyOk="yes"/></proto></item><item><proto name="QName" return-type="xs:QName" returnEmptyOk="yes" isSchema="yes" prefix="xs" role="example" returnSeq="no" returnVaries="no" isDatatype="no" isSpecial="no" isOp="no"><arg name="arg" type="xs:anyAtomicType" emptyOk="yes"/></proto><p>
                            See <specref ref="constructor-qname-notation"/> for special rules.</p></item></ulist><ulist><item><proto name="normalizedString" return-type="xs:normalizedString" returnEmptyOk="yes" isSchema="yes" prefix="xs" role="example" returnSeq="no" returnVaries="no" isDatatype="no" isSpecial="no" isOp="no"><arg name="arg" type="xs:anyAtomicType" emptyOk="yes"/></proto></item><item><proto name="token" return-type="xs:token" returnEmptyOk="yes" isSchema="yes" prefix="xs" role="example" returnSeq="no" returnVaries="no" isDatatype="no" isSpecial="no" isOp="no"><arg name="arg" type="xs:anyAtomicType" emptyOk="yes"/></proto></item><item><proto name="language" return-type="xs:language" returnEmptyOk="yes" isSchema="yes" prefix="xs" role="example" returnSeq="no" returnVaries="no" isDatatype="no" isSpecial="no" isOp="no"><arg name="arg" type="xs:anyAtomicType" emptyOk="yes"/></proto></item><item><proto name="NMTOKEN" return-type="xs:NMTOKEN" returnEmptyOk="yes" isSchema="yes" prefix="xs" role="example" returnSeq="no" returnVaries="no" isDatatype="no" isSpecial="no" isOp="no"><arg name="arg" type="xs:anyAtomicType" emptyOk="yes"/></proto></item><item><proto name="Name" return-type="xs:Name" returnEmptyOk="yes" isSchema="yes" prefix="xs" role="example" returnSeq="no" returnVaries="no" isDatatype="no" isSpecial="no" isOp="no"><arg name="arg" type="xs:anyAtomicType" emptyOk="yes"/></proto></item><item><proto name="NCName" return-type="xs:NCName" returnEmptyOk="yes" isSchema="yes" prefix="xs" role="example" returnSeq="no" returnVaries="no" isDatatype="no" isSpecial="no" isOp="no"><arg name="arg" type="xs:anyAtomicType" emptyOk="yes"/></proto></item><item><proto name="ID" return-type="xs:ID" returnEmptyOk="yes" isSchema="yes" prefix="xs" role="example" returnSeq="no" returnVaries="no" isDatatype="no" isSpecial="no" isOp="no"><arg name="arg" type="xs:anyAtomicType" emptyOk="yes"/></proto></item><item><proto name="IDREF" return-type="xs:IDREF" returnEmptyOk="yes" isSchema="yes" prefix="xs" role="example" returnSeq="no" returnVaries="no" isDatatype="no" isSpecial="no" isOp="no"><arg name="arg" type="xs:anyAtomicType" emptyOk="yes"/></proto></item><item><proto name="ENTITY" return-type="xs:ENTITY" returnEmptyOk="yes" isSchema="yes" prefix="xs" role="example" returnSeq="no" returnVaries="no" isDatatype="no" isSpecial="no" isOp="no"><arg name="arg" type="xs:anyAtomicType" emptyOk="yes"/></proto><p>See <specref ref="casting-to-ENTITY"/> for rules related to constructing values of type <code>xs:ENTITY</code> and types derived from it.</p></item><item><proto name="integer" return-type="xs:integer" returnEmptyOk="yes" isSchema="yes" prefix="xs" role="example" returnSeq="no" returnVaries="no" isDatatype="no" isSpecial="no" isOp="no"><arg name="arg" type="xs:anyAtomicType" emptyOk="yes"/></proto></item><item><proto name="nonPositiveInteger" return-type="xs:nonPositiveInteger" returnEmptyOk="yes" isSchema="yes" prefix="xs" role="example" returnSeq="no" returnVaries="no" isDatatype="no" isSpecial="no" isOp="no"><arg name="arg" type="xs:anyAtomicType" emptyOk="yes"/></proto></item><item><proto name="negativeInteger" return-type="xs:negativeInteger" returnEmptyOk="yes" isSchema="yes" prefix="xs" role="example" returnSeq="no" returnVaries="no" isDatatype="no" isSpecial="no" isOp="no"><arg name="arg" type="xs:anyAtomicType" emptyOk="yes"/></proto></item><item><proto name="long" return-type="xs:long" returnEmptyOk="yes" isSchema="yes" prefix="xs" role="example" returnSeq="no" returnVaries="no" isDatatype="no" isSpecial="no" isOp="no"><arg name="arg" type="xs:anyAtomicType" emptyOk="yes"/></proto></item><item><proto name="int" return-type="xs:int" returnEmptyOk="yes" isSchema="yes" prefix="xs" role="example" returnSeq="no" returnVaries="no" isDatatype="no" isSpecial="no" isOp="no"><arg name="arg" type="xs:anyAtomicType" emptyOk="yes"/></proto></item><item><proto name="short" return-type="xs:short" returnEmptyOk="yes" isSchema="yes" prefix="xs" role="example" returnSeq="no" returnVaries="no" isDatatype="no" isSpecial="no" isOp="no"><arg name="arg" type="xs:anyAtomicType" emptyOk="yes"/></proto></item><item><proto name="byte" return-type="xs:byte" returnEmptyOk="yes" isSchema="yes" prefix="xs" role="example" returnSeq="no" returnVaries="no" isDatatype="no" isSpecial="no" isOp="no"><arg name="arg" type="xs:anyAtomicType" emptyOk="yes"/></proto></item><item><proto name="nonNegativeInteger" return-type="xs:nonNegativeInteger" returnEmptyOk="yes" isSchema="yes" prefix="xs" role="example" returnSeq="no" returnVaries="no" isDatatype="no" isSpecial="no" isOp="no"><arg name="arg" type="xs:anyAtomicType" emptyOk="yes"/></proto></item><item><proto name="unsignedLong" return-type="xs:unsignedLong" returnEmptyOk="yes" isSchema="yes" prefix="xs" role="example" returnSeq="no" returnVaries="no" isDatatype="no" isSpecial="no" isOp="no"><arg name="arg" type="xs:anyAtomicType" emptyOk="yes"/></proto></item><item><proto name="unsignedInt" return-type="xs:unsignedInt" returnEmptyOk="yes" isSchema="yes" prefix="xs" role="example" returnSeq="no" returnVaries="no" isDatatype="no" isSpecial="no" isOp="no"><arg name="arg" type="xs:anyAtomicType" emptyOk="yes"/></proto></item><item><proto name="unsignedShort" return-type="xs:unsignedShort" returnEmptyOk="yes" isSchema="yes" prefix="xs" role="example" returnSeq="no" returnVaries="no" isDatatype="no" isSpecial="no" isOp="no"><arg name="arg" type="xs:anyAtomicType" emptyOk="yes"/></proto></item><item><proto name="unsignedByte" return-type="xs:unsignedByte" returnEmptyOk="yes" isSchema="yes" prefix="xs" role="example" returnSeq="no" returnVaries="no" isDatatype="no" isSpecial="no" isOp="no"><arg name="arg" type="xs:anyAtomicType" emptyOk="yes"/></proto></item><item><proto name="positiveInteger" return-type="xs:positiveInteger" returnEmptyOk="yes" isSchema="yes" prefix="xs" role="example" returnSeq="no" returnVaries="no" isDatatype="no" isSpecial="no" isOp="no"><arg name="arg" type="xs:anyAtomicType" emptyOk="yes"/></proto></item></ulist><ulist><item><proto name="yearMonthDuration" return-type="xs:yearMonthDuration" returnEmptyOk="yes" isSchema="yes" prefix="xs" role="example" returnSeq="no" returnVaries="no" isDatatype="no" isSpecial="no" isOp="no"><arg name="arg" type="xs:anyAtomicType" emptyOk="yes"/></proto></item><item><proto name="dayTimeDuration" return-type="xs:dayTimeDuration" returnEmptyOk="yes" isSchema="yes" prefix="xs" role="example" returnSeq="no" returnVaries="no" isDatatype="no" isSpecial="no" isOp="no"><arg name="arg" type="xs:anyAtomicType" emptyOk="yes"/></proto></item><item><proto name="untypedAtomic" return-type="xs:untypedAtomic" returnEmptyOk="yes" isSchema="yes" prefix="xs" role="example" returnSeq="no" returnVaries="no" isDatatype="no" isSpecial="no" isOp="no"><arg name="arg" type="xs:anyAtomicType" emptyOk="yes"/></proto></item></ulist><ulist><item><proto name="dateTimeStamp" return-type="xs:dateTimeStamp" returnEmptyOk="yes" isSchema="yes" prefix="xs" role="example" returnSeq="no" returnVaries="no" isDatatype="no" isSpecial="no" isOp="no"><arg name="arg" type="xs:anyAtomicType" emptyOk="yes"/></proto><p><emph>Available only if the implementation supports XSD 1.1.</emph></p></item></ulist></div2><div2 id="constructor-qname-notation"><head>Constructor functions for xs:QName and xs:NOTATION</head><p>Special rules apply to constructor functions for the types <code>xs:QName</code> and <code>xs:NOTATION</code>, for two reasons:</p><ulist><item><p>
Values cannot belong directly to the type <code>xs:NOTATION</code>, only to its subtypes.
</p></item><item><p>
The lexical representation of these types uses namespace prefixes, whose
meaning is context-dependent.</p></item></ulist><p>
These constraints result in the following rules:</p><olist><item><p>
There is no constructor function for <code>xs:NOTATION</code>. Constructors are defined, however, for <code>xs:QName</code>, 
   for types derived or constructed from <code>xs:QName</code>, and for types 
   derived or constructed from <code>xs:NOTATION</code>.
</p></item><item><p>When converting from an <code>xs:string</code>, the prefix within the lexical 
      <code>xs:QName</code> supplied
      as the argument is resolved to a namespace URI using the statically known
      namespaces from the static context. If the lexical <code>xs:QName</code>
      has no prefix, the
      namespace URI of the resulting expanded-QName is the default element/type
      namespace from the static context. Components of the static context are
      defined in <xspecref spec="XP31" ref="static_context"/>. A dynamic error is raised <errorref class="NS" code="0004"/>
      if the prefix is not bound in the static context. As described in
      <xspecref spec="DM31" ref="terminology"/>, the supplied prefix is retained as part of the
      expanded-QName value.</p></item></olist><p>When a constructor function for a namespace-sensitive type is used as a literal function item
      or in a partial function application (for example, <code>xs:QName#1</code> or <code>xs:QName(?)</code>) the namespace
      bindings that are relevant are those from the static context of the literal function item or partial function application.
      When a constructor function for a namespace-sensitive type is obtained by means of the <code>fn:function-lookup</code>
      function, the relevant namespace bindings are those from the static context of the call on <code>fn:function-lookup</code>.</p><note><p>When the supplied argument to the <code>xs:QName</code> constructor
   function is a node, the node is atomized in the usual way, and if the result is <code>xs:untypedAtomic</code> it is then
   converted as if a string had been supplied. The effect might not be what is desired.
   For example, given the attribute <code>xsi:type="my:type"</code>, the expression 
   <code>xs:QName(@xsi:type)</code> might fail on the grounds that the prefix <code>my</code>
   is undeclared. This is because the namespace bindings are taken from the static context
   (that is, from the query or stylesheet), and not from the source document containing the
   <code>@xsi:type</code> attribute. The solution to this problem is to use the function call
   <code>resolve-QName(@xsi:type, .)</code> instead.</p></note></div2><div2 id="constructor-functions-for-xsd-list-types"><head>Constructor functions for XML Schema built-in list types</head><p>Each of the three built-in list
                 types defined in <bibref ref="xmlschema-2"/>,
                 namely <code>xs:NMTOKENS</code>, <code>xs:ENTITIES</code>, and <code>xs:IDREFS</code>, has an
                 associated constructor function.</p><p>The function signatures are as follows:</p><ulist><item><proto name="NMTOKENS" return-type="xs:NMTOKEN*" isSchema="yes" prefix="xs" role="example" returnEmptyOk="no" returnSeq="no" returnVaries="no" isDatatype="no" isSpecial="no" isOp="no"><arg name="arg" type="xs:anyAtomicType" emptyOk="yes"/></proto></item><item><proto name="ENTITIES" return-type="xs:ENTITY*" isSchema="yes" prefix="xs" role="example" returnEmptyOk="no" returnSeq="no" returnVaries="no" isDatatype="no" isSpecial="no" isOp="no"><arg name="arg" type="xs:anyAtomicType" emptyOk="yes"/></proto></item><item><proto name="IDREFS" return-type="xs:IDREF*" isSchema="yes" prefix="xs" role="example" returnEmptyOk="no" returnSeq="no" returnVaries="no" isDatatype="no" isSpecial="no" isOp="no"><arg name="arg" type="xs:anyAtomicType" emptyOk="yes"/></proto></item></ulist><p>The semantics are equivalent to casting to the corresponding types from <code>xs:string</code>.</p><p>All three of these types have the facet <code>minLength = 1</code> meaning that there must
              always be at least one item in the list. The return type, however, allows for the fact that when the argument to
              the function is an empty sequence, the result is an empty sequence.</p><note><p>In the case of atomic types, it is possible to use an expression such as 
                 <code>xs:date(@date-of-birth)</code> to convert an attribute value to an instance of <code>xs:date</code>,
                 knowing that this will work both in the case where the attribute is already annotated as <code>xs:date</code>,
                 and also in the case where it is <code>xs:untypedAtomic</code>. This approach does not work with list types,
                 because it is not permitted to use a value of type <code>xs:NMTOKEN*</code> as input to the constructor
                 function <code>xs:NMTOKENS</code>. Instead, it is necessary to use conditional logic that performs the conversion
                 only in the case where the input is untyped: 
                 <code>if (@x instance of attribute(*, xs:untypedAtomic)) then xs:NMTOKENS(@x) else data(@x)</code></p></note></div2><div2 id="constructor-functions-for-xsd-union-types"><head>Constructor functions for XML Schema built-in union types</head><p diff="add" at="E">There is a constructor function for the union type <code>xs:numeric</code>
                 defined in <bibref ref="xpath-datamodel-31"/>. The function signature is:</p><ulist><item><proto name="numeric" return-type="xs:numeric?" isSchema="yes" prefix="xs" role="example" returnEmptyOk="no" returnSeq="no" returnVaries="no" isDatatype="no" isSpecial="no" isOp="no"><arg name="arg" type="xs:anyAtomicType" emptyOk="yes"/></proto></item></ulist><p diff="add" at="E">The semantics are determined by the rules in <specref ref="casting-to-union"/>. These rules have the effect that: </p><olist><item><p>If the argument is an instance of <code>xs:double</code>, <code>xs:float</code>, or <code>xs:decimal</code>,
                 then the result is an instance of the same primitive type, with the same value;</p></item><item><p>If the argument is an instance of <code>xs:boolean</code>, the result is the <code>xs:double</code> value
                    <code>0.0e0</code> or <code>1.0e0</code>;</p></item><item><p>If the argument is an instance of <code>xs:string</code> or <code>xs:untypedAtomic</code>, then:</p><olist><item><p>If the value is in the lexical space of <code>xs:double</code>, the result will be the
                       corresponding <code>xs:double</code> value;</p></item><item><p>Otherwise, a dynamic error <errorref class="RG" code="0001"/> occurs;</p></item></olist><note><p>The result will never be an instance of <code>xs:float</code>, <code>xs:decimal</code>,
                    or <code>xs:integer</code>. This is because <code>xs:double</code> appears first in the list of member
                    types of <code>xs:numeric</code>, and its lexical space subsumes the lexical space of the other numeric
                    types. Thus, unlike XPath numeric literals, the result does not depend on the lexical form of the supplied
                    value. The reason for this design choice is to retain compatibility with the function conversion rules:
                    functions such as <code>fn:abs</code> and <code>fn:round</code> are declared to expect an instance
                    of <code>xs:numeric</code> as their first or only argument, and compatibility with the function conversion
                    rules defined in earlier versions of these specifications demands that when an untyped atomic value
                    (or untyped node) is supplied as the argument, it is converted to an <code>xs:double</code> value
                       even if its lexical form is that (say) of an integer.</p></note></item><item><p>In all other cases, a dynamic error <errorref class="RG" code="0001"/> occurs.</p></item></olist><p>In the case of an implementation that supports XSD 1.1, there is a constructor function
              associated with the built-in union type <code>xs:error</code>.</p><p>The function signature is as follows:</p><ulist><item><proto name="error" return-type="xs:error?" isSchema="yes" prefix="xs" role="example" returnEmptyOk="no" returnSeq="no" returnVaries="no" isDatatype="no" isSpecial="no" isOp="no"><arg name="arg" type="xs:anyAtomicType" emptyOk="yes"/></proto></item></ulist><p>The semantics are equivalent to casting to the corresponding union type (see <specref ref="casting-to-union"/>).</p><note><p>Because <code>xs:error</code> has no member types, and therefore has an empty value space, casting
              will always fail with a dynamic error except in the case where the supplied argument is an empty
              sequence, in which case the result is also an empty sequence.</p></note></div2><div2 id="constructor-functions-for-user-defined-types"><head>Constructor functions for user-defined types</head><p> For every user-defined simple type in the static context (See <xspecref spec="XP31" ref="static_context"/>), there is a
                    constructor function whose name is the same as the name of the type and whose
                    effect is to create a value of that type from the supplied argument. The rules
                    for constructing user-defined types are defined in the same way as the rules for
                    constructing built-in derived types defined in <specref ref="constructor-functions-for-xsd-types"/>. </p><p>
                            Special rules apply to constructor functions for namespace-sensitive types, that is,
                            atomic types derived from <code>xs:QName</code> and <code>xs:NOTATION</code>, list types that have
   a namespace-sensitive item type, and union types that have a namespace-sensitive member type. See <specref ref="constructor-qname-notation"/>.</p><p>Consider a situation where the static context contains an atomic type
                    called <code>hatSize</code> defined in a schema whose target namespace is bound
                    to the prefix <code>eg</code>. In such a case the following constructor function is available to users:</p><example role="signature"><proto prefix="eg" name="hatSize" return-type="my:hatSize" isSpecial="yes" returnEmptyOk="yes" role="example" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isOp="no"><arg name="arg" type="xs:anyAtomicType" emptyOk="yes"/></proto></example><p>In the case of an atomic type <var>A</var>, the return type of the function is <code>A?</code>, reflecting
               the fact that the result will be an empty sequence if the input is an empty sequence. For a union or list type,
               the return type of the function is specified only as <code>xs:anyAtomicType*</code>. Implementations performing
               static type checking will often be able to compute a more specific result type. For example, if the target type
               is a list type whose item type is the atomic type <var>A</var>, the result will always be an instance of <var>A*</var>;
               if the target type is a pure union type <var>U</var> then the result will always be an instance of <var>U?</var>.
               In general, however, applications needing interoperable behavior on implementations that do strict static type
               checking will need to use a <code>treat as</code> expression to assert the specific type of the result.</p><p> To construct an instance of a user-defined type 
                  that is not in a namespace, it is <phrase diff="add" at="D">possible to use an
                  <code>EQName</code> (for example <code>Q{}hatsize(17)</code>). Alternatives are</phrase>
                    to use a cast expression (<code>17 cast as hatsize</code>) or <phrase>(if the host language allows it)</phrase> 
                  to undeclare the default function namespace. </p></div2></div1><div1 id="casting"><head>Casting</head><p> Constructor functions and cast expressions accept an expression and return a value
                of a given type. They both convert a source value, <emph>SV</emph>, of a source type,
                <emph>ST</emph>, to a target value, <emph>TV</emph>, of the given target type,
                <emph>TT</emph>, with identical semantics and different syntax. The name of the
                constructor function is the same as the name of the built-in <bibref ref="xmlschema-2"/> 
                datatype or the datatype defined in <xspecref spec="DM31" ref="types"/>
                   of <bibref ref="xpath-datamodel-31"/> (see <specref ref="constructor-functions-for-xsd-types"/>) or the user-derived datatype
                (see <specref ref="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,
                    <code>xs:date("2003-01-01")</code>
                 means exactly the same as 
                    <code>"2003-01-01"</code> cast as <code>xs:date?</code>.</p><p>The cast expression takes a type name to indicate the target type of the conversion.
                See <xspecref spec="XP31" ref="id-cast"/>. If the type name allows the empty sequence
                and the expression to be cast is the empty sequence, the empty sequence is returned.
                If the type name does not allow the empty sequence and the expression to be cast is
                the empty sequence, a type error is raised <xerrorref spec="XP" class="TY" code="0004" type="type"/>.</p><p>Where the argument to a cast is a literal, the result of the function <rfc2119>may</rfc2119> be
                evaluated statically; if an error is encountered during such evaluation, it <rfc2119>may</rfc2119> be
                reported as a static error. </p><p>The general rules for casting from primitive types to primitive types are defined in
            <specref ref="casting-from-primitive-to-primitive"/>, and subsections describe the rules
            for specific target types.
            The general rules for casting from <code>xs:string</code> (and <code>xs:untypedAtomic</code>)
            follow in <specref ref="casting-from-strings"/>.
            Casting to non-primitive types, including atomic types derived by resctriction,
            union types, and list types, is described in <specref ref="casting-non-primitive-types"/>.  
            Casting from derived types is defined in <specref ref="casting-from-derived-to-parent"/>, 
            <specref ref="casting-within-branch"/> and <specref ref="casting-across-hierarchy"/>.</p><p diff="add" at="D"><termdef id="dt-cast-primitive-type" term="primitive type">Throughout 
            this section (<specref ref="casting"/>), the term <term>primitive type</term> means either one of
            the 19 primitive types defined in <bibref ref="xmlschema-2"/>, or one of the types
            <code>xs:untypedAtomic</code>, <code>xs:integer</code>, <code>xs:yearMonthDuration</code>
            and <code>xs:dayTimeDuration</code>; and where the text refers to types derived from a particular
            primitive type <var>T</var>, the reference is to types for which <var>T</var> is the nearest
            ancestor-or-self primitive type in the type hierarchy.
         </termdef></p><p>When casting from <code>xs:string</code> or <code>xs:untypedAtomic</code>
            the semantics in <specref ref="casting-from-strings"/> apply, regardless of target type.</p><div2 id="casting-from-primitive-to-primitive"><head>Casting from primitive types to primitive types</head><p>This section defines casting between <termref def="dt-cast-primitive-type">primitive types</termref>
               (specifically, the 19 primitive types defined in <bibref ref="xmlschema-2"/> as well as <code>xs:untypedAtomic</code>,
                    <code>xs:integer</code> and the two derived types of
                    <code>xs:duration</code>: <code>xs:yearMonthDuration</code>
                    and <code>xs:dayTimeDuration</code> which are treated as primitive types in this section. The type conversions
                    that are supported between primitive atomic types are indicated in the table below;
                    casts between other (non-primitive) types are defined in terms of these primitives.</p><p>In this table, there is a
               row for each <termref def="dt-cast-primitive-type">primitive type</termref> acting as the source of the conversion and
               there is a column for each <termref def="dt-cast-primitive-type">primitive type</termref> acting as the target of the conversion. The
                    intersections of rows and columns contain one of three characters:
                    <code>Y</code> indicates that a conversion from values of the type to which
                    the row applies to the type to which the column applies is supported;
                    <code>N</code> 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 <code>M</code> indicates that a conversion from values of the type to
                    which the row applies to the type to which the column applies may succeed for
                    some values in the value space and fail for others.</p><p>
               <bibref ref="xmlschema-2"/> defines <code>xs:NOTATION</code> as an abstract type. 
               Thus, casting to <code>xs:NOTATION</code> from any other type including <code>xs:NOTATION</code>
               is not permitted and raises a static error <xerrorref spec="XP" class="ST" code="0080"/>.  
               However, casting from one subtype of <code>xs:NOTATION</code> to another subtype of 
               <code>xs:NOTATION</code> is permitted.</p><p>Casting is not supported to or from <code>xs:anySimpleType</code>. Thus, there is no row
               or column for this type in the table below. For any node that has not been validated or 
               has been validated as <code>xs:anySimpleType</code>, the typed value of the node is an 
               atomic value of type <code>xs:untypedAtomic</code>. There are no atomic values with the 
               type annotation <code>xs:anySimpleType</code> at runtime. 
                  Casting to
                     <code>xs:anySimpleType</code> is not permitted and raises a static error:
                     <xerrorref spec="XP" class="ST" code="0080"/>.</p><p>Similarly, casting is not supported to or from <code>xs:anyAtomicType</code> and will raise 
               a static error: <xerrorref spec="XP" class="ST" code="0080"/>. There are no atomic values 
               with the type annotation <code>xs:anyAtomicType</code> at runtime, although this can be a 
               statically inferred type.</p><p>If casting is attempted from an <emph>ST</emph> to a <emph>TT</emph> for which
                    casting is not supported, as defined in the table below, a type error is raised <xerrorref spec="XP" class="TY" code="0004" type="type"/>.</p><p>In the following table, the columns and rows are identified by short codes that
                    identify simple types as follows:</p><slist><sitem>uA = xs:untypedAtomic</sitem><sitem>aURI = xs:anyURI</sitem><sitem>b64 = xs:base64Binary</sitem><sitem>bool = xs:boolean</sitem><sitem>dat = xs:date</sitem><sitem>gDay = xs:gDay</sitem><sitem>dbl = xs:double</sitem><sitem>dec = xs:decimal</sitem><sitem>dT = xs:dateTime</sitem><sitem>dTD = xs:dayTimeDuration</sitem><sitem>dur = xs:duration</sitem><sitem>flt = xs:float</sitem><sitem>hxB = xs:hexBinary</sitem><sitem>gMD = xs:gMonthDay</sitem><sitem>gMon = xs:gMonth</sitem><sitem>int = xs:integer</sitem><sitem>NOT = xs:NOTATION</sitem><sitem>QN = xs:QName</sitem><sitem>str = xs:string</sitem><sitem>tim = xs:time</sitem><sitem>gYM = xs:gYearMonth</sitem><sitem>yMD = xs:yearMonthDuration</sitem><sitem>gYr = xs:gYear</sitem></slist><p>In the following table, the notation <quote>S\T</quote> indicates that the source
                    (<quote>S</quote>) of the conversion is indicated in the column below the
                    notation and that the target (<quote>T</quote>) is indicated in the row to the
                    right of the notation.</p><table border="1" cellpadding="1" role="casting" summary="Casting table" id="casting-to-primitives-table"><col width="5%" span="1"/><col width="3%" span="1"/><col width="3%" span="1"/><col width="3%" span="1"/><col width="3%" span="1"/><col width="3%" span="1"/><col width="3%" span="1"/><col width="3%" span="1"/><col width="3%" span="1"/><col width="3%" span="1"/><col width="3%" span="1"/><col width="3%" span="1"/><col width="3%" span="1"/><col width="3%" span="1"/><col width="3%" span="1"/><col width="3%" span="1"/><col width="3%" span="1"/><col width="3%" span="1"/><col width="3%" span="1"/><col width="3%" span="1"/><col width="3%" span="1"/><col width="3%" span="1"/><col width="3%" span="1"/><col width="3%" span="1"/><thead><tr><th rowspan="1" colspan="1">S\T</th><th rowspan="1" colspan="1">uA</th><th rowspan="1" colspan="1">str</th><th rowspan="1" colspan="1">flt</th><th rowspan="1" colspan="1">dbl</th><th rowspan="1" colspan="1">dec</th><th rowspan="1" colspan="1">int</th><th rowspan="1" colspan="1">dur</th><th rowspan="1" colspan="1">yMD</th><th rowspan="1" colspan="1">dTD</th><th rowspan="1" colspan="1">dT</th><th rowspan="1" colspan="1">tim</th><th rowspan="1" colspan="1">dat</th><th rowspan="1" colspan="1">gYM</th><th rowspan="1" colspan="1">gYr</th><th rowspan="1" colspan="1">gMD</th><th rowspan="1" colspan="1">gDay</th><th rowspan="1" colspan="1">gMon</th><th rowspan="1" colspan="1">bool</th><th rowspan="1" colspan="1">b64</th><th rowspan="1" colspan="1">hxB</th><th rowspan="1" colspan="1">aURI</th><th rowspan="1" colspan="1">QN</th><th rowspan="1" colspan="1">NOT</th></tr></thead><tbody><tr><th rowspan="1" colspan="1">uA</th><td rowspan="1" colspan="1">Y</td><td rowspan="1" colspan="1">Y</td><td rowspan="1" colspan="1">M</td><td rowspan="1" colspan="1">M</td><td rowspan="1" colspan="1">M</td><td rowspan="1" colspan="1">M</td><td rowspan="1" colspan="1">M</td><td rowspan="1" colspan="1">M</td><td rowspan="1" colspan="1">M</td><td rowspan="1" colspan="1">M</td><td rowspan="1" colspan="1">M</td><td rowspan="1" colspan="1">M</td><td rowspan="1" colspan="1">M</td><td rowspan="1" colspan="1">M</td><td rowspan="1" colspan="1">M</td><td rowspan="1" colspan="1">M</td><td rowspan="1" colspan="1">M</td><td rowspan="1" colspan="1">M</td><td rowspan="1" colspan="1">M</td><td rowspan="1" colspan="1">M</td><td rowspan="1" colspan="1">M</td><td rowspan="1" colspan="1">M</td><td rowspan="1" colspan="1">M</td></tr><tr><th rowspan="1" colspan="1">str</th><td rowspan="1" colspan="1">Y</td><td rowspan="1" colspan="1">Y</td><td rowspan="1" colspan="1">M</td><td rowspan="1" colspan="1">M</td><td rowspan="1" colspan="1">M</td><td rowspan="1" colspan="1">M</td><td rowspan="1" colspan="1">M</td><td rowspan="1" colspan="1">M</td><td rowspan="1" colspan="1">M</td><td rowspan="1" colspan="1">M</td><td rowspan="1" colspan="1">M</td><td rowspan="1" colspan="1">M</td><td rowspan="1" colspan="1">M</td><td rowspan="1" colspan="1">M</td><td rowspan="1" colspan="1">M</td><td rowspan="1" colspan="1">M</td><td rowspan="1" colspan="1">M</td><td rowspan="1" colspan="1">M</td><td rowspan="1" colspan="1">M</td><td rowspan="1" colspan="1">M</td><td rowspan="1" colspan="1">M</td><td rowspan="1" colspan="1">M</td><td rowspan="1" colspan="1">M</td></tr><tr><th rowspan="1" colspan="1">flt</th><td rowspan="1" colspan="1">Y</td><td rowspan="1" colspan="1">Y</td><td rowspan="1" colspan="1">Y</td><td rowspan="1" colspan="1">Y</td><td rowspan="1" colspan="1">M</td><td rowspan="1" colspan="1">M</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">Y</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td></tr><tr><th rowspan="1" colspan="1">dbl</th><td rowspan="1" colspan="1">Y</td><td rowspan="1" colspan="1">Y</td><td rowspan="1" colspan="1">Y</td><td rowspan="1" colspan="1">Y</td><td rowspan="1" colspan="1">M</td><td rowspan="1" colspan="1">M</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">Y</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td></tr><tr><th rowspan="1" colspan="1">dec</th><td rowspan="1" colspan="1">Y</td><td rowspan="1" colspan="1">Y</td><td rowspan="1" colspan="1">Y</td><td rowspan="1" colspan="1">Y</td><td rowspan="1" colspan="1">Y</td><td rowspan="1" colspan="1">Y</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">Y</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td></tr><tr><th rowspan="1" colspan="1">int</th><td rowspan="1" colspan="1">Y</td><td rowspan="1" colspan="1">Y</td><td rowspan="1" colspan="1">Y</td><td rowspan="1" colspan="1">Y</td><td rowspan="1" colspan="1">Y</td><td rowspan="1" colspan="1">Y</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">Y</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td></tr><tr><th rowspan="1" colspan="1">dur</th><td rowspan="1" colspan="1">Y</td><td rowspan="1" colspan="1">Y</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">Y</td><td rowspan="1" colspan="1">Y</td><td rowspan="1" colspan="1">Y</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td></tr><tr><th rowspan="1" colspan="1">yMD</th><td rowspan="1" colspan="1">Y</td><td rowspan="1" colspan="1">Y</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">Y</td><td rowspan="1" colspan="1">Y</td><td rowspan="1" colspan="1">Y</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td></tr><tr><th rowspan="1" colspan="1">dTD</th><td rowspan="1" colspan="1">Y</td><td rowspan="1" colspan="1">Y</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">Y</td><td rowspan="1" colspan="1">Y</td><td rowspan="1" colspan="1">Y</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td></tr><tr><th rowspan="1" colspan="1">dT</th><td rowspan="1" colspan="1">Y</td><td rowspan="1" colspan="1">Y</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">Y</td><td rowspan="1" colspan="1">Y</td><td rowspan="1" colspan="1">Y</td><td rowspan="1" colspan="1">Y</td><td rowspan="1" colspan="1">Y</td><td rowspan="1" colspan="1">Y</td><td rowspan="1" colspan="1">Y</td><td rowspan="1" colspan="1">Y</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td></tr><tr><th rowspan="1" colspan="1">tim</th><td rowspan="1" colspan="1">Y</td><td rowspan="1" colspan="1">Y</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">Y</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td></tr><tr><th rowspan="1" colspan="1">dat</th><td rowspan="1" colspan="1">Y</td><td rowspan="1" colspan="1">Y</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">Y</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">Y</td><td rowspan="1" colspan="1">Y</td><td rowspan="1" colspan="1">Y</td><td rowspan="1" colspan="1">Y</td><td rowspan="1" colspan="1">Y</td><td rowspan="1" colspan="1">Y</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td></tr><tr><th rowspan="1" colspan="1">gYM</th><td rowspan="1" colspan="1">Y</td><td rowspan="1" colspan="1">Y</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">Y</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td></tr><tr><th rowspan="1" colspan="1">gYr</th><td rowspan="1" colspan="1">Y</td><td rowspan="1" colspan="1">Y</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">Y</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td></tr><tr><th rowspan="1" colspan="1">gMD</th><td rowspan="1" colspan="1">Y</td><td rowspan="1" colspan="1">Y</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">Y</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td></tr><tr><th rowspan="1" colspan="1">gDay</th><td rowspan="1" colspan="1">Y</td><td rowspan="1" colspan="1">Y</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">Y</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td></tr><tr><th rowspan="1" colspan="1">gMon</th><td rowspan="1" colspan="1">Y</td><td rowspan="1" colspan="1">Y</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">Y</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td></tr><tr><th rowspan="1" colspan="1">bool</th><td rowspan="1" colspan="1">Y</td><td rowspan="1" colspan="1">Y</td><td rowspan="1" colspan="1">Y</td><td rowspan="1" colspan="1">Y</td><td rowspan="1" colspan="1">Y</td><td rowspan="1" colspan="1">Y</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">Y</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td></tr><tr><th rowspan="1" colspan="1">b64</th><td rowspan="1" colspan="1">Y</td><td rowspan="1" colspan="1">Y</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">Y</td><td rowspan="1" colspan="1">Y</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td></tr><tr><th rowspan="1" colspan="1">hxB</th><td rowspan="1" colspan="1">Y</td><td rowspan="1" colspan="1">Y</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">Y</td><td rowspan="1" colspan="1">Y</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td></tr><tr><th rowspan="1" colspan="1">aURI</th><td rowspan="1" colspan="1">Y</td><td rowspan="1" colspan="1">Y</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">Y</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td></tr><tr><th rowspan="1" colspan="1">QN</th><td rowspan="1" colspan="1">Y</td><td rowspan="1" colspan="1">Y</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">Y</td><td rowspan="1" colspan="1">M</td></tr><tr><th rowspan="1" colspan="1">NOT</th><td rowspan="1" colspan="1">Y</td><td rowspan="1" colspan="1">Y</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">N</td><td rowspan="1" colspan="1">Y</td><td rowspan="1" colspan="1">M</td></tr></tbody></table><div3 id="casting-to-string"><head>Casting to xs:string and xs:untypedAtomic</head><p>Casting is permitted from any <termref def="dt-cast-primitive-type">primitive type</termref> to the 
                  <termref def="dt-cast-primitive-type">primitive types</termref>
                        <code>xs:string</code> and <code>xs:untypedAtomic</code>.</p><p>When a value of any simple type is cast as <code>xs:string</code>, the
                        derivation of the <code>xs:string</code> value <emph>TV</emph> depends on
                        the <emph>ST</emph> and on the <emph>SV</emph>, as follows.</p><ulist><item><p>If <emph>ST</emph> is <code>xs:string</code> or a type derived from
                                <code>xs:string</code>, <emph>TV</emph> is <emph>SV</emph>.</p></item><item><p>If <emph>ST</emph> is <code>xs:anyURI</code>, the type conversion is
                                performed without escaping any characters.</p></item><item><p>If <emph>ST</emph> is <code>xs:QName</code> or <code>xs:NOTATION</code>:</p><ulist><item><p>if the qualified name
          has a prefix, then <emph>TV</emph> is the concatenation of the prefix of <emph>SV</emph>, 
		  a single colon (:), and the local name of <emph>SV</emph>.</p></item><item><p>otherwise <emph>TV</emph> is the local-name.</p></item></ulist></item><item><p>If <emph>ST</emph> is a numeric type, the following rules apply:</p><ulist><item><p>If <emph>ST</emph> is <code>xs:integer</code>,
                                        <emph>TV</emph> is the canonical lexical representation of
                                        <emph>SV</emph> as defined in <bibref ref="xmlschema-2"/>. There
                                        is no decimal point.</p></item><item><p>If <emph>ST</emph> is <code>xs:decimal</code>, then:</p><ulist><item><p>If <emph>SV</emph> is in the value space of
                                                <code>xs:integer</code>, that is, if there are no
                                                significant digits after the decimal point, then the
                                                value is converted from an <code>xs:decimal</code>
                                                to an <code>xs:integer</code> and the resulting
                                                <code>xs:integer</code> is converted to an
                                                <code>xs:string</code> using the rule above.</p></item><item><p> Otherwise, the canonical lexical representation of
                                                <emph>SV</emph> is returned, as defined in <bibref ref="xmlschema-2"/>.</p></item></ulist></item><item><p> If <emph>ST</emph> is <code>xs:float</code> or
                                        <code>xs:double</code>, then:</p><ulist><item><p>
                                    <emph>TV</emph> will be an <code>xs:string</code> in the lexical space of <code>xs:double</code> or <code>xs:float</code> that when
converted to an <code>xs:double</code> or <code>xs:float</code> under the rules of <specref ref="casting-from-strings"/> produces
a value that is equal to <emph>SV</emph>, or is <code>NaN</code> if <emph>SV</emph> is <code>NaN</code>.
In addition, <emph>TV</emph> must satisfy the constraints in the
following sub-bullets.
											</p><ulist><item><p>If <emph>SV</emph> has an absolute value that is
                                                greater than or equal to 0.000001 (one millionth)
                                                and less than 1000000 (one million), then the value
                                                is converted to an <code>xs:decimal</code> and the
                                                resulting <code>xs:decimal</code> is converted to an
                                                <code>xs:string</code> according to the rules above, as though using an 
implementation of <code>xs:decimal</code> that imposes no limits on the
<code>totalDigits</code> or
<code>fractionDigits</code> facets.</p></item><item><p>If <emph>SV</emph> has the value positive or negative zero, <emph>TV</emph> is "0" or "-0"
respectively.
</p></item><item><p>If <emph>SV</emph> is positive or negative infinity, <emph>TV</emph> is the string "<code>INF</code>" or "<code>-INF</code>" respectively.
</p></item><item><p>In other cases, the result consists of a mantissa, which has the lexical form
of an <code>xs:decimal</code>, followed by the letter "E", followed by an exponent which has
the lexical form of an <code>xs:integer</code>. Leading zeroes and "+" signs are prohibited
in the exponent. For the mantissa, there must be a decimal point, and there must
be exactly one digit before the decimal point, which must be non-zero. The  "+"
sign is prohibited. There must be at least one digit after the decimal point.
Apart from this mandatory digit, trailing zero digits are prohibited. 
</p></item></ulist></item></ulist><note><p>The above rules allow more than one representation of the same value. 
                                 For example, the <code>xs:float</code> value whose exact decimal representation is 1.26743223E15
might be represented by any of the strings "1.26743223E15", "1.26743222E15" or
"1.26743224E15" (inter alia). It is implementation-dependent which of these
representations is chosen.
</p></note></item></ulist></item><item><p>If <emph>ST</emph> is <code>xs:dateTime</code>, <code>xs:date</code>
                                or <code>xs:time</code>, <emph>TV</emph> is the local value. 
The components of <emph>TV</emph> are individually cast to <code>xs:string</code> using the functions 
                        described in <bibref ref="casting-to-datetimes"/> 
                        and the results are concatenated together.  The <code>year</code> component is 
                        cast to <code>xs:string</code> using <code>eg:convertYearToString</code>.  
                        The <code>month</code>, <code>day</code>, <code>hour</code> and <code>minute</code> 
                        components are cast to <code>xs:string</code> using <code>eg:convertTo2CharString</code>.  
                        The <code>second</code> component is cast to <code>xs:string</code> using 
                        <code>eg:convertSecondsToString</code>. The timezone component, if present, is 
                        cast to <code>xs:string</code> using <code>eg:convertTZtoString</code>.  
</p><p> 
Note that the hours component of the resulting string
will never be <code>"24"</code>. Midnight is always represented as <code>"00:00:00"</code>.
</p></item><item><p>If <emph>ST</emph> is <code>xs:yearMonthDuration</code> or <code>xs:dayTimeDuration</code>, <emph>TV</emph> is the 
                                canonical representation of <emph>SV</emph> as defined in <bibref ref="xmlschema11-2"/>.</p></item><item><p>If <emph>ST</emph> is <code>xs:duration</code>
 then let <emph>SYM</emph> be <emph>
                           <code>SV</code>
                        </emph> 
                        <code>cast as xs:yearMonthDuration</code>, and let <emph>SDT</emph> be <emph>
                           <code>SV</code>
                        </emph> 
                        <code>cast as xs:dayTimeDuration</code>;  Now, let the next intermediate value, <emph>TYM</emph>, 
be <emph>
                           <code>SYM</code>
                        </emph> 
                        <code>cast as</code> 
                        <emph>
                           <code>TT</code>
                        </emph>, and let <emph>TDT</emph> be <emph>
                           <code>SDT</code>
                        </emph> 
                        <code>cast as</code> 
                        <emph>
                           <code>TT</code>
                        </emph>.  If <emph>TYM</emph> is "P0M", then <emph>TV</emph> is 
<emph>TDT</emph>.  Otherwise, <emph>TYM</emph> and <emph>TDT</emph> are merged according to the following rules:</p><olist><item><p>If <emph>TDT</emph> is "PT0S", then <emph>TV</emph> is <emph>TYM</emph>.</p></item><item><p>Otherwise, <emph>TV</emph> is the concatenation of all the characters in <emph>TYM</emph> and all the
characters except the first "P" and the optional negative sign in <emph>TDT</emph>.</p></item></olist></item><item><p>In all other cases, <emph>TV</emph> is the <bibref ref="xmlschema-2"/>
                                canonical representation of <emph>SV</emph>. For datatypes that do
                                not have a canonical lexical representation defined an <termref def="implementation-dependent"/> canonical representation may be used.</p></item></ulist><p>To cast as <code>xs:untypedAtomic</code> the value is cast as
                        <code>xs:string</code>, as described above, and the type annotation changed
                        to <code>xs:untypedAtomic</code>.</p><note><p>The string representations of numeric values are backwards compatible
                            with XPath 1.0 except for the special values positive and negative
                            infinity, negative zero and values outside the range <code>1.0e-6</code> to <code>1.0e+6</code>.</p></note></div3><div3 id="casting-to-numerics"><head>Casting to numeric types</head><div4 id="casting-to-float"><head>Casting to xs:float</head><p>When a value of any simple type is cast as <code>xs:float</code>, the <code>xs:float</code>
                            <emph>TV</emph> is derived from the <emph>ST</emph> and the
                            <emph>SV</emph> as follows:</p><ulist><item><p>If <emph>ST</emph> is <code>xs:float</code>, then <emph>TV</emph>
                                    is <emph>SV</emph> and the conversion is complete.</p></item><item><p>If <emph>ST</emph> is <code>xs:double</code>, then
                                    <emph>TV</emph> is obtained as follows: </p><ulist><item><p>if <emph>SV</emph> is the <code>xs:double</code> value
                                            <code>INF</code>, <code>-INF</code>, <code>NaN</code>,
                                            positive zero, or negative zero, then <emph>TV</emph> is
                                            the <code>xs:float</code> value <code>INF</code>,
                                            <code>-INF</code>, <code>NaN</code>, positive zero, or
                                            negative zero respectively.</p></item><item><p>otherwise, <emph>SV</emph> can be expressed in the form
                                                <code>m × 2^e</code> where the mantissa
                                            <code>m</code> and exponent <code>e</code> are signed
                                            <code>xs:integer</code>s whose value range is defined in
                                                <bibref ref="xmlschema-2"/>, and the following rules apply:</p><ulist><item><p>if <code>m</code> (the mantissa of
                                                  <emph>SV</emph>) is outside the permitted range
                                                  for the mantissa of an <code>xs:float</code>
                                                  value <code>(-2^24-1 to +2^24-1)</code>, then it
                                                  is divided by <code>2^N</code> where
                                                  <code>N</code> is the lowest positive
                                                  <code>xs:integer</code> that brings the result
                                                  of the division within the permitted range, and
                                                  the exponent <code>e</code> is increased by
                                                  <code>N</code>. This is integer division (in
                                                  effect, the binary value of the mantissa is
                                                  truncated on the right). Let <code>M</code> be
                                                  the mantissa and <code>E</code> the exponent
                                                  after this adjustment.</p></item><item><p>if <code>E</code> exceeds <code>104</code> (the
                                                  maximum exponent value in the value space of
                                                  <code>xs:float</code>) then <emph>TV</emph> is
                                                  the <code>xs:float</code> value <code>INF</code>
                                                  or <code>-INF</code> depending on the sign of <code>M</code>.</p></item><item><p>if <code>E</code> is less than <code>-149</code>
                                                  (the minimum exponent value in the value space
                                                  of <code>xs:float</code>) then <emph>TV</emph> is
                                                  the <code>xs:float</code> value positive or
                                                  negative zero depending on the sign of <code>M</code>
                                                </p></item><item><p>otherwise, <emph>TV</emph> is the
                                                  <code>xs:float</code> value <code>M × 2^E</code>.</p></item></ulist></item></ulist></item><item><p>If <emph>ST</emph> is <code>xs:decimal</code>, or
                                    <code>xs:integer</code>, then <emph>TV</emph> is <code>xs:float(</code>
                                    <emph>SV</emph>
                                    <code> cast as xs:string)</code> and the conversion is complete.</p></item><item><p>If <emph>ST</emph> is <code>xs:boolean</code>, <emph>SV</emph> is
                                    converted to <code>1.0E0</code> if <emph>SV</emph> is
                                    <code>true</code> and to <code>0.0E0</code> if <emph>SV</emph>
                                    is <code>false</code> and the conversion is complete.</p></item><item><p> If <emph>ST</emph> is <code>xs:untypedAtomic</code>
                                    or <code>xs:string</code>, see 
                                    <specref ref="casting-from-strings"/>. 
                        </p><note><p>XSD 1.1 adds the value <code>+INF</code> to the lexical space,
                           as an alternative to <code>INF</code>. XSD 1.1 also adds negative zero
                           to the value space.</p></note></item></ulist><note><p>Implementations <rfc2119>should</rfc2119> return negative zero for <code>xs:float("-0.0E0")</code>.  
                        But because <bibref ref="xmlschema-2"/> does not distinguish between the values positive zero and negative zero.
                        Implementations <rfc2119>may</rfc2119> return positive zero in this case.</p></note></div4><div4 id="casting-to-double"><head>Casting to xs:double</head><p>When a value of any simple type is cast as <code>xs:double</code>, the
                            <code>xs:double</code> value <emph>TV</emph> is derived from the
                            <emph>ST</emph> and the <emph>SV</emph> as follows:</p><ulist><item><p>If <emph>ST</emph> is <code>xs:double</code>, then
                                    <emph>TV</emph> is <emph>SV</emph> and the conversion is complete.</p></item><item><p>If <emph>ST</emph> is <code>xs:float</code> or a type derived
                                    from <code>xs:float</code>, then <emph>TV</emph> is obtained as follows:</p><ulist><item><p>if <emph>SV</emph> is the <code>xs:float</code> value
                                            <code>INF</code>, <code>-INF</code>, <code>NaN</code>,
                                            positive zero, or negative zero, then <emph>TV</emph> is
                                            the <code>xs:double</code> value <code>INF</code>,
                                            <code>-INF</code>, <code>NaN</code>, positive zero, or
                                            negative zero respectively. </p></item><item><p>otherwise, <emph>SV</emph> can be expressed in the form
                                                <code>m × 2^e</code> where the
                                            mantissa <code>m</code> and exponent <code>e</code> are
                                            signed <code>xs:integer</code> values whose value range
                                            is defined in <bibref ref="xmlschema-2"/>, and
                                            <emph>TV</emph> is the <code>xs:double</code> value
                                                <code>m × 2^e</code>. </p></item></ulist></item><item><p>If <emph>ST</emph> is <code>xs:decimal</code> or
                                    <code>xs:integer</code>, then <emph>TV</emph> is <code>xs:double(</code>
                                    <emph>SV</emph>
                                    <code> cast as xs:string)</code> and the conversion is complete.</p></item><item><p>If <emph>ST</emph> is <code>xs:boolean</code>, <emph>SV</emph> is
                                    converted to <code>1.0E0</code> if <emph>SV</emph> is
                                    <code>true</code> and to <code>0.0E0</code> if <emph>SV</emph>
                                    is <code>false</code> and the conversion is complete.</p></item><item><p> If <emph>ST</emph> is <code>xs:untypedAtomic</code>
                                    or <code>xs:string</code>, see 
                                    <specref ref="casting-from-strings"/>.</p><note><p>XSD 1.1 adds the value <code>+INF</code> to the lexical space,
                        as an alternative to <code>INF</code>. XSD 1.1 also adds negative zero
                        to the value space.</p></note></item></ulist><note><p>Implementations <rfc2119>should</rfc2119> return negative zero for <code>xs:double("-0.0E0")</code>.  
                        But because <bibref ref="xmlschema-2"/> does not distinguish between the values positive zero and negative zero.
                        Implementations <rfc2119>may</rfc2119> return positive zero in this case.</p></note></div4><div4 id="casting-to-decimal"><head>Casting to xs:decimal</head><p>When a value of any simple type is cast as <code>xs:decimal</code>, the
                            <code>xs:decimal</code> value <emph>TV</emph> is derived from
                            <emph>ST</emph> and <emph>SV</emph> as follows: </p><ulist><item><p>If <emph>ST</emph> is <code>xs:decimal</code>,
                                    <code>xs:integer</code> or a type derived from them, then
                                    <emph>TV</emph> is <emph>SV</emph>, converted to an
                                    <code>xs:decimal</code> value if need be, and the conversion is complete.</p></item><item><p>If <emph>ST</emph> is <code>xs:float</code> or
                                    <code>xs:double</code>, then <emph>TV</emph> is the
                                    <code>xs:decimal</code> value, within the set of
                                    <code>xs:decimal</code> values that the implementation is
                                    capable of representing, that is numerically closest to
                                    <emph>SV</emph>. If two values are equally close, then the one
                                    that is closest to zero is chosen. If <emph>SV</emph> is too
                                    large to be accommodated as an <code>xs:decimal</code>, (see
                                        <bibref ref="xmlschema-2"/> for <termref def="implementation-defined"/> limits on
                           numeric values) a dynamic error is raised <errorref class="CA" code="0001"/>. If <emph>SV</emph> is one of the special
                                    <code>xs:float</code> or <code>xs:double</code> values
                           <code>NaN</code>, <code>INF</code>, or <code>-INF</code>, a dynamic
                                    error is raised <errorref class="CA" code="0002"/>.</p></item><item><p>If <emph>ST</emph> is <code>xs:boolean</code>, <emph>SV</emph> is
                                    converted to <code>1.0</code> if <emph>SV</emph> is
                                    <code>1</code> or <code>true</code> and to <code>0.0</code> if
                                    <emph>SV</emph> is <code>0</code> or <code>false</code> and the
                                    conversion is complete.</p></item><item><p>If <emph>ST</emph> is <code>xs:untypedAtomic</code>
                                    or <code>xs:string</code>, see 
                                    <specref ref="casting-from-strings"/>.</p></item></ulist></div4><div4 id="casting-to-integer"><head>Casting to xs:integer</head><p>When a value of any simple type is cast as <code>xs:integer</code>, the
                            <code>xs:integer</code> value <emph>TV</emph> is derived from
                            <emph>ST</emph> and <emph>SV</emph> as follows:</p><ulist><item><p>If <emph>ST</emph> is <code>xs:integer</code>, or a type derived
                                    from <code>xs:integer</code>, then <emph>TV</emph> is
                                    <emph>SV</emph>, converted to an <code>xs:integer</code> value
                                    if need be, and the conversion is complete.</p></item><item><p>If <emph>ST</emph> is
                                    <code>xs:decimal</code>, <code>xs:float</code> or
                                    <code>xs:double</code>, then <emph>TV</emph> is <emph>SV</emph>
                                    with the fractional part discarded and the value converted to
                                    <code>xs:integer</code>. Thus, casting <code>3.1456</code>
                                    returns <code>3</code> and <code>-17.89</code> returns
                                    <code>-17</code>. Casting <code>3.124E1</code>
                                    returns <code>31</code>. If <emph>SV</emph> is too large to be
                                    accommodated as an integer, (see <bibref ref="xmlschema-2"/> for
                           <termref def="implementation-defined"/> limits on numeric values) a 
                           dynamic error is
                                    raised <errorref class="CA" code="0003"/>. If <emph>SV</emph> is
                                    one of the special <code>xs:float</code> or
                                    <code>xs:double</code> values <code>NaN</code>,
                           <code>INF</code>, or <code>-INF</code>, a dynamic error is raised
                                        <errorref class="CA" code="0002"/>.</p></item><item><p>If <emph>ST</emph> is <code>xs:boolean</code>, <emph>SV</emph> is
                                    converted to <code>1</code> if <emph>SV</emph> is <code>1</code>
                                    or <code>true</code> and to <code>0</code> if <emph>SV</emph> is
                                    <code>0</code> or <code>false</code> and the conversion is complete.</p></item><item><p>If <emph>ST</emph> is <code>xs:untypedAtomic</code>
                                    or <code>xs:string</code>, see 
                                    <specref ref="casting-from-strings"/>.</p></item></ulist></div4></div3><div3 id="casting-to-durations"><head>Casting to duration types</head><p>When a value of type <code>xs:untypedAtomic</code>, <code>xs:string</code>,
                        a type derived from <code>xs:string</code>,
                        <code>xs:yearMonthDuration</code> or <code>xs:dayTimeDuration</code> is
                        cast as <code>xs:duration</code>, <code>xs:yearMonthDuration</code> or
                        <code>xs:dayTimeDuration</code>, <emph>TV</emph> is derived from
                        <emph>ST</emph> and <emph>SV</emph> as follows:</p><ulist><item><p>If <emph>ST</emph> is the same as <emph>TT</emph>, then
                                <emph>TV</emph> is <emph>SV</emph>. </p></item><item><p>If <emph>ST</emph> is <code>xs:duration</code>, or a type derived
                                from <code>xs:duration</code>, but not
                                <code>xs:dayTimeDuration</code> or a type derived from
                                <code>xs:dayTimeDuration</code>, and <emph>TT</emph> is
                                <code>xs:yearMonthDuration</code>, then <emph>TV</emph> is derived
                                from <emph>SV</emph> by removing the day, hour, minute and second
                                components from <emph>SV</emph>.</p></item><item><p>If <emph>ST</emph> is <code>xs:duration</code>, or a type derived
                                from <code>duration</code>, but not
                                <code>xs:yearMonthDuration</code> or a type derived from
                                <code>xs:yearMonthDuration</code>, and <emph>TT</emph> is
                                <code>xs:dayTimeDuration</code>, then <emph>TV</emph> is derived
                                from <emph>SV</emph> by removing the year and month components from <emph>SV</emph>.</p></item><item><p>If <emph>ST</emph> is <code>xs:yearMonthDuration</code>
                                or <code>xs:dayTimeDuration</code>, and <emph>TT</emph> is
                                <code>xs:duration</code>, then <emph>TV</emph> is derived from
                                <emph>SV</emph> as defined in <specref ref="casting-from-derived-to-parent"/>.</p></item><item><p>If <emph>ST</emph> is <code>xs:yearMonthDuration</code>
                                and <emph>TT</emph> is
                                <code>xs:dayTimeDuration</code>, the cast is permitted and returns a <code>xs:dayTimeDuration</code> with value 0.0 seconds.</p></item><item><p>If <emph>ST</emph> is <code>xs:dayTimeDuration</code>
                                and <emph>TT</emph> is
                                <code>xs:yearMonthDuration</code>, the cast is permitted and returns a <code>xs:yearMonthDuration</code> with value 0 months.</p></item><item><p>If <emph>ST</emph> is <code>xs:untypedAtomic</code>
                                or <code>xs:string</code>, see 
                                    <specref ref="casting-from-strings"/>.</p></item></ulist><p>Note that casting from <code>xs:duration</code> to
                        <code>xs:yearMonthDuration</code> or <code>xs:dayTimeDuration</code> loses
                        information. To avoid this, users can cast the <code>xs:duration</code>
                        value to both an <code>xs:yearMonthDuration</code> and an
                        <code>xs:dayTimeDuration</code> and work with both values.</p></div3><div3 id="casting-to-datetimes"><head>Casting to date and time types</head><p>In several situations, casting to date and time types requires the extraction
                        of a component from <emph>SV</emph> or from the result of
                        <code>fn:current-dateTime</code> and converting it to an
                        <code>xs:string</code>. These conversions must follow certain rules. For
                        example, converting an <code>xs:integer</code> year value requires
                        converting to an <code>xs:string</code> with four or more characters, preceded
                        by a minus sign if the value is negative.</p><p>This document defines four functions to perform these conversions. These
                        functions are for illustrative purposes only and make no recommendations as
                        to style or efficiency.  References to these functions from the following text are not normative.</p><p>The arguments to these functions come from functions defined in this
                        document. Thus, the functions below assume that they are correct and do no
                        range checking on them.</p><eg xml:space="preserve">
declare function eg:convertYearToString($year as xs:integer) as xs:string
{
   let $plusMinus := if ($year &gt;= 0) then "" else "-"
   let $yearString := fn:abs($year) cast as xs:string
   let $length := fn:string-length($yearString)
   return
     if ($length = 1)  then fn:concat($plusMinus, "000", $yearString)
     else
     if ($length = 2)  then fn:concat($plusMinus, "00", $yearString)
       else
       if ($length = 3)  then fn:concat($plusMinus, "0", $yearString)
       else fn:concat($plusMinus, $yearString)
}
                    </eg><eg xml:space="preserve">
declare function eg:convertTo2CharString($value as xs:integer) as xs:string
{
   let $string := $value cast as xs:string
   return 
     if (fn:string-length($string) = 1) then fn:concat("0", $string)
     else $string
}
                    </eg><eg xml:space="preserve">
declare function eg:convertSecondsToString($seconds as xs:decimal) as xs:string
{
   let $string := $seconds cast as xs:string
   let $intLength := fn:string-length(($seconds cast as xs:integer) cast as xs:string)
   return 
     if ($intLength = 1) then fn:concat("0", $string)
     else $string
}
                    </eg><eg xml:space="preserve">
declare function eg:convertTZtoString($tz as xs:dayTimeDuration?) as xs:string
{
   if (empty($tz)) 
     then ""
   else if ($tz eq xs:dayTimeDuration('PT0S'))
     then "Z"
   else 
     let $tzh := fn:hours-from-duration($tz)
     let $tzm := fn:minutes-from-duration($tz)
     let $plusMinus := if ($tzh &gt;= 0) then "+" else "-"
     let $tzhString := eg:convertTo2CharString(fn:abs($tzh))
     let $tzmString := eg:convertTo2CharString(fn:abs($tzm))
     return fn:concat($plusMinus, $tzhString, ":", $tzmString)
}

                    </eg><p>Conversion from 
                  <termref def="dt-cast-primitive-type">primitive types</termref> to date and time types follows the rules below.</p><olist><item><p>When a value of any primitive type is cast as
                                <code>xs:dateTime</code>, the <code>xs:dateTime</code> value
                                <emph>TV</emph> is derived from <emph>ST</emph> and <emph>SV</emph>
                                as follows:</p><ulist><item><p>If <emph>ST</emph> is <code>xs:dateTime</code>, then
                                        <emph>TV</emph> is <emph>SV</emph>. </p></item><item><p>If <emph>ST</emph> is <code>xs:date</code>, then let
                                        <emph>SYR</emph> be <code>eg:convertYearToString( fn:year-from-date(</code>
                                        <emph>SV</emph>
                                        <code>))</code>, let <emph>SMO</emph> be
                                            <code>eg:convertTo2CharString( fn:month-from-date(</code>
                                        <emph>SV</emph>
                                        <code>))</code>, let <emph>SDA</emph> be
                                            <code>eg:convertTo2CharString( fn:day-from-date(</code>
                                        <emph>SV</emph>
                                        <code>))</code> and let <emph>STZ</emph> be
                                            <code>eg:convertTZtoString( fn:timezone-from-date(</code>
                                        <emph>SV</emph>
                                        <code>))</code>; <emph>TV</emph> is <code>xs:dateTime( fn:concat(</code>
                                        <emph>SYR</emph>
                                        <code>, '-', </code>
                                        <emph>SMO</emph>
                                        <code>, '-', </code>
                                        <emph>SDA</emph>
                                        <code>, 'T00:00:00 '</code>, <emph>STZ</emph>
                                        <code>) )</code>. </p></item><item><p> If <emph>ST</emph> is <code>xs:untypedAtomic</code> or
                                        <code>xs:string</code>, see 
                                    <specref ref="casting-from-strings"/>.</p></item></ulist></item><item><p>When a value of any primitive type is cast as <code>xs:time</code>,
                                the <code>xs:time</code> value <emph>TV</emph> is derived from
                                <emph>ST</emph> and <emph>SV</emph> as follows:</p><ulist><item><p>If <emph>ST</emph> is <code>xs:time</code>, then
                                        <emph>TV</emph> is <emph>SV</emph>. </p></item><item><p>If <emph>ST</emph> is <code>xs:dateTime</code>, then
                                        <emph>TV</emph> is <code>xs:time( fn:concat(
                                            eg:convertTo2CharString( fn:hours-from-dateTime(</code>
                                        <emph>SV</emph>
                                        <code>)), ':', eg:convertTo2CharString( fn:minutes-from-dateTime(</code>
                                        <emph>SV</emph>
                                        <code>)), ':', eg:convertSecondsToString( fn:seconds-from-dateTime(</code>
                                        <emph>SV</emph>
                                        <code>)), eg:convertTZtoString( fn:timezone-from-dateTime(</code>
                                        <emph>SV</emph>
                                        <code>)) ))</code>. </p></item><item><p> If <emph>ST</emph> is <code>xs:untypedAtomic</code>
                                        or <code>xs:string</code>, see 
                                    <specref ref="casting-from-strings"/>. </p></item></ulist></item><item><p>When a value of any primitive type is cast as <code>xs:date</code>,
                                the <code>xs:date</code> value <emph>TV</emph> is derived from
                                <emph>ST</emph> and <emph>SV</emph> as follows:</p><ulist><item><p>If <emph>ST</emph> is <code>xs:date</code>, then
                                        <emph>TV</emph> is <emph>SV</emph>. </p></item><item><p>If <emph>ST</emph> is <code>xs:dateTime</code>, then let
                                        <emph>SYR</emph> be <code>eg:convertYearToString( fn:year-from-dateTime(</code>
                                        <emph>SV</emph>
                                        <code>))</code>, let <emph>SMO</emph> be
                                            <code>eg:convertTo2CharString( fn:month-from-dateTime(</code>
                                        <emph>SV</emph>
                                        <code>))</code>, let <emph>SDA</emph> be
                                            <code>eg:convertTo2CharString( fn:day-from-dateTime(</code>
                                        <emph>SV</emph>
                                        <code>))</code> and let <emph>STZ</emph> be <code>eg:convertTZtoString(fn:timezone-from-dateTime(</code>
                                        <emph>SV</emph>
                                        <code>))</code>; <emph>TV</emph> is <code>xs:date( fn:concat(</code>
                                        <emph>SYR</emph>
                                        <code>, '-', </code>
                                        <emph>SMO</emph>
                                        <code>, '-', </code>
                                        <emph>SDA</emph>, <emph>STZ</emph>
                                        <code>) )</code>. </p></item><item><p> If <emph>ST</emph> is <code>xs:untypedAtomic</code>
                                        or <code>xs:string</code>, see 
                                    <specref ref="casting-from-strings"/>. </p></item></ulist></item><item><p>When a value of any primitive type is cast as
                                <code>xs:gYearMonth</code>, the <code>xs:gYearMonth</code> value
                                <emph>TV</emph> is derived from <emph>ST</emph> and <emph>SV</emph>
                                as follows:</p><ulist><item><p>If <emph>ST</emph> is <code>xs:gYearMonth</code>, then
                                        <emph>TV</emph> is <emph>SV</emph>. </p></item><item><p>If <emph>ST</emph> is <code>xs:dateTime</code>, then let
                                        <emph>SYR</emph> be <code>eg:convertYearToString( fn:year-from-dateTime(</code>
                                        <emph>SV</emph>
                                        <code>))</code>, let <emph>SMO</emph> be
                                            <code>eg:convertTo2CharString( fn:month-from-dateTime(</code>
                                        <emph>SV</emph>
                                        <code>))</code> and let <emph>STZ</emph> be
                                            <code>eg:convertTZtoString( fn:timezone-from-dateTime(</code>
                                        <emph>SV</emph>
                                        <code>))</code>; <emph>TV</emph> is <code>xs:gYearMonth( fn:concat(</code>
                                        <emph>SYR</emph>
                                        <code>, '-', </code>
                                        <emph>SMO</emph>, <emph>STZ</emph>
                                        <code>) )</code>. </p></item><item><p>If <emph>ST</emph> is <code>xs:date</code>, then let
                                        <emph>SYR</emph> be <code>eg:convertYearToString( fn:year-from-date(</code>
                                        <emph>SV</emph>
                                        <code>))</code>, let <emph>SMO</emph> be
                                            <code>eg:convertTo2CharString( fn:month-from-date(</code>
                                        <emph>SV</emph>
                                        <code>))</code> and let <emph>STZ</emph> be
                                            <code>eg:convertTZtoString( fn:timezone-from-date(</code>
                                        <emph>SV</emph>
                                        <code>))</code>; <emph>TV</emph> is <code>xs:gYearMonth( fn:concat(</code>
                                        <emph>SYR</emph>
                                        <code>, '-', </code>
                                        <emph>SMO</emph>, <emph>STZ</emph>
                                        <code>) )</code>. </p></item><item><p> If <emph>ST</emph> is <code>xs:untypedAtomic</code>
                                        or <code>xs:string</code>, see 
                                    <specref ref="casting-from-strings"/>. </p></item></ulist></item><item><p>When a value of any primitive type is cast as <code>xs:gYear</code>,
                                the <code>xs:gYear</code> value <emph>TV</emph> is derived from
                                <emph>ST</emph> and <emph>SV</emph> as follows:</p><ulist><item><p>If <emph>ST</emph> is <code>xs:gYear</code>, then
                                        <emph>TV</emph> is <emph>SV</emph>. </p></item><item><p>If <emph>ST</emph> is <code>xs:dateTime</code>, let
                                        <emph>SYR</emph> be <code>eg:convertYearToString( fn:year-from-dateTime(</code>
                                        <emph>SV</emph>
                                        <code>))</code> and let <emph>STZ</emph> be
                                            <code>eg:convertTZtoString( fn:timezone-from-dateTime(</code>
                                        <emph>SV</emph>
                                        <code>))</code>; <emph>TV</emph> is <code>xs:gYear(fn:concat(</code>
                                        <emph>SYR</emph>, <emph>STZ</emph>
                                        <code>))</code>. </p></item><item><p>If <emph>ST</emph> is <code>xs:date</code>, let
                                        <emph>SYR</emph> be <code>eg:convertYearToString( fn:year-from-date(</code>
                                        <emph>SV</emph>
                                        <code>))</code>; and let <emph>STZ</emph> be
                                            <code>eg:convertTZtoString( fn:timezone-from-date(</code>
                                        <emph>SV</emph>
                                        <code>))</code>; <emph>TV</emph> is <code>xs:gYear(fn:concat(</code>
                                        <emph>SYR</emph>, <emph>STZ</emph>
                                        <code>))</code>. </p></item><item><p> If <emph>ST</emph> is <code>xs:untypedAtomic</code>
                                        or <code>xs:string</code>, see 
                                    <specref ref="casting-from-strings"/>. </p></item></ulist></item><item><p>When a value of any primitive type is cast as
                                <code>xs:gMonthDay</code>, the <code>xs:gMonthDay</code> value
                                <emph>TV</emph> is derived from <emph>ST</emph> and <emph>SV</emph>
                                as follows:</p><ulist><item><p>If <emph>ST</emph> is <code>xs:gMonthDay</code>, then
                                        <emph>TV</emph> is <emph>SV</emph>. </p></item><item><p>If <emph>ST</emph> is <code>xs:dateTime</code>, then let
                                        <emph>SMO</emph> be <code>eg:convertTo2CharString( fn:month-from-dateTime(</code>
                                        <emph>SV</emph>
                                        <code>))</code>, let <emph>SDA</emph> be
                                            <code>eg:convertTo2CharString( fn:day-from-dateTime(</code>
                                        <emph>SV</emph>
                                        <code>))</code> and let <emph>STZ</emph> be
                                            <code>eg:convertTZtoString( fn:timezone-from-dateTime(</code>
                                        <emph>SV</emph>
                                        <code>))</code>; <emph>TV</emph> is <code>xs:gYearMonth( fn:concat(</code>
                                        <code> '--', </code>
                                        <emph>SMO</emph>
                                        <code> '-', </code>
                                        <emph>SDA</emph>, <emph>STZ</emph>
                                        <code>) )</code>. </p></item><item><p>If <emph>ST</emph> is <code>xs:date</code>, then let
                                        <emph>SMO</emph> be <code>eg:convertTo2CharString( fn:month-from-date(</code>
                                        <emph>SV</emph>
                                        <code>))</code>, let <emph>SDA</emph> be
                                            <code>eg:convertTo2CharString( fn:day-from-date(</code>
                                        <emph>SV</emph>
                                        <code>))</code> and let <emph>STZ</emph> be
                                            <code>eg:convertTZtoString( fn:timezone-from-date(</code>
                                        <emph>SV</emph>
                                        <code>))</code>; <emph>TV</emph> is <code>xs:gYearMonth( fn:concat(</code>
                                        <code> '--', </code>
                                        <emph>SMO</emph>
                                        <code>, '-', </code>
                                        <emph>SDA</emph>, <emph>STZ</emph>
                                        <code>) )</code>. </p></item><item><p> If <emph>ST</emph> is <code>xs:untypedAtomic</code>
                                        or <code>xs:string</code>, see 
                                    <specref ref="casting-from-strings"/>.</p></item></ulist></item><item><p>When a value of any primitive type is cast as <code>xs:gDay</code>,
                                the <code>xs:gDay</code> value <emph>TV</emph> is derived from
                                <emph>ST</emph> and <emph>SV</emph> as follows:</p><ulist><item><p>If <emph>ST</emph> is <code>xs:gDay</code>, then
                                        <emph>TV</emph> is <emph>SV</emph>. </p></item><item><p>If <emph>ST</emph> is <code>xs:dateTime</code>, then let
                                        <emph>SDA</emph> be <code>eg:convertTo2CharString( fn:day-from-dateTime(</code>
                                        <emph>SV</emph>
                                        <code>))</code> and let <emph>STZ</emph> be
                                            <code>eg:convertTZtoString( fn:timezone-from-dateTime(</code>
                                        <emph>SV</emph>
                                        <code>))</code>; <emph>TV</emph> is <code>xs:gDay(
                                            fn:concat( '---'</code>, <emph>SDA</emph>, <emph>STZ</emph>
                                        <code>))</code>. </p></item><item><p>If <emph>ST</emph> is <code>xs:date</code>, then let
                                        <emph>SDA</emph> be <code>eg:convertTo2CharString( fn:day-from-date(</code>
                                        <emph>SV</emph>
                                        <code>))</code> and let <emph>STZ</emph> be
                                            <code>eg:convertTZtoString( fn:timezone-from-date(</code>
                                        <emph>SV</emph>
                                        <code>))</code>; <emph>TV</emph> is <code>xs:gDay(
                                            fn:concat( '---'</code>, <emph>SDA</emph>, <emph>STZ</emph>
                                        <code>))</code>. </p></item><item><p> If <emph>ST</emph> is <code>xs:untypedAtomic</code>
                                        or <code>xs:string</code>, see 
                                    <specref ref="casting-from-strings"/>. </p></item></ulist></item><item><p>When a value of any primitive type is cast as <code>xs:gMonth</code>,
                                the <code>xs:gMonth</code> value <emph>TV</emph> is derived from
                                <emph>ST</emph> and <emph>SV</emph> as follows:</p><ulist><item><p>If <emph>ST</emph> is <code>xs:gMonth</code>, then
                                        <emph>TV</emph> is <emph>SV</emph>. </p></item><item><p>If <emph>ST</emph> is <code>xs:dateTime</code>, then let
                                        <emph>SMO</emph> be <code>eg:convertTo2CharString( fn:month-from-dateTime(</code>
                                        <emph>SV</emph>
                                        <code>))</code> and let <emph>STZ</emph> be
                                            <code>eg:convertTZtoString( fn:timezone-from-dateTime(</code>
                                        <emph>SV</emph>
                                        <code>))</code>; <emph>TV</emph> is <code>xs:gMonth(
                                            fn:concat( '--' </code>, <emph>SMO</emph>, <emph>STZ</emph>
                                        <code>))</code>. </p></item><item><p>If <emph>ST</emph> is <code>xs:date</code>, then let
                                        <emph>SMO</emph> be <code>eg:convertTo2CharString( fn:month-from-date(</code>
                                        <emph>SV</emph>
                                        <code>))</code> and let <emph>STZ</emph> be
                                            <code>eg:convertTZtoString( fn:timezone-from-date(</code>
                                        <emph>SV</emph>
                                        <code>))</code>; <emph>TV</emph> is <code>xs:gMonth(
                                            fn:concat( '--'</code>, <emph>SMO</emph>, <emph>STZ</emph>
                                        <code>))</code>. </p></item><item><p> If <emph>ST</emph> is <code>xs:untypedAtomic</code>
                                        or <code>xs:string</code>, see 
                                    <specref ref="casting-from-strings"/>.</p></item></ulist></item></olist></div3><div3 id="casting-boolean"><head>Casting to xs:boolean </head><p>When a value of any <termref def="dt-cast-primitive-type">primitive type</termref> is cast as <code>xs:boolean</code>, the
                        <code>xs:boolean</code> value <emph>TV</emph> is derived from
                        <emph>ST</emph> and <emph>SV</emph> as follows:</p><ulist><item><p>If <emph>ST</emph> is <code>xs:boolean</code>, then <emph>TV</emph>
                                is <emph>SV</emph>.</p></item><item><p>If <emph>ST</emph> is <code>xs:float</code>, <code>xs:double</code>,
                                <code>xs:decimal</code> or <code>xs:integer</code> and
                                <emph>SV</emph> is <code>0</code>, <code>+0</code>, <code>-0</code>,
                                <code>0.0</code>, <code>0.0E0</code> or <code>NaN</code>, then
                                <emph>TV</emph> is <code>false</code>. </p></item><item><p>If <emph>ST</emph> is <code>xs:float</code>, <code>xs:double</code>,
                                <code>xs:decimal</code> or <code>xs:integer</code> and
                                <emph>SV</emph> is not one of the above values, then <emph>TV</emph>
                                is <code>true</code>. </p></item><item><p> If <emph>ST</emph> is <code>xs:untypedAtomic</code>
                                or <code>xs:string</code>, see 
                                    <specref ref="casting-from-strings"/>. </p></item></ulist></div3><div3 id="casting-to-binary"><head>Casting to xs:base64Binary and xs:hexBinary</head><p>Values of type <code>xs:base64Binary</code> can be cast as
                        <code>xs:hexBinary</code> and vice versa, since the two types have the same
                        value space. Casting to <code>xs:base64Binary</code> and
                        <code>xs:hexBinary</code> is also supported from the same type and from
                        <code>xs:untypedAtomic</code>, <code>xs:string</code> and subtypes of
                        <code>xs:string</code> using <bibref ref="xmlschema-2"/> semantics.</p></div3><div3 id="casting-to-anyuri"><head>Casting to xs:anyURI</head><p>Casting to <code>xs:anyURI</code> is supported only from the same type,
                        <code>xs:untypedAtomic</code> or <code>xs:string</code>.</p><p>When a value of any <termref def="dt-cast-primitive-type">primitive type</termref> is cast as <code>xs:anyURI</code>, the
                        <code>xs:anyURI</code> value <emph>TV</emph> is derived from the
                        <emph>ST</emph> and <emph>SV</emph> as follows:</p><ulist><item><p>If <emph>ST</emph> is <code>xs:untypedAtomic</code> or <code>xs:string</code> see 
                                    <specref ref="casting-from-strings"/>.
                             </p></item></ulist></div3><div3 id="casting-to-qname-and-notation"><head>Casting to xs:QName and xs:NOTATION</head><p>Casting from <code>xs:string</code> or <code>xs:untypedAtomic</code> to
                  <code>xs:QName</code> or <code>xs:NOTATION</code> is described in 
                  <specref ref="casting-from-strings"/>.</p><p>It is also possible to cast from <code>xs:NOTATION</code> to <code>xs:QName</code>, 
                  or from <code>xs:QName</code> to
                  any type derived by restriction from <code>xs:NOTATION</code>. (Casting to <code>xs:NOTATION</code>
                  itself is not allowed, because <code>xs:NOTATION</code> is an abstract type.) The resulting
                  <code>xs:QName</code> or <code>xs:NOTATION</code> has the same prefix, local name, and namespace URI
                  parts as the supplied value.</p><note><p>See <specref ref="constructor-qname-notation"/> for a discussion of how the combination of
               atomization and casting might not produce the desired effect.</p></note></div3><div3 id="casting-to-ENTITY"><head>Casting to xs:ENTITY</head><p>
                  <bibref ref="xmlschema-2"/> says that <quote>The
                     value space of ENTITY is the set of all strings that match the 
                     NCName production ... and have been
                     declared as an unparsed entity in a document type definition.</quote>
                  However,
                  <bibref ref="xslt-30"/> and <bibref ref="xquery-31"/> do not check that constructed values of type <code>xs:ENTITY</code> match declared unparsed entities.  Thus, this rule is relaxed in this specification and, in casting to <code>xs:ENTITY</code> and types derived from it, no check is made that the values correspond to declared unparsed entities.
               </p></div3></div2><div2 id="casting-from-strings"><head>Casting from xs:string and xs:untypedAtomic</head><p>This section applies when the supplied value <var>SV</var>
               is an instance of <code>xs:string</code> or <code>xs:untypedAtomic</code>,
               including types derived from these by restriction. If the value is
               <code>xs:untypedAtomic</code>, it is treated in exactly the same way as a
               string containing the same sequence of characters.</p><p>The supplied string is mapped to a typed value of the target type as defined in <bibref ref="xmlschema-2"/>. 
               Whitespace normalization is applied as indicated by the
               <code>whiteSpace</code> facet for the datatype. The resulting whitespace-normalized string 
               must be a valid lexical form for the datatype.  The semantics of casting follow the rules of
               XML Schema validation.  For example, <code>"13" cast as xs:unsignedInt</code> returns 
               the <code>xs:unsignedInt</code> typed 
               value <code>13</code>. This could also be written <code>xs:unsignedInt("13")</code>.</p><p>The target type can be any simple type other than an
               abstract type. Specifically, it can be a type whose variety is atomic, union, or list.
               In each case the effect of casting to the target type is the same as constructing an element
               with the supplied value as its content, validating the element using the target type as
               the governing type, and atomizing the element to obtain its typed value.</p><p>When the target type is a derived type that is restricted by a pattern facet, the
               lexical form is first checked against the pattern before further casting
               is attempted (See <specref ref="casting-to-derived-types"/>).  If the lexical form does
               not conform to the pattern, a dynamic 
               error <errorref class="RG" code="0001" type="dynamic"/> is raised.</p><p>For example, consider a user-defined type <code>my:boolean</code> which is derived by
               restriction from <code>xs:boolean</code> and specifies the pattern facet <code>value="0|1"</code>.
               The expression <code>"true" cast as my:boolean</code> would fail with a dynamic
               error <errorref class="RG" code="0001" type="dynamic"/>.</p><p>Facets other than <code>pattern</code> are checked <emph>after</emph> the conversion.
               For example if there is a user-defined datatype called <code>my:height</code> 
               defined as a restriction of <code>xs:integer</code> with the facet <code>&lt;maxInclusive value="84"/&gt;</code>,
               then the expression <code>"100" cast as my:height</code> would fail with a dynamic
               error <errorref class="RG" code="0001" type="dynamic"/>.</p><p>Casting to the types <code>xs:NOTATION</code>, <code>xs:anySimpleType</code>, 
               or <code>xs:anyAtomicType</code> is not permitted because these types are abstract (they have
               no immediate instances).</p><p>Special rules apply when casting to namespace-sensitive types. The types <code>xs:QName</code>
               and <code>xs:NOTATION</code> are namespace-sensitive. Any type derived by restriction from 
               a namespace-sensitive type is itself namespace-sensitive, as is any union type having a
               namespace-sensitive type among its members, and any list type having a namespace-sensitive type
               as its item type. For details, see <specref ref="constructor-qname-notation"/>.</p><note><p>This version of the specification allows casting between <code>xs:QName</code>
               and <code>xs:NOTATION</code> in either direction; this was not permitted in the previous Recommendation. This version also removes
               the rule that only a string literal (rather than a dynamic string) may be cast to an <code>xs:QName</code></p></note><p>When casting to a numeric type:</p><ulist><item><p>If the value is too large or too small to be accurately represented by the implementation, 
                  it is handled as an overflow or underflow as defined in <specref ref="op.numeric"/>.</p></item><item><p>If the target type is <code>xs:float</code> or <code>xs:double</code>, the string <code>-0</code> (and equivalents
                  such as <code>-0.0</code> or <code>-000</code>) <rfc2119>should</rfc2119> be converted to the value negative zero.
                  However, if the implementation is reliant on an implementation of XML Schema 1.0 in which negative zero
                  is not part of the value space for these types, these lexical forms <rfc2119>may</rfc2119> be converted to positive zero.</p></item></ulist><p>
               In casting to <code>xs:decimal</code> or to a type derived from <code>xs:decimal</code>, 
               if the value is not too large or too small but nevertheless cannot be represented accurately 
               with the number of decimal digits available to the implementation, the implementation may round 
               to the nearest representable value or may raise a dynamic error <errorref class="CA" code="0006" type="dynamic"/>. 
               The choice of rounding algorithm and the choice between rounding and error behavior and is 
               <termref def="implementation-defined"/>.
            </p><p>In casting to <code>xs:date</code>, <code>xs:dateTime</code>, <code>xs:gYear</code>, 
               or <code>xs:gYearMonth</code> 
               (or types derived from these), if the value is too large or too 
               small to be represented by the implementation, a dynamic error 
               <errorref class="DT" code="0001" type="dynamic"/> is raised.</p><p>In casting to a duration value, if the value is too large or too small to be represented by the 
               implementation, a dynamic error <errorref class="DT" code="0002" type="dynamic"/> is raised.</p><p> For <code>xs:anyURI</code>, the extent to which an implementation validates the
               lexical form of <code>xs:anyURI</code> is <termref def="implementation-dependent"/>.</p><p>If the cast fails for any other reason, a dynamic error
               <errorref class="RG" code="0001" type="dynamic"/> is raised.</p></div2><div2 id="casting-non-primitive-types"><head>Casting involving non-primitive types</head><p>Casting from <code>xs:string</code> and <code>xs:untypedAtomic</code> to any other type
            (primitive or non-primitive) has been described in <specref ref="casting-from-strings"/>.
            This section defines how other casts to non-primitive types operate, including casting
            to types derived by restriction, to union types, and to list types.</p><note><p>A <term>non-primitive type</term> here means any type that is not a
                  <termref def="dt-cast-primitive-type">primitive type</termref> according
               to the extended definition used in <specref ref="casting"/>.</p></note><div3 id="casting-to-derived-types" diff="chg" at="D"><head>Casting to derived types</head><p>Casting a value to a derived type can be separated into four cases. In these rules:</p><ulist><item><p>The types <code>xs:untypedAtomic</code>, <code>xs:integer</code>, <code>xs:yearMonthDuration</code>,
               and <code>xs:dayTimeDuration</code> are treated as primitive types (alongside the 19 primitive types defined in XSD).</p></item><item><p>For any atomic type <var>T</var>, let <var>P(T)</var> denote the most specific primitive type
               such that <code>itemType-subtype(T, P(T))</code> is true.</p></item></ulist><p>The rules are then:</p><olist><item><p>When <var>ST</var> is the same type as <var>TT</var>: this case always succeeds, returning <var>SV</var> unchanged.</p></item><item><p>When <code>itemType-subtype(ST, TT)</code> is true: This case is described in <specref ref="casting-from-derived-to-parent"/>. </p></item><item><p>When <var>P(ST)</var> is the same type as <var>P(TT)</var>: This case is described in <specref ref="casting-within-branch"/>.</p></item><item><p>Otherwise (<var>P(ST)</var> is not the same type as <var>P(TT)</var>): This case is described in <specref ref="casting-across-hierarchy"/>.</p></item></olist></div3><div3 id="casting-from-derived-to-parent"><head>Casting from derived types to parent types</head><p>
               It is always possible to cast an atomic value <var>A</var> to a type <var>T</var>
               if the relation <code>A instance of T</code> is true, provided that <var>T</var>
               is not an abstract type.
            </p><p>For example, it is
              possible to cast an <code>xs:unsignedShort</code> to an
              <code>xs:unsignedInt</code>, to an <code>xs:integer</code>, to an
              <code>xs:decimal</code>, or to a union type
              whose member types are <code>xs:integer</code> and <code>xs:double</code>.</p><p>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.</p><p>For the expression <code>A instance of T</code> to be true, <var>T</var> must be
               either an atomic type, or a union type that has no constraining facets. It cannot
               be a list type, nor a union type derived by restriction from another union type, nor
               a union type that has a list type among its member types.</p><p>The
            result will have the same value as the original, but will have a new type annotation:</p><ulist><item><p>If <var>T</var> is an atomic type, then the type annotation of the result is <code>T</code>.
               </p></item><item><p>If <var>T</var> is a union type, then the type of the result is an atomic type <code>M</code>
                  such that <var>M</var> is one of the atomic types in the transitive membership of
                  the union type <var>T</var> and <code>A instance of M</code> is true; if there is more
                  than one type <var>M</var> that satisfies these conditions (which could happen, for example,
                  if <var>T</var> is the union of two overlapping types such as <code>xs:int</code>
                  and <code>xs:positiveInteger</code>) then the first one is used, taking the member types
                  in the order in which they appear within the definition of the union type.</p></item></ulist></div3><div3 id="casting-within-branch"><head>Casting within a branch of the type hierarchy</head><p>It is possible to cast an <emph>SV</emph> to a <emph>TT</emph> if the type of the
                    <emph>SV</emph> and the <emph>TT</emph> type are both derived by restriction
               (directly or indirectly) from the same <termref def="dt-cast-primitive-type">primitive type</termref>, provided that the
                    supplied value conforms to the constraints implied by the facets of the target
                    type.  This includes the case where the target type is derived from the type of the supplied value,
                    as well as the case where the type of the supplied value is derived from the target type.  For example, an instance of <code>xs:byte</code> can be cast as
                    <code>xs:unsignedShort</code>, provided the value is not negative.  </p><p>If the value does not conform to the facets defined for the target type, then a dynamic
                    error is raised <errorref class="RG" code="0001"/>. See <bibref ref="xmlschema-2"/>.
                    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 for the source type (or the result
                    of casting the value to an <code>xs:string</code>, in the case of types that have no canonical
                    lexical representation defined for them).</p><p>Note that this will cause casts to fail if the pattern excludes the canonical
                    lexical representation of the source type. For example, if the type
                    <code>my:distance</code> is defined as a restriction of <code>xs:decimal</code>
                    with a pattern that requires two digits after the decimal point, casting of an
                    <code>xs:integer</code> to <code>my:distance</code> will always fail, because
                    the canonical representation of an <code>xs:integer</code> does not conform to
                    this pattern.</p><p>In some cases, casting from a parent type to a derived type requires special
                    rules. See <specref ref="casting-to-durations"/> for rules regarding casting to
                    <code>xs:yearMonthDuration</code> and <code>xs:dayTimeDuration</code>.  See <specref ref="casting-to-ENTITY"/>, below, for casting to <code>xs:ENTITY</code> and types derived from it.</p></div3><div3 id="casting-across-hierarchy"><head>Casting across the type hierarchy</head><p>When the <emph>ST</emph> and the <emph>TT</emph> are derived, directly or
               indirectly, from different <termref def="dt-cast-primitive-type">primitive types</termref>, this is called casting across the
                    type hierarchy. Casting across the type hierarchy is logically equivalent to
                    three separate steps performed in order. Errors can occur in either of the
                    latter two steps.</p><olist><item><p>Cast the <emph>SV</emph>, up the hierarchy, to the <termref def="dt-cast-primitive-type">primitive type</termref> of the
                            source, as described in <specref ref="casting-from-derived-to-parent"/>.</p><olist><item><p>
If <emph>SV</emph> is an instance of <code>xs:string</code> or <code>xs:untypedAtomic</code>, check its value against the 
                           pattern facet of <emph>TT</emph>, and raise a dynamic error <errorref class="RG" code="0001"/> if the check fails.</p></item></olist></item><item><p>Cast the value to the <termref def="dt-cast-primitive-type">primitive type</termref> of <emph>TT</emph>, as described in
                                <specref ref="casting-from-primitive-to-primitive"/>.</p><ulist><item><p>If <emph>TT</emph> is derived from <code>xs:NOTATION</code>, assume for the
purposes of this rule that casting to <code>xs:NOTATION</code> succeeds.
</p></item></ulist></item><item><p>Cast the value down to the <emph>TT</emph>, as described in <specref ref="casting-within-branch"/>
                        </p></item></olist></div3><div3 id="casting-to-union"><head>Casting to union types</head><p>If the target type of a cast expression (or a constructor function) is a type with variety union, the
               supplied value must be one of the following:</p><olist><item><p>A value of type <code>xs:string</code> or <code>xs:untypedAtomic</code>.
               This case follows the general rules for casting from strings, and has already been
               described in <specref ref="casting-from-strings"/>.</p><p>If the union type has a pattern facet, the pattern is tested against the supplied
                     value after whitespace normalization, using the <code>whiteSpace</code>
                     normalization rules of the member datatype against which validation succeeds.</p></item><item><p>A value that is an instance of one of the atomic types in the transitive
               membership of the union type, and of the union type itself. This case has already been described in
               <specref ref="casting-from-derived-to-parent"/></p><p>This situation only applies when the value is an instance of the union type,
                  which means it will never apply when the union is derived by facet-based restriction
                  from another union type.</p></item><item><p>A value that is castable to one or more of the atomic types in the transitive membership
                  of the union type (in the sense that the <code>castable as</code> operator returns true).</p><p>In this case the supplied value is cast to each atomic type in the transitive membership
                     of the union type in turn (in the order in which the member types appear in the declaration)
                     until one of these casts is successful; if none of them is successful, a dynamic error occurs
                     <errorref class="RG" code="0001"/>. If the union type has constraining facets then the
                     resulting value must satisfy these facets, otherwise a dynamic error occurs 
                     <errorref class="RG" code="0001"/>.</p><p>If the union type has a pattern facet, the pattern is tested against the canonical
                  representation of the result value.</p><p>Only the atomic types in the transitive membership of the union type are considered. The
                  union type may have list types in its transitive membership, but (unless the supplied value
                  is of type <code>xs:string</code> or <code>xs:untypedAtomic</code>, in which case the
                  rules in <specref ref="casting-from-strings"/> apply), any list types in the membership
                  are effectively ignored.</p></item></olist><p>If more than one of these conditions applies, then the casting is done according to the rules
            for the first condition that applies.</p><p>If none of these conditions applies, the cast fails with a dynamic error
            <errorref class="RG" code="0001"/>.</p><p>Example: consider a type <var>U</var> whose member types are <code>xs:integer</code>
               and <code>xs:date</code>.</p><ulist><item><p>The expression <code>"123" cast as U</code> returns the
                  <code>xs:integer</code> value <code>123</code>.</p></item><item><p>The expression <code>current-date() cast as U</code> returns
                     the current date as an instance of <code>xs:date</code>.</p></item><item><p>The expression <code>23.1 cast as U</code> returns the <code>xs:integer</code>
                  value <code>23</code>.</p></item></ulist><p>Example: consider a type <var>V</var> whose member types are <code>xs:short</code>
               and <code>xs:negativeInteger</code>.</p><ulist><item><p>The expression <code>"-123" cast as V</code> returns the
                  <code>xs:short</code> value <code>-123</code>.</p></item><item><p>The expression <code>"-100000" cast as V</code> returns the
                  <code>xs:negativeInteger</code> value <code>-100000</code>.</p></item><item><p>The expression <code>93.7 cast as V</code> returns the
                  <code>xs:short</code> value <code>93</code>.</p></item><item><p>The expression <code>"93.7" cast as V</code> raises
                  a dynamic error <errorref class="RG" code="0001"/> on the grounds that the string
               <code>"93.7"</code> is not in the lexical space of the union type.</p></item></ulist><p>Example: consider a type <var>W</var> that is derived from the above type <var>V</var>
               by restriction, with a pattern facet of <code>-?\d\d</code>.</p><ulist><item><p>The expression <code>"12" cast as V</code> returns the
                     <code>xs:short</code> value <code>12</code>.</p></item><item><p>The expression <code>"123" cast as V</code> raises
                     an dynamic error <errorref class="RG" code="0001"/> on the grounds that the string
                     <code>"123"</code> does not match the pattern facet.</p></item></ulist></div3><div3 id="casting-to-list"><head>Casting to list types</head><p>If the target type of a cast expression (or a constructor function) is a
            type with variety <code>list</code>, the supplied value must be of type <code>xs:string</code> or
            <code>xs:untypedAtomic</code>. The rules follow the general principle for
            all casts from <code>xs:string</code> outlined in <specref ref="casting-from-strings"/>.</p><p>The semantics of the operation are consistent with validation: that is,
            the effect of casting a string <var>S</var> to a list type <var>L</var> is the same as
            constructing an element or attribute node whose string value is <var>S</var>,
            validating it using <var>L</var> as the governing type, and atomizing the resulting
            node. The result will always be either failure, or a sequence of zero or
            more atomic values each of which is an instance of the item type of <var>L</var>
            (or if the item type of <var>L</var> is a union type, an instance of one of the
            atomic types in its transitive membership).</p><p>If the item type of the list type is namespace-sensitive, then the 
               namespace bindings in the static context will be used to
            resolve any namespace prefix, in the same way as when the target type is
            <code>xs:QName</code>.</p><p>If the list type has a <code>pattern</code> facet, the pattern must match
            the supplied value after collapsing whitespace (an operation equivalent to the
            use of the <code>fn:normalize-space</code> function).</p><p>For example, the expression <code>cast "A B C D" as xs:NMTOKENS</code>
            produces a sequence of four <code>xs:NMTOKEN</code> values, 
            <code>("A", "B", "C", "D")</code>.</p><p>For example, given a user-defined type <code>my:coordinates</code> defined
            as a list of <code>xs:integer</code> with the facet <code>&lt;xs:length value="2"/&gt;</code>,
            the expression <code>my:coordinates("2 -1")</code> will return a sequence of two
            xs:integer values <code>(2, -1)</code>, while the expression <code>my:coordinates("1 2 3")</code>
            will result in a dynamic error because the length of the list does not conform to the
            <code>length</code> facet. The expression <code>my:coordinates("1.0 3.0")</code>
            will also fail because the strings <code>1.0</code> and <code>3.0</code> 
               are not in the lexical space of <code>xs:integer</code>.</p></div3></div2></div1></body><back><div1 id="biblio"><head>References</head><div2 id="normative-biblio"><head>Normative references</head><blist><bibl xmlns:xlink="http://www.w3.org/1999/xlink" id="charmod" key="Character Model for the World Wide Web 1.0: Fundamentals" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">
                  <titleref href="https://www.w3.org/TR/charmod/" xlink:type="simple" xlink:show="new" xlink:actuate="onRequest">Character Model for the World Wide Web 1.0:
                     Fundamentals</titleref>,
                  Martin J. Dürst, François Yergeau, <emph>et. al.</emph>, Editors.
                  World Wide Web Consortium,
                  15 February 2015.
                  This version is http://www.w3.org/TR/2005/REC-charmod-20050215/.
                  The <loc href="https://www.w3.org/TR/charmod/" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">latest version</loc>
                  is available at https://www.w3.org/TR/charmod/.</bibl><bibl xmlns:xlink="http://www.w3.org/1999/xlink" id="html5" key="HTML5: A vocabulary and associated APIs for HTML and XHTML" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">
                  <titleref href="http://www.w3.org/TR/html5/" xlink:type="simple" xlink:show="new" xlink:actuate="onRequest">HTML5: A vocabulary and associated APIs for HTML and XHTML</titleref>,
                  Ian Hickson, Robin Berjon, <emph>et. al.</emph>, Editors.
                  World Wide Web Consortium,
                  28 October 2014.
                  This version is http://www.w3.org/TR/2014/REC-html5-20141028/.
                  The <loc href="https://www.w3.org/TR/html5/" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">latest version</loc>
                  is available at https://www.w3.org/TR/html5/.</bibl><bibl xmlns:xlink="http://www.w3.org/1999/xlink" id="olson" key="IANA Timezone Database" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">
                  The <emph>tz</emph> timezone database, available at 
                  <loc href="http://www.iana.org/time-zones" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">http://www.iana.org/time-zones</loc>.
                  It is <termref def="implementation-defined"/> which version of the database is used.
               </bibl><bibl xmlns:xlink="http://www.w3.org/1999/xlink" id="ieee754-2008" key="IEEE 754-2008" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">IEEE. <emph>IEEE Standard for
                  Floating-Point Arithmetic.</emph>
               </bibl><bibl xmlns:xlink="http://www.w3.org/1999/xlink" id="ISO3166" key="ISO 3166-1" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">ISO (International Organization for Standardization)
					<emph>Codes for the representation of names of countries
					 and their subdivisions - Part 1: Country codes</emph> ISO 3166-1:2013.
                    </bibl><bibl xmlns:xlink="http://www.w3.org/1999/xlink" id="ISO8601" key="ISO 8601" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">ISO (International Organization for
                  Standardization). <emph>Representations of dates and times. Third edition,
                     2004-12-01.</emph> ISO 8601:2004(E). Available from:
                  <loc href="http://www.iso.org/" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">http://www.iso.org/"</loc>.
               </bibl><bibl xmlns:xlink="http://www.w3.org/1999/xlink" id="ISO10967" key="ISO 10967" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">ISO (International Organization
for Standardization). <emph>ISO/IEC 10967-1:2012, Information
technology—Language Independent Arithmetic—Part 1:
Integer and floating point arithmetic</emph> [Geneva]: International
Organization for Standardization, 2012. Available from: <loc href="http://www.iso.org/" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">http://www.iso.org/</loc>.
               </bibl><bibl xmlns:xlink="http://www.w3.org/1999/xlink" id="ISO15924" key="ISO 15924" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">ISO (International Organization for Standardization) 
                  <emph>Information and documentation — Codes
                     for the representation of names of scripts</emph> ISO 15924:2004, 
                  January 2004.</bibl><bibl xmlns:xlink="http://www.w3.org/1999/xlink" id="ISO15924_register" key="ISO 15924 Register" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">Unicode Consortium. 
                  <emph>Codes for the representation of names of scripts — Alphabetical list of four-letter script codes.</emph>
                  See <loc href="http://www.unicode.org/iso15924/iso15924-codes.html" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest"/>.
                  Retrieved February 2013; continually updated.</bibl><bibl xmlns:xlink="http://www.w3.org/1999/xlink" id="LEIRI" key="Legacy extended IRIs for XML resource identification" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest"><emph>Legacy extended IRIs for XML resource identification</emph>.
                  Henry S. Thomson, Richard Tobin, and Norman Walsh (eds), World Wide Web Consortium. 3 November 2008. Available at
                  <loc href="http://www.w3.org/TR/leiri/" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">http://www.w3.org/TR/leiri/</loc>.
               </bibl><bibl xmlns:xlink="http://www.w3.org/1999/xlink" id="rfc2376" key="RFC 2376" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">IETF. <emph>RFC 2376: XML Media Types. </emph> Available at:
                  <loc href="http://www.ietf.org/rfc/rfc2376.txt" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">http://www.ietf.org/rfc/rfc2376.txt</loc>.
               </bibl><bibl xmlns:xlink="http://www.w3.org/1999/xlink" id="rfc3986" key="RFC 3986" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">IETF. <emph>RFC 3986: Uniform
                  Resource Identifiers (URI): Generic Syntax. </emph> Available at:
                  <loc href="http://www.ietf.org/rfc/rfc3986.txt" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">http://www.ietf.org/rfc/rfc3986.txt</loc>.
               </bibl><bibl xmlns:xlink="http://www.w3.org/1999/xlink" id="rfc3987" key="RFC 3987" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">IETF. <emph>RFC 3987:
                  Internationalized Resource Identifiers (IRIs).</emph> Available at:
                  <loc href="http://www.ietf.org/rfc/rfc3987.txt" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">http://www.ietf.org/rfc/rfc3987.txt</loc>.
               </bibl><bibl xmlns:xlink="http://www.w3.org/1999/xlink" id="rfc7159" key="RFC 7159" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">IETF. <emph>RFC 7159: The Javascript Object Notation (JSON) Data Interchange Format</emph> Available at:
                  <loc href="http://www.rfc-editor.org/rfc/rfc7159.txt" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">http://www.rfc-editor.org/rfc/rfc7159.txt</loc>.
               </bibl><bibl xmlns:xlink="http://www.w3.org/1999/xlink" id="rfc7303" key="RFC 7303" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">H. Thompson and C. Lilley. <emph>XML Media Types</emph>.
                  IETF RFC 7303. See <loc href="http://www.ietf.org/rfc/rfc7303.txt" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">http://www.ietf.org/rfc/rfc7303.txt</loc>.</bibl><bibl xmlns:xlink="http://www.w3.org/1999/xlink" id="UNICODE-TR15" key="UAX #15" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest"><emph>Unicode Standard Annex #15: Unicode Normalization
                     Forms</emph>. 
                  Ed. Mark Davis and Ken Whistler, Unicode Consortium.
                  The current version is 9.0.0, dated 2016-02-24.
                  As with <bibref ref="Unicode"/>, the version to be used is <termref def="implementation-defined"/>.
                  Available at:
                  <loc href="http://www.unicode.org/reports/tr15/" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">http://www.unicode.org/reports/tr15/</loc>.                 
               </bibl><bibl xmlns:xlink="http://www.w3.org/1999/xlink" id="Unicode" key="The Unicode Standard" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">
The Unicode Consortium, Reading, MA, Addison-Wesley, 2016. <emph>The Unicode Standard</emph>
as updated from time to time by the publication of new versions. See 
<loc href="http://www.unicode.org/standard/versions/" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">http://www.unicode.org/standard/versions/</loc>
for the latest version and additional information on versions of the standard and of the Unicode Character Database. 
The version of Unicode to be used is <termref def="implementation-defined"/>,
but implementations are recommended to use the latest Unicode version;
currently, Version 9.0.0.
</bibl><bibl xmlns:xlink="http://www.w3.org/1999/xlink" id="UNICODE-TR10" key="UTS #10" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest"><emph>Unicode
                  Technical Standard #10: Unicode Collation Algorithm</emph>. 
                  Ed. Mark Davis and Ken Whistler, Unicode Consortium. The current version is 9.0.0, dated 2016-05-18.
                  As with <bibref ref="Unicode"/>, the version to be used is <termref def="implementation-defined"/>. 
                  Available at: <loc href="http://www.unicode.org/reports/tr10/" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest"/>.</bibl><bibl xmlns:xlink="http://www.w3.org/1999/xlink" id="UNICODE-TR35" key="UTS #35" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest"><emph>Unicode
                  Technical Standard #35: Unicode Locale Data Markup Language</emph>. 
                  Ed Mark Davis <emph>et al</emph>, Unicode Consortium. The current version is 29, dated 2016-03-15.
                  As with <bibref ref="Unicode"/>, the version to be used is <termref def="implementation-defined"/>.
                  Available at: <loc href="http://www.unicode.org/reports/tr35/" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest"/>.</bibl><bibl xmlns:xlink="http://www.w3.org/1999/xlink" id="xml" key="Extensible Markup Language (XML) 1.0 (Fifth Edition)" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest"/><bibl xmlns:xlink="http://www.w3.org/1999/xlink" id="xml11" key="Extensible Markup Language (XML) 1.1 Recommendation" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest"/><bibl xmlns:xlink="http://www.w3.org/1999/xlink" id="xpath" key="XML Path Language (XPath) Version 1.0" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest"/><bibl xmlns:xlink="http://www.w3.org/1999/xlink" id="xpath-31" key="XML Path Language (XPath) 3.1" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest"/><bibl xmlns:xlink="http://www.w3.org/1999/xlink" id="xslt10" key="XSL Transformations (XSLT) Version 1.0" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest"/><bibl xmlns:xlink="http://www.w3.org/1999/xlink" id="xslt20" key="XSL Transformations (XSLT) Version 2.0" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest"/><bibl xmlns:xlink="http://www.w3.org/1999/xlink" id="xslt-30" key="XSL Transformations (XSLT) Version 3.0" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest"/><bibl xmlns:xlink="http://www.w3.org/1999/xlink" id="xpath-datamodel-30" key="XQuery and XPath Data Model (XDM) 3.0" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest"/><bibl xmlns:xlink="http://www.w3.org/1999/xlink" id="xpath-datamodel-31" key="XQuery and XPath Data Model (XDM) 3.1" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest"/><bibl xmlns:xlink="http://www.w3.org/1999/xlink" id="xslt-xquery-serialization-31" key="XSLT and XQuery Serialization 3.1" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest"/><bibl xmlns:xlink="http://www.w3.org/1999/xlink" id="xquery-semantics" key="XQuery 1.0 and XPath 2.0 Formal Semantics" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest"/><bibl xmlns:xlink="http://www.w3.org/1999/xlink" id="xquery-31" key="XQuery 3.1: An XML Query Language" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest"/><bibl xmlns:xlink="http://www.w3.org/1999/xlink" id="xinclude" key="XML Inclusions (XInclude) Version 1.0 (Second Edition)" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest"/><bibl xmlns:xlink="http://www.w3.org/1999/xlink" id="xmlschema-2" key="XML Schema Part 2: Datatypes Second Edition" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest"> XML Schema
                        Part 2: Datatypes Second Edition, Oct. 28 2004. Available at: 
						<loc href="http://www.w3.org/TR/xmlschema-2/" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">http://www.w3.org/TR/xmlschema-2/</loc>
               </bibl><bibl xmlns:xlink="http://www.w3.org/1999/xlink" id="xmlschema11-2" key="Schema 1.1 Part 2" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest"/><bibl xmlns:xlink="http://www.w3.org/1999/xlink" id="xml-names" key="Namespaces in XML" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest"/></blist></div2><div2 id="non-normative-biblio"><head>Non-normative references</head><blist><bibl xmlns:xlink="http://www.w3.org/1999/xlink" id="CALCALC" key="Calendrical Calculations" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">Edward M. Reingold and Nachum Dershowitz.
<emph>Calendrical Calculations Millennium edition (2nd Edition)</emph>. Cambridge University Press, 
ISBN 0 521 77752 6.</bibl><bibl xmlns:xlink="http://www.w3.org/1999/xlink" id="CLDR" key="Unicode CLDR" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">CLDR - Unicode Common Locale Data Repository. Available at:
                  <loc href="http://cldr.unicode.org" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">http://cldr.unicode.org</loc>.</bibl><bibl xmlns:xlink="http://www.w3.org/1999/xlink" id="charmod-normalization" key="Character Model for the World Wide Web 1.0: Normalization" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">Character Model for the World Wide Web
                  1.0: Normalization, Last Call Working Draft. Available at:
                  <loc href="http://www.w3.org/TR/2004/WD-charmod-norm-20040225/" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">http://www.w3.org/TR/2004/WD-charmod-norm-20040225/</loc>.
               </bibl><bibl xmlns:xlink="http://www.w3.org/1999/xlink" id="expath" key="EXPath" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">EXPath: Collaboratively Defining Open Standards for Portable XPath Extensions.
               <loc href="http://expath.org/" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">http://expath.org/</loc>.</bibl><bibl xmlns:xlink="http://www.w3.org/1999/xlink" id="exquery" key="EXQuery" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">EXQuery: Collaboratively Defining Open Standards for Portable XQuery Extensions.
                  <loc href="http://exquery.org/" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">http://exquery.org/</loc>.</bibl><bibl xmlns:xlink="http://www.w3.org/1999/xlink" id="exslt" key="EXSLT" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">EXSLT: A Community Initiative to Provide Extensions to XSLT.
                  <loc href="http://exslt.org/" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">http://exslt.org/</loc>.</bibl><bibl xmlns:xlink="http://www.w3.org/1999/xlink" id="functx" key="FunctX" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">FunctX Functions. 
                  <loc href="http://www.functx.com/" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">http://www.functx.com/</loc>.</bibl><bibl xmlns:xlink="http://www.w3.org/1999/xlink" id="HTML40" key="HTML 4.0" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">HTML 4.01 Recommendation, 24 December
1999. Available at:
<loc href="http://www.w3.org/TR/REC-html40/" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">http://www.w3.org/TR/REC-html40/</loc>.
               </bibl><bibl xmlns:xlink="http://www.w3.org/1999/xlink" id="ICU" key="ICU" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">ICU - International Components for Unicode. Available at <loc href="http://site.icu-project.org" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">http://site.icu-project.org</loc>.
               </bibl><bibl xmlns:xlink="http://www.w3.org/1999/xlink" id="POSIX.1-2008" key="POSIX.1-2008" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">
                  <emph>The Open Group Base Specifications Issue 7 (IEEE Std 1003.1-2008)</emph>.
                  Available at: <loc href="http://pubs.opengroup.org/onlinepubs/9699919799/" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">http://pubs.opengroup.org/onlinepubs/9699919799/</loc>.
               </bibl><bibl xmlns:xlink="http://www.w3.org/1999/xlink" id="rfc822" key="RFC 822" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">IETF. <emph>RFC 822: Standard for the Format of ARPA Internet Text Messages. </emph> Available at:
                  <loc href="http://www.ietf.org/rfc/rfc822.txt" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">http://www.ietf.org/rfc/rfc822.txt</loc>.
               </bibl><bibl xmlns:xlink="http://www.w3.org/1999/xlink" id="rfc850" key="RFC 850" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">IETF. <emph>RFC 850: Standard for Interchange of USENET Messages. </emph> Available at:
                  <loc href="http://www.ietf.org/rfc/rfc850.txt" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">http://www.ietf.org/rfc/rfc850.txt</loc>.
               </bibl><bibl xmlns:xlink="http://www.w3.org/1999/xlink" id="rfc1036" key="RFC 1036" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">IETF. <emph>RFC 1036: Standard for Interchange of USENET Messages. </emph> Available at:
                  <loc href="http://www.ietf.org/rfc/rfc1036.txt" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">http://www.ietf.org/rfc/rfc1036.txt</loc>.
               </bibl><bibl xmlns:xlink="http://www.w3.org/1999/xlink" id="rfc1123" key="RFC 1123" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">IETF. <emph>RFC 1123: Requirements for Internet Hosts -- Application and Support. </emph> Available at:
                  <loc href="http://www.ietf.org/rfc/rfc1123.txt" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">http://www.ietf.org/rfc/rfc1123.txt</loc>.
               </bibl><bibl xmlns:xlink="http://www.w3.org/1999/xlink" id="rfc2616" key="RFC 2616" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">IETF. <emph>RFC 2616: Hypertext Transfer Protocol -- HTTP/1.1. </emph> Available at:
                  <loc href="http://www.ietf.org/rfc/rfc2616.txt" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">http://www.ietf.org/rfc/rfc2616.txt</loc>.
               </bibl><bibl xmlns:xlink="http://www.w3.org/1999/xlink" id="rfc3339" key="RFC 3339" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">IETF. <emph>RFC 3339: Date and Time on the Internet: Timestamps. </emph> Available at:
                  <loc href="http://www.ietf.org/rfc/rfc3339.txt" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">http://www.ietf.org/rfc/rfc3339.txt</loc>.
               </bibl><bibl xmlns:xlink="http://www.w3.org/1999/xlink" id="UNICODE-TR18" key="UTS #18" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest"><emph>Unicode
                  Technical Standard #18: Unicode Regular Expressions</emph>. 
                  Ed. Mark Davis and Andy Heniger, Unicode Consortium. The current version is 17, dated 2013-11-19. Available at:
                  <loc href="http://www.unicode.org/reports/tr18/" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">http://www.unicode.org/reports/tr18/</loc>.
               </bibl><bibl xmlns:xlink="http://www.w3.org/1999/xlink" id="Working-With-Timezones" key="Working With Timezones" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">World Wide Web Consortium Working Group Note. 
					 <emph>Working With Timezones, October 13, 2005.</emph> Available at:
<loc href="http://www.w3.org/TR/2005/NOTE-timezone-20051013/" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">http://www.w3.org/TR/2005/NOTE-timezone-20051013/</loc>.
               </bibl></blist></div2></div1><div1 id="error-summary"><head>Error summary</head><p>The error text provided with these errors is non-normative.</p><error-list><error class="ER" code="0000" label="Unidentified error." type="dynamic"><p>Error code used by <code>fn:error</code> when no other error code is provided.</p></error><error class="AP" code="0001" label="Wrong number of arguments." type="dynamic"><p>Raised when <code>fn:apply</code> is called and the arity of the supplied function is not
                  the same as the number of members in the supplied array.</p></error><error class="AR" code="0001" label="Division by zero." type="dynamic"><p>This error is raised whenever an attempt is made to divide by zero.</p></error><error class="AR" code="0002" label="Numeric operation overflow/underflow." type="dynamic"><p>This error is raised whenever numeric operations result in an overflow or underflow.</p></error><error class="AY" code="0001" label="Array index out of bounds." type="dynamic"><p diff="add" at="A">This error is raised when an integer used to select a member of an array is outside the range of values for that array.</p></error><error class="AY" code="0002" label="Negative array length." type="dynamic"><p diff="add" at="A">This error is raised when the <code>$length</code> argument to <code>array:subarray</code> is negative.</p></error><error class="CA" code="0001" label="Input value too large for decimal." type="dynamic"><p>Raised when casting to <code>xs:decimal</code> if the supplied value exceeds the
               implementation-defined limits for the datatype.</p></error><error class="CA" code="0002" label="Invalid lexical value." type="dynamic"><p>Raised by <code>fn:resolve-QName</code> and <code>fn:QName</code> when a supplied value does not have the lexical
               form of a QName or URI respectively; and when casting to decimal, if the supplied value is NaN or Infinity.</p></error><error class="CA" code="0003" label="Input value too large for integer." type="dynamic"><p>Raised when casting to <code>xs:integer</code> if the supplied value exceeds the
                  implementation-defined limits for the datatype.</p></error><error class="CA" code="0005" label="NaN supplied as float/double value." type="dynamic"><p>Raised when multiplying or dividing a duration by a number, if the number supplied is NaN.</p></error><error class="CA" code="0006" label="String to be cast to decimal has too many digits of precision." type="dynamic"><p>Raised when casting a string to <code>xs:decimal</code> if the string has more digits of precision
               than the implementation can represent (the implementation also has the option of rounding).</p></error><error class="CH" code="0001" label="Codepoint not valid." type="dynamic"><p>Raised by <code>fn:codepoints-to-string</code> if the input contains an integer that is not the codepoint
               of a valid XML character.</p></error><error class="CH" code="0002" label="Unsupported collation." type="dynamic"><p>Raised by any function that uses a collation if the requested collation is not recognized.</p></error><error class="CH" code="0003" label="Unsupported normalization form." type="static"><p>Raised by <code>fn:normalize-unicode</code> if the requested normalization form is not
               supported by the implementation.</p></error><error class="CH" code="0004" label="Collation does not support collation units." type="dynamic"><p>Raised by functions such as <code>fn:contains</code> if the requested collation does
               not operate on a character-by-character basis.</p></error><error class="DC" code="0001" label="No context document." type="dynamic"><p>Raised by <code>fn:id</code>, <code>fn:idref</code>, and <code>fn:element-with-id</code>
                  if the node that identifies the tree to be searched is a node in a tree whose root is not
                  a document node.</p></error><error class="DC" code="0002" label="Error retrieving resource." type="dynamic"><p>Raised by <code>fn:doc</code>, <code>fn:collection</code>, and <code>fn:uri-collection</code>
               to indicate that either the supplied URI cannot be dereferenced to obtain a resource, or the resource
               that is returned is not parseable as XML.</p></error><error class="DC" code="0003" label="Function not defined as deterministic." type="dynamic"><p>Raised by <code>fn:doc</code>, <code>fn:collection</code>, <phrase diff="add" at="D">and <code>fn:uri-collection</code></phrase> 
                  to indicate that it is not possible to
               return a result that is guaranteed deterministic.</p></error><error class="DC" code="0004" label="Invalid collection URI." type="dynamic"><p>Raised by <code>fn:collection</code> <phrase diff="add" at="D">and <code>fn:uri-collection</code></phrase> 
                  if the argument is not a valid <code>xs:anyURI</code>.</p></error><error class="DC" code="0005" label="Invalid argument to fn:doc or fn:doc-available." type="dynamic"><p>Raised (optionally) by <code>fn:doc</code> and <code>fn:doc-available</code> if the argument 
                  is not a valid <phrase diff="chg" at="D">URI reference</phrase>.</p></error><error class="DC" code="0006" label="String passed to fn:parse-xml is not a well-formed XML document." type="dynamic"><p>Raised by <code>fn:parse-xml</code> if the supplied string is not a well-formed and namespace-well-formed XML document;
               or if DTD validation is requested and the document is not valid against its DTD.</p></error><error class="DC" code="0010" label="The processor does not support serialization." type="dynamic"><p>Raised when <code>fn:serialize</code> is called and the processor does not support serialization,
               in cases where the host language makes serialization an optional feature.</p></error><error class="DF" code="1280" label="Invalid decimal format name." type="dynamic"><p>This error is raised if the decimal format name supplied to <code>fn:format-number</code> is not a valid QName,
			   or if the prefix in the QName is undeclared, or if there is no decimal format in the static context with
			   a matching name.</p></error><error class="DF" code="1310" label="Invalid decimal format picture string." type="dynamic"><p>This error is raised if the picture string supplied to <code>fn:format-number</code> <phrase diff="chg" at="D">or 
                  <code>fn:format-integer</code></phrase> has invalid syntax.</p></error><error class="DT" code="0001" label="Overflow/underflow in date/time operation." type="dynamic"><p>Raised when casting to date/time datatypes, or performing arithmetic with date/time values, if
               arithmetic overflow or underflow occurs.</p></error><error class="DT" code="0002" label="Overflow/underflow in duration operation." type="dynamic"><p>Raised when casting to duration datatypes, or performing arithmetic with duration values, if
                  arithmetic overflow or underflow occurs.</p></error><error class="DT" code="0003" label="Invalid timezone value." type="dynamic"><p>Raised by <code>adjust-date-to-timezone</code> and related functions if the supplied timezone is invalid.</p></error><error class="FD" code="1340" label="Invalid date/time formatting parameters." type="dynamic"><p>This error is raised if the picture string or calendar supplied to <code>fn:format-date</code>, <code>fn:format-time</code>, 
			   or <code>fn:format-dateTime</code> has invalid syntax.</p></error><error class="FD" code="1350" label="Invalid date/time formatting component." type="dynamic"><p>This error is raised if the picture string supplied to <code>fn:format-date</code> 
			   selects a component that is not present in a date, or if the picture string supplied to <code>fn:format-time</code> 
			   selects a component that is not present in a time.</p></error><error class="JS" code="0001" label="JSON syntax error." type="dynamic"><p diff="add" at="A">Raised by functions such as <code>fn:json-doc</code>, <code>fn:parse-json</code> 
                  <phrase diff="add" at="D">or <code>fn:json-to-xml</code></phrase> 
                  if the string supplied as input does not conform to the JSON grammar (optionally with implementation-defined extensions).</p></error><error class="JS" code="0003" label="JSON duplicate keys." type="dynamic"><p diff="add" at="A">Raised by functions such as <code>map:merge</code>, <code>fn:json-doc</code>, 
                  <code>fn:parse-json</code> <phrase diff="add" at="D">or <code>fn:json-to-xml</code></phrase> 
                  if the input contains duplicate keys, when the chosen policy is to reject duplicates.</p></error><error class="JS" code="0004" label="JSON: not schema-aware." type="dynamic"><p diff="add" at="D">Raised by <code>fn:json-to-xml</code> if validation 
                  is requested when the processor does not support schema validation or typed nodes.</p></error><error class="JS" code="0005" label="Invalid options." type="dynamic"><p diff="add" at="D">Raised by functions such as <code>map:merge</code>, <code>fn:parse-json</code>,
                  and <code>fn:xml-to-json</code> if the <code>$options</code> map contains an invalid entry.</p></error><error class="JS" code="0006" label="Invalid XML representation of JSON." type="dynamic"><p diff="add" at="D">Raised by <code>fn:xml-to-json</code> if the XML input does not
                  conform to the rules for the XML representation of JSON.</p></error><error class="JS" code="0007" label="Bad JSON escape sequence." type="dynamic"><p diff="add" at="D">Raised by <code>fn:xml-to-json</code> if the XML input uses the attribute
                  <code>escaped="true"</code> or <code>escaped-key="true"</code>, and the corresponding string
                  or key contains an invalid JSON escape sequence.</p></error><error class="NS" code="0004" label="No namespace found for prefix." type="dynamic"><p>Raised by <code>fn:resolve-QName</code> and analogous functions if a supplied QName has a 
                  prefix that has no binding to a namespace.</p></error><error class="NS" code="0005" label="Base-uri not defined in the static context." type="dynamic"><p>Raised by <code>fn:resolve-uri</code> if no base URI is available for resolving a relative URI.</p></error><error class="QM" code="0001" label="Module URI is a zero-length string." type="dynamic"><p>Raised by <code>fn:load-xquery-module</code> if the supplied module URI is zero-length.</p></error><error class="QM" code="0002" label="Module URI not found." type="dynamic"><p>Raised by <code>fn:load-xquery-module</code> if no module can be found with the supplied module URI.</p></error><error class="QM" code="0003" label="Static error in dynamically-loaded XQuery module." type="dynamic"><p>Raised by <code>fn:load-xquery-module</code> if a static error 
                  (including a statically-detected type error) is encountered when processing the library module.</p></error><error class="QM" code="0005" label="Parameter for dynamically-loaded XQuery module has incorrect type." type="dynamic"><p>Raised by <code>fn:load-xquery-module</code> if a value is supplied for the initial context 
                  item or for an external variable, and the value does not conform to the required
                  type declared in the dynamically loaded module.</p></error><error class="QM" code="0006" label="No suitable XQuery processor available." type="dynamic"><p>Raised by <code>fn:load-xquery-module</code> if no XQuery processor is available supporting the requested
                  XQuery version (or if none is available at all).</p></error><error class="RG" code="0001" label="Invalid value for cast/constructor." type="dynamic"><p>A general-purpose error raised when casting, if a cast between two datatypes is allowed in principle,
               but the supplied value cannot be converted: for example when attempting to cast the string "nine" to an integer.</p></error><error class="RG" code="0002" label="Invalid argument to fn:resolve-uri()." type="dynamic"><p>Raised when either argument to <code>fn:resolve-uri</code> is not a valid URI/IRI.</p></error><error class="RG" code="0003" label="fn:zero-or-one called with a sequence containing more than one item." type="dynamic"><p>Raised by <code>fn:zero-or-one</code> if the supplied value contains more than one item.</p></error><error class="RG" code="0004" label="fn:one-or-more called with a sequence containing no items." type="dynamic"><p>Raised by <code>fn:one-or-more</code> if the supplied value is an empty sequence.</p></error><error class="RG" code="0005" label="fn:exactly-one called with a sequence containing zero or more than one item." type="dynamic"><p>Raised by <code>fn:exactly-one</code> if the supplied value is not a singleton sequence.</p></error><error class="RG" code="0006" label="Invalid argument type." type="static"><p>Raised by functions such as <code>fn:max</code>, <code>fn:min</code>, <code>fn:avg</code>, <code>fn:sum</code>
               if the supplied sequence contains values inappropriate to this function.</p></error><error class="RG" code="0008" label="The two arguments to fn:dateTime have inconsistent timezones." type="dynamic"><p>Raised by <code>fn:dateTime</code> if the two arguments both have timezones and the timezones are different.</p></error><error class="RG" code="0009" label="Error in resolving a relative URI against a base URI in fn:resolve-uri." type="dynamic"><p>A catch-all error for <code>fn:resolve-uri</code>, recognizing that the implementation can choose between a variety
               of algorithms and that some of these may fail for a variety of reasons.</p></error><error class="RG" code="0010" label="Invalid date/time." type="dynamic"><p>Raised when the input to <code>fn:parse-ietf-date</code> does not match the prescribed
                  grammar, or when it represents an invalid date/time such as 31 February.</p></error><error class="RX" code="0001" label="Invalid regular expression flags." type="static"><p>Raised by regular expression functions such as <code>fn:matches</code> and <code>fn:replace</code> if the
               regular expression flags contain a character other than <code>i</code>, <code>m</code>, <code>q</code>, <code>s</code>, or <code>x</code>.</p></error><error class="RX" code="0002" label="Invalid regular expression." type="dynamic"><p>Raised by regular expression functions such as <code>fn:matches</code> and <code>fn:replace</code> if the
                  regular expression is syntactically invalid.</p></error><error class="RX" code="0003" label="Regular expression matches zero-length string." type="dynamic"><p>For functions such as <code>fn:replace</code> and <code>fn:tokenize</code>, raises an error if
               the supplied regular expression is capable of matching a zero length string.</p></error><error class="RX" code="0004" label="Invalid replacement string." type="dynamic"><p>Raised by <code>fn:replace</code> to report errors in the replacement string.</p></error><error class="TY" code="0012" label="Argument to fn:data() contains a node that does not have a typed value." type="dynamic"><p>Raised by <code>fn:data</code>, or by implicit atomization, if applied to a node with no typed value,
               the main example being an element validated against a complex type that defines it to have element-only content.</p></error><error class="TY" code="0013" label="The argument to fn:data() contains a function item." type="dynamic"><p>Raised by <code>fn:data</code>, or by implicit atomization, if the sequence to be atomized contains
                a function item.</p></error><error class="TY" code="0014" label="The argument to fn:string() is a function item." type="dynamic"><p>Raised by <code>fn:string</code>, or by implicit string conversion, if the input sequence contains
                  a function item.</p></error><error class="TY" code="0015" label="An argument to fn:deep-equal() contains a function item." type="dynamic"><p>Raised by <code>fn:deep-equal</code> if either input sequence contains a
                  function item.</p></error><error class="UT" code="1170" label="Invalid $href argument to fn:unparsed-text() (etc.)" type="dynamic"><p>A dynamic error is raised if the <code>$href</code> argument
                  contains a fragment identifier, or if it cannot be used to retrieve a resource
                  containing text.</p></error><error class="UT" code="1190" label="Cannot decode resource retrieved by fn:unparsed-text() (etc.)" type="dynamic"><p>A dynamic error is raised if the retrieved
                  resource contains octets that cannot be decoded into Unicode <termref def="character">characters</termref> using the specified encoding, or if the resulting characters
                  are not permitted XML characters. This includes the case where the processor 
                  does not support the requested encoding.</p></error><error class="UT" code="1200" label="Cannot infer encoding of resource retrieved by fn:unparsed-text() (etc.)" type="dynamic"><p>A dynamic error is raised if
                  <code>$encoding</code> is absent and the processor cannot infer the encoding using external information and the
                  encoding is not UTF-8.</p></error><error class="XT" code="0001" label="No suitable XSLT processor available" type="dynamic"><p>A dynamic error is raised if no XSLT processor suitable for evaluating a call on <function>fn:transform</function>
                  is available.</p></error><error class="XT" code="0002" label="Invalid parameters to XSLT transformation" type="dynamic"><p>A dynamic error is raised if the parameters supplied to <code>fn:transform</code> are invalid, for example
                  if two mutually-exclusive parameters are supplied. If a suitable XSLT error code is available (for example in the
               case where the requested <code>initial-template</code> does not exist in the stylesheet), that error code should
               be used in preference.</p></error><error class="XT" code="0003" label="XSLT transformation failed" type="dynamic"><p>A dynamic error is raised if an XSLT transformation invoked using <code>fn:transform</code> fails with a
                  static or dynamic error. The XSLT error code is used if available; this error code provides a fallback when no XSLT
                  error code is returned, for example because the processor is an XSLT 1.0 processor.</p></error><error class="XT" code="0004" label="XSLT transformation has been disabled" type="dynamic"><p>A dynamic error is raised if the <code>fn:transform</code> function is invoked when XSLT transformation (or a specific
                  transformation option) has been disabled for security or other reasons.</p></error><error class="XT" code="0005" label="XSLT output cannot be saved" type="dynamic"><p>A dynamic error is raised if the <code>fn:transform</code> function uses <code>delivery-format:saved</code> and
                  the output of the transformation cannot be saved at the requested location.</p></error><error class="XT" code="0006" label="XSLT output contains non-accepted characters" type="dynamic"><p>A dynamic error is raised if the result of the <code>fn:transform</code> function contains characters available
                  only in XML 1.1 and the calling processor cannot handle such characters.</p></error><error class="XT" code="0007" label="XSLT delivery-format:saved violates conditions on its use" type="dynamic"><p>A dynamic error is raised if the the <code>fn:transform</code> function uses <code>delivery-format:saved</code> in
                  a way that violates implementation-defined conditions on its use.</p></error></error-list></div1><div1 id="schemata"><head>Schemas</head><p diff="add" at="D">Two functions in this specification, <code>fn:analyze-string</code> and
         <code>fn:json-to-xml</code>, produce results in the form of an XDM node tree that must conform
         to a specified schema. In both cases the elements in the result are in the namespace 
         <code>http://www.w3.org/2005/xpath-functions</code>, which is therefore the target namespace
         of the relevant schema document.</p><p>The schema for this namespace is organized as three schema documents. The first is a simple
         umbrella document that includes the other two. A copy can be found at 
            <loc xmlns:xlink="http://www.w3.org/1999/xlink" href="xpath-functions.xsd" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">xpath-functions.xsd</loc>:</p><pre class="small">&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
    elementFormDefault="qualified"
    targetNamespace="http://www.w3.org/2005/xpath-functions"&gt;
    
    &lt;!-- 
     * This is a schema for the namespace http://www.w3.org/2005/xpath-functions
     *
     * The schema is made available under the terms of the W3C software notice and license
     * at http://www.w3.org/Consortium/Legal/copyright-software-19980720
     *
     * The schema includes two schema documents, containing definitions of the structure
     * of the results of the fn:analyze-string and fn:json-to-xml functions respectively.
     *
    --&gt;
    
    &lt;xs:include schemaLocation="analyze-string.xsd"/&gt;
    &lt;xs:include schemaLocation="schema-for-json.xsd"/&gt;
&lt;/xs:schema&gt;
</pre><div2 id="schema-for-analyze-string"><head>Schema for the result of <code>fn:analyze-string</code></head><p>This schema describes the output of the function <code>fn:analyze-string</code>.</p><p>The schema is reproduced below, and can also be found in <loc xmlns:xlink="http://www.w3.org/1999/xlink" href="analyze-string.xsd" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">analyze-string.xsd</loc>:</p><pre class="small">&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
    targetNamespace="http://www.w3.org/2005/xpath-functions"
    xmlns:fn="http://www.w3.org/2005/xpath-functions"
    elementFormDefault="qualified"&gt;
    
    &lt;!-- 
     * This is a schema for the XML representation of JSON used as the target for the
     * function fn:analyze-string()
     *
     * The schema is made available under the terms of the W3C software notice and license
     * at http://www.w3.org/Consortium/Legal/copyright-software-19980720
     *
    --&gt;

    &lt;xs:element name="analyze-string-result" type="fn:analyze-string-result-type"/&gt;
    &lt;xs:element name="match" type="fn:match-type"/&gt;
    &lt;xs:element name="non-match" type="xs:string"/&gt;
    &lt;xs:element name="group" type="fn:group-type"/&gt;
    
    &lt;xs:complexType name="analyze-string-result-type" mixed="true"&gt;
        &lt;xs:choice minOccurs="0" maxOccurs="unbounded"&gt;
            &lt;xs:element ref="fn:match"/&gt;
            &lt;xs:element ref="fn:non-match"/&gt;
        &lt;/xs:choice&gt;
    &lt;/xs:complexType&gt;
        
    &lt;xs:complexType name="match-type" mixed="true"&gt;
        &lt;xs:sequence&gt;
            &lt;xs:element ref="fn:group" minOccurs="0" maxOccurs="unbounded"/&gt;
        &lt;/xs:sequence&gt;
    &lt;/xs:complexType&gt;
    
    &lt;xs:complexType name="group-type" mixed="true"&gt;
        &lt;xs:sequence&gt;
            &lt;xs:element ref="fn:group" minOccurs="0" maxOccurs="unbounded"/&gt;
        &lt;/xs:sequence&gt;
        &lt;xs:attribute name="nr" type="xs:positiveInteger"/&gt;
    &lt;/xs:complexType&gt;    
 
&lt;/xs:schema&gt;
</pre></div2><div2 id="schema-for-json"><head>Schema for the result of <code>fn:json-to-xml</code></head><p>This schema describes the output of the function <code>fn:json-to-xml</code>, and the input to the
            function <code>fn:xml-to-json</code>. </p><p>The schema is reproduced below, and can also be found in <loc xmlns:xlink="http://www.w3.org/1999/xlink" href="schema-for-json.xsd" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">schema-for-json.xsd</loc>:</p><pre class="small">&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
    elementFormDefault="qualified"
    targetNamespace="http://www.w3.org/2005/xpath-functions"
    xmlns:j="http://www.w3.org/2005/xpath-functions"&gt;
    
    &lt;!-- 
     * This is a schema for the XML representation of JSON used as the target for the
     * function fn:json-to-xml()
     *
     * The schema is made available under the terms of the W3C software notice and license
     * at http://www.w3.org/Consortium/Legal/copyright-software-19980720
     *
    --&gt;
    
    &lt;xs:element name="map" type="j:mapType"&gt;
        &lt;xs:unique name="unique-key"&gt;
            &lt;xs:selector xpath="*"/&gt;
            &lt;xs:field xpath="@key"/&gt;
            &lt;xs:field xpath="@escaped-key"/&gt;
        &lt;/xs:unique&gt;
    &lt;/xs:element&gt;
    
    &lt;xs:element name="array" type="j:arrayType"/&gt;
    
    &lt;xs:element name="string" type="j:stringType"/&gt;
    
    &lt;xs:element name="number" type="j:numberType"/&gt;
    
    &lt;xs:element name="boolean" type="j:booleanType"/&gt;
    
    &lt;xs:element name="null" type="j:nullType"/&gt;
    
    &lt;xs:complexType name="nullType"&gt;
        &lt;xs:sequence/&gt;
        &lt;xs:anyAttribute processContents="skip" namespace="##other"/&gt;
    &lt;/xs:complexType&gt;
    
    &lt;xs:complexType name="booleanType"&gt;
        &lt;xs:simpleContent&gt;
            &lt;xs:extension base="xs:boolean"&gt;
                &lt;xs:anyAttribute processContents="skip" namespace="##other"/&gt;
            &lt;/xs:extension&gt;
        &lt;/xs:simpleContent&gt;
    &lt;/xs:complexType&gt;
    
    &lt;xs:complexType name="stringType"&gt;
        &lt;xs:simpleContent&gt;
            &lt;xs:extension base="xs:string"&gt;
                &lt;xs:attribute name="escaped" type="xs:boolean" use="optional" default="false"/&gt;
                &lt;xs:anyAttribute processContents="skip" namespace="##other"/&gt;
            &lt;/xs:extension&gt;
        &lt;/xs:simpleContent&gt;
    &lt;/xs:complexType&gt;
    
    &lt;xs:simpleType name="finiteNumberType"&gt;
        &lt;xs:restriction base="xs:double"&gt;
            &lt;!-- exclude positive and negative infinity, and NaN --&gt;
            &lt;xs:minExclusive value="-INF"/&gt;
            &lt;xs:maxExclusive value="INF"/&gt;
        &lt;/xs:restriction&gt;
    &lt;/xs:simpleType&gt;
    
    &lt;xs:complexType name="numberType"&gt;
        &lt;xs:simpleContent&gt;
            &lt;xs:extension base="j:finiteNumberType"&gt;
                &lt;xs:anyAttribute processContents="skip" namespace="##other"/&gt;
            &lt;/xs:extension&gt;
        &lt;/xs:simpleContent&gt;
    &lt;/xs:complexType&gt;
    
    &lt;xs:complexType name="arrayType"&gt;
        &lt;xs:choice minOccurs="0" maxOccurs="unbounded"&gt;
            &lt;xs:element ref="j:map"/&gt;
            &lt;xs:element ref="j:array"/&gt;
            &lt;xs:element ref="j:string"/&gt;
            &lt;xs:element ref="j:number"/&gt;
            &lt;xs:element ref="j:boolean"/&gt;
            &lt;xs:element ref="j:null"/&gt;
        &lt;/xs:choice&gt;
        &lt;xs:anyAttribute processContents="skip" namespace="##other"/&gt;
    &lt;/xs:complexType&gt;
    
    &lt;xs:complexType name="mapWithinMapType"&gt;
        &lt;xs:complexContent&gt;
            &lt;xs:extension base="j:mapType"&gt;
                &lt;xs:attributeGroup ref="j:key-group"/&gt;
            &lt;/xs:extension&gt;
        &lt;/xs:complexContent&gt;
    &lt;/xs:complexType&gt;
    
    &lt;xs:complexType name="arrayWithinMapType"&gt;
        &lt;xs:complexContent&gt;
            &lt;xs:extension base="j:arrayType"&gt;
                &lt;xs:attributeGroup ref="j:key-group"/&gt;
            &lt;/xs:extension&gt;
        &lt;/xs:complexContent&gt;
    &lt;/xs:complexType&gt;
    
    &lt;xs:complexType name="stringWithinMapType"&gt;
        &lt;xs:simpleContent&gt;
            &lt;xs:extension base="j:stringType"&gt;
                &lt;xs:attributeGroup ref="j:key-group"/&gt;
            &lt;/xs:extension&gt;
        &lt;/xs:simpleContent&gt;
    &lt;/xs:complexType&gt;
    
    &lt;xs:complexType name="numberWithinMapType"&gt;
        &lt;xs:simpleContent&gt;
            &lt;xs:extension base="j:numberType"&gt;
                &lt;xs:attributeGroup ref="j:key-group"/&gt;
            &lt;/xs:extension&gt;
        &lt;/xs:simpleContent&gt;
    &lt;/xs:complexType&gt;
    
    &lt;xs:complexType name="booleanWithinMapType"&gt;
        &lt;xs:simpleContent&gt;
            &lt;xs:extension base="j:booleanType"&gt;
                &lt;xs:attributeGroup ref="j:key-group"/&gt;
            &lt;/xs:extension&gt;
        &lt;/xs:simpleContent&gt;
    &lt;/xs:complexType&gt;
    
    &lt;xs:complexType name="nullWithinMapType"&gt;
        &lt;xs:attributeGroup ref="j:key-group"/&gt;
    &lt;/xs:complexType&gt;
    
    &lt;xs:complexType name="mapType"&gt;
        &lt;xs:choice minOccurs="0" maxOccurs="unbounded"&gt;
            &lt;xs:element name="map" type="j:mapWithinMapType"&gt;
                &lt;xs:unique name="unique-key-2"&gt;
                    &lt;xs:selector xpath="*"/&gt;
                    &lt;xs:field xpath="@key"/&gt;
                &lt;/xs:unique&gt;
            &lt;/xs:element&gt;
            &lt;xs:element name="array" type="j:arrayWithinMapType"/&gt;            
            &lt;xs:element name="string" type="j:stringWithinMapType"/&gt;   
            &lt;xs:element name="number" type="j:numberWithinMapType"/&gt;
            &lt;xs:element name="boolean" type="j:booleanWithinMapType"/&gt;
            &lt;xs:element name="null" type="j:nullWithinMapType"/&gt;
        &lt;/xs:choice&gt;
        &lt;xs:anyAttribute processContents="skip" namespace="##other"/&gt;
    &lt;/xs:complexType&gt;
    
    &lt;xs:attributeGroup name="key-group"&gt;
        &lt;xs:attribute name="key" type="xs:string" use="required"/&gt;
        &lt;xs:attribute name="escaped-key" type="xs:boolean" use="optional" default="false"/&gt;
    &lt;/xs:attributeGroup&gt;
    
&lt;/xs:schema&gt;
</pre></div2></div1><inform-div1 id="other-functions"><head>Other Functions</head><p>This Appendix describes some sources of functions that fall outside the scope of the function library defined
         in this specification. It includes both function specifications and function implementations. Inclusion of a function
         in this appendix does not constitute any kind of recommendation or endorsement; neither is omission from this appendix
         to be construed negatively. This Appendix does not attempt to give any information about licensing arrangements for
         these function specifications or implementations.</p><div2 id="functions-in-other-w3c-specs" diff="add" at="E"><head>XPath Functions Defined in Other W3C Recommendations</head><p>A number of W3C Recommendations make use of XPath, and in some cases such Recommmendations define additional
            functions to be made available when XPath is used in a specific host language.</p><div3 id="functions-defined-in-XSLT"><head>Functions Defined in XSLT</head><p>The various versions of XSLT have all included additional functions intended to be available only when XPath
               is used within XSLT, and not in other host language environments. Some of these functions were originally defined
               in XSLT, and subsequently migrated into the core function library defined in this specification.</p><p>Generally, the reason that functions have been defined in XSLT rather than in the core library has been that
               they required additional static or dynamic context information.</p><p>XSLT-defined functions share the core namespace <code>http://www.w3.org/2005/xpath-functions</code> (but in XPath 1.0
               and XSLT 1.0, no namespace was defined for these functions).</p><p>The conformance rules for XSLT 3.0 require implementations to support either XPath 3.0 or XPath 3.1. Some of the
               new functions in XPath 3.1, however, must be supported by all XSLT 3.0 implementations whether or not they implement
               other parts of XPath 3.1.</p><p>The following table lists all functions that have been defined in XSLT 1.0, 2.0, or 3.0, and summarizes their status.</p><table role="data"><thead><tr><th rowspan="1" colspan="1">Function name</th><th rowspan="1" colspan="1">Availability</th></tr></thead><tbody><tr><td rowspan="1" colspan="1">fn:accumulator-after</td><td rowspan="1" colspan="1">XSLT 3.0 only</td></tr><tr><td rowspan="1" colspan="1">fn:accumulator-before</td><td rowspan="1" colspan="1">XSLT 3.0 only</td></tr><tr><td rowspan="1" colspan="1">fn:available-system-properties</td><td rowspan="1" colspan="1">XSLT 3.0 only</td></tr><tr><td rowspan="1" colspan="1">fn:collation-key</td><td rowspan="1" colspan="1">Common to XSLT 3.0 and XPath 3.1</td></tr><tr><td rowspan="1" colspan="1">fn:copy-of</td><td rowspan="1" colspan="1">XSLT 3.0 only</td></tr><tr><td rowspan="1" colspan="1">fn:current</td><td rowspan="1" colspan="1">XSLT 1.0, 2.0, and 3.0</td></tr><tr><td rowspan="1" colspan="1">fn:current-group</td><td rowspan="1" colspan="1">XSLT 2.0 and 3.0</td></tr><tr><td rowspan="1" colspan="1">fn:current-grouping-key</td><td rowspan="1" colspan="1">XSLT 2.0 and 3.0</td></tr><tr><td rowspan="1" colspan="1">fn:current-merge-group</td><td rowspan="1" colspan="1">XSLT 3.0 only</td></tr><tr><td rowspan="1" colspan="1">fn:current-merge-key</td><td rowspan="1" colspan="1">XSLT 3.0 only</td></tr><tr><td rowspan="1" colspan="1">fn:current-output-uri</td><td rowspan="1" colspan="1">XSLT 3.0 only</td></tr><tr><td rowspan="1" colspan="1">fn:document</td><td rowspan="1" colspan="1">XSLT 1.0, 2.0, and 3.0</td></tr><tr><td rowspan="1" colspan="1">fn:element-available</td><td rowspan="1" colspan="1">XSLT 1.0, 2.0, and 3.0</td></tr><tr><td rowspan="1" colspan="1">fn:format-date</td><td rowspan="1" colspan="1">XSLT 2.0; migrated to XPath 3.0 and 3.1</td></tr><tr><td rowspan="1" colspan="1">fn:format-dateTime</td><td rowspan="1" colspan="1">XSLT 2.0; migrated to XPath 3.0 and 3.1</td></tr><tr><td rowspan="1" colspan="1">fn:format-number</td><td rowspan="1" colspan="1">XSLT 1.0 and 2.0; migrated to XPath 3.0 and 3.1</td></tr><tr><td rowspan="1" colspan="1">fn:format-time</td><td rowspan="1" colspan="1">XSLT 2.0; migrated to XPath 3.0 and 3.1</td></tr><tr><td rowspan="1" colspan="1">fn:function-available</td><td rowspan="1" colspan="1">XSLT 1.0, 2.0, and 3.0</td></tr><tr><td rowspan="1" colspan="1">fn:generate-id</td><td rowspan="1" colspan="1">XSLT 1.0 and 2.0; migrated to XPath 3.0 and 3.1</td></tr><tr><td rowspan="1" colspan="1">fn:json-to-xml</td><td rowspan="1" colspan="1">Common to XSLT 3.0 and XPath 3.1</td></tr><tr><td rowspan="1" colspan="1">fn:key</td><td rowspan="1" colspan="1">XSLT 1.0, 2.0, and 3.0</td></tr><tr><td rowspan="1" colspan="1">fn:regex-group</td><td rowspan="1" colspan="1">XSLT 2.0 and 3.0</td></tr><tr><td rowspan="1" colspan="1">fn:snapshot</td><td rowspan="1" colspan="1">XSLT 3.0 only</td></tr><tr><td rowspan="1" colspan="1">fn:stream-available</td><td rowspan="1" colspan="1">XSLT 3.0 only</td></tr><tr><td rowspan="1" colspan="1">fn:system-property</td><td rowspan="1" colspan="1">XSLT 1.0, 2.0, and 3.0</td></tr><tr><td rowspan="1" colspan="1">fn:type-available</td><td rowspan="1" colspan="1">XSLT 2.0 and 3.0</td></tr><tr><td rowspan="1" colspan="1">fn:unparsed-entity-public-id</td><td rowspan="1" colspan="1">XSLT 2.0 and 3.0</td></tr><tr><td rowspan="1" colspan="1">fn:unparsed-entity-uri</td><td rowspan="1" colspan="1">XSLT 1.0, 2.0, and 3.0</td></tr><tr><td rowspan="1" colspan="1">fn:unparsed-text</td><td rowspan="1" colspan="1">XSLT 2.0; migrated to XPath 3.0 and 3.1</td></tr><tr><td rowspan="1" colspan="1">fn:xml-to-json</td><td rowspan="1" colspan="1">Common to XSLT 3.0 and XPath 3.1</td></tr><tr><td rowspan="1" colspan="1">map:contains</td><td rowspan="1" colspan="1">Common to XSLT 3.0 and XPath 3.1</td></tr><tr><td rowspan="1" colspan="1">map:entry</td><td rowspan="1" colspan="1">Common to XSLT 3.0 and XPath 3.1</td></tr><tr><td rowspan="1" colspan="1">map:find</td><td rowspan="1" colspan="1">Common to XSLT 3.0 and XPath 3.1</td></tr><tr><td rowspan="1" colspan="1">map:for-each</td><td rowspan="1" colspan="1">Common to XSLT 3.0 and XPath 3.1</td></tr><tr><td rowspan="1" colspan="1">map:get</td><td rowspan="1" colspan="1">Common to XSLT 3.0 and XPath 3.1</td></tr><tr><td rowspan="1" colspan="1">map:keys</td><td rowspan="1" colspan="1">Common to XSLT 3.0 and XPath 3.1</td></tr><tr><td rowspan="1" colspan="1">map:merge</td><td rowspan="1" colspan="1">Common to XSLT 3.0 and XPath 3.1</td></tr><tr><td rowspan="1" colspan="1">map:put</td><td rowspan="1" colspan="1">Common to XSLT 3.0 and XPath 3.1</td></tr><tr><td rowspan="1" colspan="1">map:remove</td><td rowspan="1" colspan="1">Common to XSLT 3.0 and XPath 3.1</td></tr><tr><td rowspan="1" colspan="1">map:size</td><td rowspan="1" colspan="1">Common to XSLT 3.0 and XPath 3.1</td></tr></tbody></table></div3><div3 id="functions-defined-in-XForms"><head>Functions Defined in XForms</head><p>XForms 1.1 is based on XPath 1.0. It adds the following functions to the set defined in XPath 1.0, using the same
               namespace:</p><p><code>boolean-from-string</code>, <code>is-card-number</code>, <code>avg</code>, <code>min</code>, <code>max</code>, 
                  <code>count-non-empty</code>, <code>index</code>, <code>power</code>, <code>random</code>, <code>compare</code>,
                  <code>if</code>, <code>property</code>, 
               <code>digest</code>, <code>hmac</code>, <code>local-date</code>, <code>local-dateTime</code>, <code>now</code>, 
                  <code>days-from-date</code>, <code>days-to-date</code>, <code>seconds-from-dateTime</code>, <code>seconds-to-dateTime</code>,
               <code>adjust-dateTime-to-timezone</code>, <code>seconds</code>, <code>months</code>, <code>instance</code>, 
                  <code>current</code>, <code>id</code>, <code>context</code>, <code>choose</code>, <code>event</code>.</p><p>XForms 2.0 was first published as a W3C Working Draft, and subsequently as a W3C Community Group specification. These
               draft specifications do not include any additional functions beyond those in the core XPath specification.</p></div3><div3 id="xquery-update"><head>Function Defined in XQuery Update 1.0</head><p>The XQuery Update 1.0 specification defines one additional function in the core namespace
                  <code>http://www.w3.org/2005/xpath-functions</code>, namely <code role="example">fn:put</code>. This function can be used
               to write a document to external storage. It is thus unusual in that it has side-effects; the XQuery Update 1.0
               specification defines semantics for updating expressions including this function.</p><p>Although XQuery Update 1.0 is defined as an extension of XQuery 1.0, a number of implementors have adapted it,
               in a fairly intuitive way, to work with later versions of XQuery. At the time of this publication, later versions of the
               XQuery Update specification remain at Working Draft status.</p></div3></div2><div2 id="functions-defined-by-community-groups" diff="add" at="E"><head>Functions Defined by Community Groups</head><p>A number of community groups, with varying levels of formal organization, have defined specifications for
            additional function libraries to augment the core functions defined in this specification. Many of the resulting
            function specifications have implementations available for popular XPath, XQuery, and XSLT processors, though
            the level of support is highly variable.</p><p>The first such group was EXSLT. This activity was primarily concerned with augmenting the capability of
            XSLT 1.0, and many of its specifications were overtaken by core functions that became available in XPath 2.0.
            EXSLT defined a number of function modules covering:</p><slist><sitem>Dates and Times</sitem><sitem>Dynamic XPath Evaluation</sitem><sitem>Common (containing most notably the widely-used <code>node-set</code> function)</sitem><sitem>Math (<code>max</code>, <code>min</code>, <code>abs</code>, and trigonometric functions)</sitem><sitem>Random Number Generation</sitem><sitem>Regular Expressions</sitem><sitem>Sets (operations on sets of nodes including set intersection and difference)</sitem><sitem>String Manipulation (tokenize, replace, join and split, etc.)</sitem></slist><p>Specifications from the EXSLT group can be found at <bibref ref="exslt"/>.</p><p>A renewed attempt to define additional function libraries using XPath 2.0 as its baseline formed
            under the name EXPath. Again, the specifications are in various states of maturity and stability, and
            implementation across popular processors is patchy. At the time of this publication the function libraries that
            exist in stable published form include:</p><slist><sitem>Binary (functions for manipulating binary data)</sitem><sitem>File Handling (reading and writing files)</sitem><sitem>Geospatial (handling of geographic data)</sitem><sitem>HTTP Client (sending HTTP requests)</sitem><sitem>ZIP Facility (reading and creating ZIP files or similar archives)</sitem></slist><p>The EXPath community has also been engaged in other related projects, such as defining packaging
            standards for distribution of XSLT/XQuery components, and tools for unit testing. Its specifications
            can be found at <bibref ref="expath"/>.</p><p>A third activity has operated under the name EXQuery, which as the name suggests has focused
            on extensions to XQuery. EXQuery has published a single specification, RestXQ, which is primarily a 
            system of function annotations allowing XQuery functions to act as endpoints for RESTful services.
            It also includes some simple functions to assist with the creation of such services. The RestXQ specification
            can be found at <bibref ref="exquery"/>.</p></div2><div2 id="functx-library" diff="add" at="E"><head>The FunctX Library</head><p>Many useful functions can be written in XSLT or XQuery, and in this case the function implementations
                  themselves can be portable across different XSLT and XQuery processors. This section describes one such library.</p><p>FunctX is an open-source library of general-purpose functions, supplied in the form of XQuery 1.0 and XSLT 2.0
               implementations. It contains over a hundred functions. Typical examples of these functions are:</p><slist><sitem>Test whether a string is all-whitespace</sitem><sitem>Trim leading and trailing whitespace</sitem><sitem>Test whether all the values in a sequence are distinct</sitem><sitem>Capitalize the first character of a string</sitem><sitem>Change the namespace of all elements in a tree</sitem><sitem>Get the number of days in a given month</sitem><sitem>Get the first or last day in a given month</sitem><sitem>Get the date of the preceding or following day</sitem><sitem>Ask whether an element has element-only, mixed, or simple content</sitem><sitem>Find the position of a node in a sequence</sitem><sitem>Count words in a string</sitem></slist><p>The FunctX library can be found at <bibref ref="functx"/>.</p></div2><div2 id="examples"><head>Illustrative user-written functions</head><p> Certain 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.</p><p>This Appendix provides sample implementations of some of these functions.</p><p> 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.</p><div3 id="if-empty-or-absent"><head>eg:if-empty</head><p>In some situations, users may want to provide default values for missing
                    information that may be signaled by elements that are omitted, have no value or
                    have the empty sequence as their value. For example, a missing middle initial
                    may be indicated by omitting the element or a non-existent bonus signaled with
                    an empty sequence. This section includes examples of functions that provide such
                    defaults. These functions return <code>xs:anyAtomicType*</code>. Users may want
                    to write functions that return more specific types.</p><div4 id="if-empty"><head>eg:if-empty</head><example role="signature"><proto role="example" name="if-empty" return-type="xs:anyAtomicType*" prefix="eg" returnEmptyOk="no" isSpecial="yes" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isOp="no"><arg name="node" type="node()" emptyOk="yes"/><arg name="value" type="xs:anyAtomicType"/></proto></example><p> If the first argument is the empty sequence or an element without simple or
                        complex content, <code>eg:if-empty()</code> returns the second argument; otherwise, it
                        returns the content of the first argument.</p><p>XSLT implementation</p><eg xml:space="preserve">
&lt;xsl:function name="eg:if-empty" as="xs:anyAtomicType*"&gt;
  &lt;xsl:param name="node" as="node()?"/&gt;
  &lt;xsl:param name="value" as="xs:anyAtomicType"/&gt;
  &lt;xsl:sequence select="($node[child::node()], $value)[1]"/&gt;
&lt;/xsl:function&gt;</eg><p>XQuery implementation</p><eg xml:space="preserve">
declare function eg:if-empty (
  $node as node()?,
  $value as xs:anyAtomicType) as xs:anyAtomicType* 
{
  ($node[child::node()], $value)[1]
}
                    </eg></div4><div4 id="if-absent"><head>eg:if-absent</head><example role="signature"><proto role="example" name="if-absent" return-type="xs:anyAtomicType*" prefix="eg" returnEmptyOk="no" isSpecial="yes" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isOp="no"><arg name="node" type="node()" emptyOk="yes"/><arg name="value" type="xs:anyAtomicType"/></proto></example><p> If the first argument is the empty sequence, <code>eg:if-absent()</code> returns the second
                        argument; otherwise, it returns the content of the first argument.</p><p>XSLT implementation</p><eg xml:space="preserve">
&lt;xsl:function name="eg:if-absent" as="xs:anyAtomicType*"&gt;
  &lt;xsl:param name="node" as="node()?"/&gt;
  &lt;xsl:param name="value" as="xs:anyAtomicType"/&gt;
  &lt;xsl:sequence select="($node, $value)[1]"/&gt;
&lt;/xsl:function&gt;</eg><p>XQuery implementation</p><eg xml:space="preserve">
declare function eg:if-absent (
  $node as node()?,
  $value as xs:anyAtomicType) as xs:anyAtomicType* 
{
  ($node, $value)[1]
}
                    </eg></div4></div3><div3 id="union-intersect-except-on-values"><head>Union, intersection and difference on sequences of values</head><div4 id="value-union"><head>eg:value-union</head><example role="signature"><proto role="example" name="value-union" return-type="xs:anyAtomicType*" prefix="eg" returnEmptyOk="no" isSpecial="yes" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isOp="no"><arg name="arg1" type="xs:anyAtomicType*"/><arg name="arg2" type="xs:anyAtomicType*"/></proto></example><p> This function returns a sequence containing all the distinct items in <code>$arg1</code>
                        and <code>$arg2</code>, in an arbitrary order.</p><p>XSLT implementation</p><eg xml:space="preserve">
&lt;xsl:function name="eg:value-union" as="xs:anyAtomicType*"&gt;
  &lt;xsl:param name="arg1" as="xs:anyAtomicType*"/&gt;
  &lt;xsl:param name="arg2" as="xs:anyAtomicType*"/&gt;
  &lt;xsl:sequence
     select="fn:distinct-values(($arg1, $arg2))"/&gt; 
&lt;/xsl:function&gt;</eg><p>XQuery implementation</p><eg xml:space="preserve">
declare function eg:value-union (
  $arg1 as xs:anyAtomicType*,
  $arg2 as xs:anyAtomicType*) as xs:anyAtomicType* 
{
  fn:distinct-values(($arg1, $arg2))
}
                    </eg></div4><div4 id="value-intersect"><head>eg:value-intersect</head><example role="signature"><proto role="example" name="value-intersect" return-type="xs:anyAtomicType*" prefix="eg" returnEmptyOk="no" isSpecial="yes" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isOp="no"><arg name="arg1" type="xs:anyAtomicType*"/><arg name="arg2" type="xs:anyAtomicType*"/></proto></example><p> This function returns a sequence containing all the distinct items that
                        appear in both <code>$arg1</code> and <code>$arg2</code>, in an arbitrary order.</p><p>XSLT implementation&gt;</p><eg xml:space="preserve">
&lt;xsl:function name="eg:value-intersect" as="xs:anyAtomicType*"&gt;
  &lt;xsl:param name="arg1" as="xs:anyAtomicType*"/&gt;
  &lt;xsl:param name="arg2" as="xs:anyAtomicType*"/&gt;
  &lt;xsl:sequence 
     select="fn:distinct-values($arg1[.=$arg2])"/&gt;
&lt;/xsl:function&gt;</eg><p>XQuery implementation</p><eg xml:space="preserve">
declare function eg:value-intersect (
  $arg1 as xs:anyAtomicType*,
  $arg2 as xs:anyAtomicType* ) as xs:anyAtomicType* 
{
  fn:distinct-values($arg1[.=$arg2])
}
                    </eg></div4><div4 id="value-except"><head>eg:value-except</head><example role="signature"><proto role="example" name="value-except" return-type="xs:anyAtomicType*" prefix="eg" returnEmptyOk="no" isSpecial="yes" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isOp="no"><arg name="arg1" type="xs:anyAtomicType*"/><arg name="arg2" type="xs:anyAtomicType*"/></proto></example><p> This function returns a sequence containing all the distinct items that
                        appear in <code>$arg1</code> but not in <code>$arg2</code>, in an arbitrary order.</p><p>XSLT implementation</p><eg xml:space="preserve">
&lt;xsl:function name="eg:value-except" as="xs:anyAtomicType*"&gt;
  &lt;xsl:param name="arg1" as="xs:anyAtomicType*"/&gt;
  &lt;xsl:param name="arg2" as="xs:anyAtomicType*"/&gt;
  &lt;xsl:sequence
     select="fn:distinct-values($arg1[not(.=$arg2)])"/&gt;
&lt;/xsl:function&gt;</eg><p>XQuery implementation</p><eg xml:space="preserve">
declare function eg:value-except (
  $arg1 as xs:anyAtomicType*,
  $arg2 as xs:anyAtomicType*) as xs:anyAtomicType* 
{
  fn:distinct-values($arg1[not(.=$arg2)])
}</eg></div4></div3><div3 id="index-of-node"><head>eg:index-of-node</head><example role="signature"><proto role="example" name="index-of-node" return-type="xs:integer*" prefix="eg" returnEmptyOk="no" isSpecial="yes" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isOp="no"><arg name="seq" type="node()*"/><arg name="search" type="node()"/></proto></example><p>This function returns a sequence of positive integers giving the positions within
                    the sequence <code>$seq</code> of nodes that are identical to <code>$search</code>.</p><p>The nodes in the sequence <code>$seq</code> are compared with
               <code>$search</code> under the rules for the <code>is</code> operator. If a
                    node compares identical, then the position of that node in the sequence
                    <code>$seq</code> is included in the result.</p><p>If the value of <code>$seq</code> is the empty sequence, or if no node in
               <code>$seq</code> matches <code>$search</code>, then the empty sequence is returned.</p><p>The index is 1-based, not 0-based.</p><p>The result sequence is in ascending numeric order.</p><p>XSLT implementation</p><eg xml:space="preserve">
&lt;xsl:function name="eg:index-of-node" as="xs:integer*"&gt;
  &lt;xsl:param name="seq" as="node()*"/&gt;
  &lt;xsl:param name="search" as="node()"/&gt;
  &lt;xsl:sequence select="filter(
      1 to count($seq),
      function($i as xs:integer) as xs:boolean {$seq[$i] is $search}  
    )
  "/&gt;
&lt;/xsl:function&gt;</eg><p>XQuery implementation</p><eg xml:space="preserve">
declare function eg:index-of-node($seq as node()*, $search as node()) as xs:integer* 
{
    fn:filter(
      1 to fn:count($seq),
      function($i as xs:integer) as xs:boolean {$seq[$i] is $search}   
    )

}</eg><p>An alternative implementation, which might be faster in systems where indexing into a sequence
            is slow, is:</p><eg xml:space="preserve">
declare function eg:index-of-node($seq as node()*, $search as node()) as xs:integer* 
{
  fn:for-each-pair(
     $seq, 1 to fn:count($seq),
     function($node, $index) {
        if($node is $search) then $index else () 
     })
}</eg></div3><div3 id="string-pad"><head>eg:string-pad</head><example role="signature"><proto role="example" name="string-pad" return-type="xs:string" returnEmptyOk="no" prefix="eg" isSpecial="yes" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isOp="no"><arg name="padString" type="xs:string" emptyOk="yes"/><arg name="padCount" type="xs:integer"/></proto></example><p>Returns a <code>xs:string</code> consisting of a given number of copies of an
                    <code>xs:string</code> argument concatenated together.</p><p>XSLT implementation</p><eg xml:space="preserve">
&lt;xsl:function name="eg:string-pad" as="xs:string"&gt;
  &lt;xsl:param name="padString" as="xs:string?"/&gt;
  &lt;xsl:param name="padCount" as="xs:integer"/&gt;
  &lt;xsl:sequence select="
     fn:string-join(for $i in 1 to $padCount return $padString)"/&gt;
 &lt;/xsl:function&gt;
                </eg><p>XQuery implementation</p><eg xml:space="preserve">
declare function eg:string-pad (
  $padString as xs:string?,
  $padCount as xs:integer) as xs:string 
{
   fn:string-join(for $i in 1 to $padCount return $padString)
}
                </eg><p>This returns the zero-length string if <code>$padString</code> is the empty
                    sequence, which is consistent with the general principle that if an
                    <code>xs:string</code> argument is the empty sequence it is treated as if it
                    were the zero-length string.</p></div3><div3 id="func-distinct-nodes-stable"><head>eg:distinct-nodes-stable</head><example role="signature"><proto role="example" name="distinct-nodes-stable" return-type="node()*" prefix="eg" returnEmptyOk="no" isSpecial="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isOp="no"><arg name="arg" type="node()*"/></proto></example><p>This function illustrates one possible implementation of a distinct-nodes
                    function. It removes duplicate nodes by identity, preserving the first
                    occurrence of each node.</p><p>XPath</p><eg xml:space="preserve">$arg[empty(subsequence($arg, 1, position()-1) intersect .)]
                </eg><p>XSLT implementation</p><eg xml:space="preserve">
&lt;xsl:function name="eg:distinct-nodes-stable" as="node()*"&gt;
  &lt;xsl:param name="arg" as="node()*"/&gt;
  &lt;xsl:sequence select=""
    fn:fold-left(
      $arg, (),
      function($foundSoFar as node()*, $this as node()) as node()* {
        if ($foundSoFar intersect $this)
        then $foundSoFar
        else ($foundSoFar, $this)
      })
  "/&gt; 
&lt;/xsl:function&gt;
                </eg><p>XQuery implementation</p><eg xml:space="preserve">
declare function eg:distinct-nodes-stable ($arg as node()*) as node()* { 
  fn:fold-left(
      $arg, (),
      function($foundSoFar as node()*, $this as node()) as node()* {
        if ($foundSoFar intersect $this)
        then $foundSoFar
        else ($foundSoFar, $this)
      })

};</eg></div3><div3 id="highest-lowest"><head>Finding minima and maxima</head><p>The <code>fn:min</code> and <code>fn:max</code> functions allow one to determine the smallest and largest
            values in a set of values, but they do not directly allow one to determine the elements having the smallest
            or largest value for some property, for example the employees earning the highest or lowest salary. The
            functions in this section show how this can be achieved.</p><p>The functions take as input an arbitrary sequence of items (typically but not necessarily a sequence of elements)
            and a function that computes a property value for each of these items. This must be a value of an atomic type
            for which order comparisons are defined. The functions return those items from the input sequence that have
            a higher (or lower) value for the given property than any others in the sequence. If there are several that
            are joint highest (or lowest) then they are all returned.</p><div4 id="highest"><head>eg:highest</head><p>The function <code>eg:highest</code> returns the items having the highest value for the supplied function.</p><p>XSLT implementation</p><eg xml:space="preserve">
&lt;xsl:function name="eg:highest" as="item()*"&gt;
  &lt;xsl:param name="seq" as="item()*"/&gt;
  &lt;xsl:param name="f" as="function(item()) as xs:anyAtomicType"/&gt;
  &lt;xsl:sequence select="
     fold-left(
       tail($seq), head($seq),
       function($highestSoFar as item()*, $this as item()*) as item()* {
         let $thisValue := $f($this)
         let $highestValue := $f($highestSoFar[1])
         return
           if ($thisValue gt $highestValue)
             then $this
           else if ($thisValue eq $highestValue)
             then ($highestSoFar, $this)
           else $highestSoFar
       })"/&gt;
&lt;/xsl:function&gt;</eg><p>XQuery implementation</p><eg xml:space="preserve">
declare function eg:highest(
                     $seq as item()*
                     $f as function(item()) as xs:anyAtomicType)
                  as item()* {
     fn:fold-left(
       fn:tail($seq), fn:head($seq),
       function($highestSoFar as item()*, $this as item()*) as item()* {
         let $thisValue := $f($this)
         let $highestValue := $f($highestSoFar[1])
         return
           if ($thisValue gt $highestValue)
             then $this
           else if ($thisValue eq $highestValue)
             then ($highestSoFar, $this)
           else $highestSoFar
       })
};</eg><p>To find the employees with the highest salary, the function might be called as:</p><eg xml:space="preserve">
eg:highest(//employee, function($emp){$emp/salary})</eg></div4><div4 id="lowest"><head>eg:lowest</head><p>The function <code>eg:lowest</code> returns the items having the lowest value for the supplied function.</p><p>XSLT implementation</p><eg xml:space="preserve">
&lt;xsl:function name="eg:lowest" as="item()*"&gt;
  &lt;xsl:param name="seq" as="item()*"/&gt;
  &lt;xsl:param name="f" as="function(item()) as xs:anyAtomicType"/&gt;
  &lt;xsl:sequence select="
     fold-left(
       tail($seq), head($seq),
       function($lowestSoFar as item()*, $this as item()*) as item()* {
         let $thisValue := $f($this)
         let $lowestValue := $f($lowestSoFar[1])
         return
           if ($thisValue lt $lowestValue)
             then $this
           else if ($thisValue eq $lowestValue)
             then ($lowestSoFar, $this)
           else $lowestSoFar
       })"/&gt;
&lt;/xsl:function&gt;</eg><p>XQuery implementation</p><eg xml:space="preserve">
declare function eg:lowest(
                     $seq as item()*,
                     $f as function(item()) as xs:anyAtomicType)
                  as item()* {
     fn:fold-left(
       fn:tail($seq), fn:head($seq),
       function($lowestSoFar as item()*, $this as item()*) as item()* {
         let $thisValue := $f($this)
         let $lowestValue := $f($lowestSoFar[1])
         return
           if ($thisValue gt $lowestValue)
             then $this
           else if ($thisValue eq $lowestValue)
             then ($lowestSoFar, $this)
           else $lowestSoFar
       })
};</eg><p>To find the employees with the lowest total number of hours worked, the function might be called as:</p><eg xml:space="preserve">
eg:lowest(//employee, function($emp){sum($emp/timesheet/period/hours})</eg></div4></div3></div2></inform-div1><inform-div1 id="impl-def"><head>Checklist of implementation-defined features</head><?imp-def-features?></inform-div1><inform-div1 id="changelog" diff="chg" at="B"><head>Changes since version 3.0</head><div2 id="substantive-changes"><head>Substantive changes</head><olist><item><p>Functions are added to manipulate maps and arrays.</p></item><item><p>Functions are provided to convert data to and from JSON format.</p></item><item><p>The <code>format-number</code> function is enhanced to allow formatting using
              exponential notation.</p></item><item><p>Some new collation URIs are standardized:</p><ulist><item><p>A family of collation URIs corresponding to the Unicode
                     Collation Algorithm</p></item><item><p>A URI corresponding to the HTML matching rules (where ASCII letters are case-blind, but non-ASCII letters are not)</p></item></ulist></item><item><p>As well as functions for maps and arrays, further new functions are added:</p><ulist><item><p><code>fn:apply</code> (dynamically applies a function to arguments supplied as an array)</p></item><item><p><code>fn:collation-key</code> (generates a key that can be used for collation-based matching)</p></item><item><p><code>fn:contains-token</code> (tests whether a token is present in a whitespace-separated list)</p></item><item><p><code>fn:default-language</code> (returns the default language from the context)</p></item><item><p><code>fn:json-doc</code> (loads and parses a document in JSON format, producing maps and arrays)</p></item><item><p><code>fn:json-to-xml</code> (converts JSON to XML)</p></item><item><p><code>fn:load-xquery-module</code> (dynamically loads an XQuery module, providing access to its global variables and functions)</p></item><item><p><code>fn:parse-ietf-date</code> (parses a date/time supplied in IETF format)</p></item><item><p><code>fn:parse-json</code> (parses a string in JSON format, producing maps and arrays)</p></item><item><p><code>fn:random-number-generator</code> (generates random numbers)</p></item><item><p><code>fn:sort</code>(sorts a sequence)</p></item><item><p><code>fn:transform</code> (runs an XSLT transformation)</p></item><item><p><code>fn:xml-to-json</code> (converts XML to JSON)</p></item></ulist></item><item><p>New variants of some existing functions are introduced:</p><ulist><item><p>A one-argument form of <code>fn:tokenize</code>, to handle whitespace-separated strings</p></item><item><p>A one-argument form of <code>fn:trace</code>, omitting the <code>$label</code> argument</p></item><item><p>The single-argument form of the <code>fn:error</code> function, like the other forms, now allows the first argument
                       to be an empty sequence.</p></item></ulist></item><item><p>Some existing functions are extended to handle maps and arrays: affected functions include
              <code>fn:boolean</code>, <code>fn:string</code>, <code>fn:data</code>, <code>fn:deep-equal</code>,
                 and <code>fn:collection</code>.</p></item><item><p>The <code>fn:serialize</code> function can now accept serialization parameters supplied in the form of a map.</p></item><item><p>An ordering relation is defined for <code>xs:hexBinary</code> and <code>xs:base64Binary</code>
              values.</p></item><item><p>Functions and operators on numeric values now make use of the new built-in union type <code>xs:numeric</code>,
              replacing the previous use of <code>numeric</code> as a label representing a pseudo-type.</p></item><item><p>For the <code>fn:max</code> and <code>fn:min</code> functions, the rules for the dynamic type of the
              result value are stricter than in previous versions. In the case where the input sequence consists entirely of
              numeric or <code>xs:anyURI</code> values of the same primitive type, previous versions required only that the returned
              value be an instance of the least common supertype of the input types; this version requires that the returned value
              retains its original type, which means that the same rule now applies to numeric and <code>xs:anyURI</code> values
              as to values of other primitive types.</p></item><item><p>An ambiguity relating to the type of the results of functions such as <code>fn:abs</code> and <code>fn:round</code>
              has been resolved. The specification is now explicit, for example, that when <code>fn:abs</code> is applied to a value
              of type <code>xs:positiveInteger</code>, it is legitimate to return the supplied value unchanged (any other type derived
              from <code>xs:integer</code> is also permitted).</p></item><item><p>Many edge cases in the functions for formatting dates, times, and numbers are now specified more prescriptively, and
              in some cases mandate behavior that was previously implementation-defined. For example, the handling of grouping separators
              when formatting fractional seconds is now spelled out.</p></item></olist></div2><div2 id="editorial-changes"><head>Editorial and procedural changes</head><olist><item><p>The conformance rules have been rewritten to better reflect the relationship with host languages. </p></item><item><p>The types <code>xs:dayTimeDuration</code> and <code>xs:yearMonthDuration</code> are now defined by
		          reference to XSD 1.1.</p></item><item><p>References to ISO 8601 are updated to refer to the 2004 edition.</p></item><item><p>The claim that early normalization is preferred has been removed, as the relevant W3C document has effectively
		          withdrawn this recommendation.</p></item><item><p>For functions that depend on the static base URI, the specification describes more clearly what happens when the
		          static base URI is absent.</p></item><item><p>The functions underpinning the operators "<code>&lt;&lt;</code>", "<code>&gt;&gt;</code>", <code>is</code>, <code>union</code>, <code>except</code>,
		          <code>to</code>, and "<code>,</code>" have been removed from this document. These operators are fully described in the
		          XPath and XQuery language specifications, which make no reference to the specifications that previously 
		          appeared in this document.</p></item><item><p>Compatibility with versions earlier than 3.0 is now described by reference to the 3.0 version of this Recommendation, which
		          contains detailed information on the topic.</p></item><item><p>An informative appendix now gives brief details of additional function libraries defined by third parties.</p></item><item><p>Numerous minor editorial errors have been corrected, and numerous clarifications added.</p></item><item><p>The (poorly defined) concept of least common subtype is no longer used.</p></item><item><p>Some minor changes have been made in support of streaming in XSLT 3.0: for example it is recognized that there
		       are circumstances in which the <code>fn:last</code> function may raise dynamic errors related to streaming.</p></item></olist></div2><div2 id="changes-since-Dec-2014" diff="add" at="D"><head>Changes since the Candidate Recommendation of 18 December 2014</head><p>Numerous editorial corrections and clarifications have been made. Except for the most trivial, these
	        can be found listed in the public Bugzilla database, and can be identified by the highlighting in the
	        change-marked version of this document.</p><p>The following substantive technical changes have been made:</p><olist><item><p>The rules for determinism of <code>fn:uri-collection</code> are now identical to the rules for 
	              <code>fn:collection</code> (Bug 27750).</p></item><item><p>The <code>fn:collection</code> function can now return items of any type (not only nodes).</p></item><item><p>The <code>fn:doc-available</code> function now returns false, rather than raising an error, when
	              an invalid URI is supplied (Bug 29404).</p></item><item><p>The <code>fn:collection</code> and <code>fn:uri-collection</code> functions are no longer
	              required to report a specific error when the supplied URI is invalid (Bug 29404).</p></item><item><p>The two functions <code>fn:json-to-xml</code> and <code>fn:xml-to-json</code>, previously
	              in the XSLT 3.0 specification, have been transferred to this specification (Bug 27997),
	              and minor changes have been made to <code>fn:parse-json</code> and <code>fn:json-doc</code>
	              in the interests of alignment.</p></item><item><p>The rules for functions that accept an options parameter as a map have been unified,
	              clarified, and moved into a single place (Bug 28196).</p></item><item><p>Added a suggested (optional) way of referencing CLDR numbering schemes in <code>fn:format-integer</code> (Bug 27614).</p></item><item><p>The second argument of <code>fn:serialize</code> can now be provided in the form of a map, giving serialization
	              options (Bug 28140).</p></item><item><p>The new function <code>fn:default-language</code> has been added. (Bug 28850).</p></item><item><p>The <code>fn:parse-ietf-date</code> function now accepts a single-digit hours value (Bug 29496).</p></item><item><p>Clarified that <code>array:join</code> when given an empty sequence as input produces an empty array as its result. (Bug 29607).</p></item><item><p>Provided a suggested interpretation for fragment identifiers in the URI passed to <code>fn:doc</code>. (Bug 29608).</p></item><item><p>The new function <code>array:put</code> has been added. (Bug 29685).</p></item><item><p>The function <code>fn:random-number-generator</code> now accepts an empty sequence
	              as the first argument. (Bug 29671).</p></item><item><p>The functions <code>map:remove</code> and <code>array:remove</code> can now remove
	           multiple entries/members in a single call. (Bug 29660).</p></item><item><p>The rules under which <code>fn:xml-to-json</code> recognizes map keys as duplicates, especially
	           when some characters are escaped, have been clarified. (Bug 29588)</p></item><item><p>The <code>fn:json-to-xml</code> function now escapes solidus (<code>/</code>) as
	              <code>\/</code>. (Bug 29665)</p></item><item><p>A new function <code>map:find</code> is provided to allow recursive searching of nested maps and arrays. (Bug 29743)</p></item><item><p>The options to the <code>fn:transform</code> function have been refined. (Bugs 29832 and 29939)</p></item><item><p>The serialization parameters supplied to <code>fn:transform</code> have been brought into line with those supplied
	              to <code>fn:serialize</code>. (Bugs 29940 and 29943)</p></item><item><p>To ensure that collation keys can be compared without ambiguity, the <code>fn:collation-key</code> function
	           is now defined to return an <code>xs:base64Binary</code> result. (Bug 29853)</p></item><item><p>Collation URIs for UCA collations have a new parameter <code>maxVariable</code> indicating which groups
	           of characters (for example whitespace and punctuation) should be ignored, or given reduced significance, when
	           comparing strings. In addition, most of the parameters in UCA collation URIs now have interoperable default
	           values. (Bug 29865)</p></item></olist><p>In addition, a number of technical clarifications have been made:</p><olist><item><p>Clarification of the specialized meaning of the term "primitive type" used throughout 
	              section <specref ref="casting"/> (Bug 27737).</p></item><item><p>Error conditions and handling of edge cases such as unpaired surrogates are more clearly defined
	              for JSON-related functions such as <code>fn:parse-json</code>.</p></item><item><p>The description of <code>fn:replace</code> has been changed to clarify that certain error conditions are not
	              applicable when the <code>q</code> flag is present.</p></item><item><p>The properties of the functions returned by <code>fn:random-number-generator</code>
	           have been spelt out in more detail.</p></item><item><p>The rules for the <code>fn:idref</code> function have been clarified in the edge case where a node contains both IDREF
	           and non-IDREF items in its typed value (Bug 28238).</p></item><item><p>The specification of regular expressions is now more careful to distinguish capturing parentheses in a
	              regex from other (non-capturing) parentheses.</p></item><item><p>The specification of <code>fn:collation-key</code> has been clarified to make it explicit that the function
	              follows the general rules for collation URI arguments.</p></item><item><p>The rules for handling of grouping separators in <code>fn:format-integer</code> have been spelt out in more detail.</p></item><item><p>Some rules have been added to disallow nonsensical picture strings in <code>fn:format-number</code>. Specifically,
	           the mantissa part cannot consist of a decimal separator on its own; a grouping separator cannot appear at the end of the integer part
	           of the picture; and adjacent grouping separators are disallowed. (Bug 28567)</p></item></olist></div2><div2 id="changes-since-Dec-2016" diff="add" at="F"><head>Changes since the Candidate Recommendation of 13 December 2016</head><p>The following corrections have been made:</p><olist><item><p>Bug 30041: removed any ambiguity as to how <code>fn:year-from-date</code> and
	              <code>fn:year-from-dateTime</code> should handle negative (BCE) years.</p></item><item><p>Bug 30045: corrected an error in the specification of <code>array:fold-left</code> and <code>array:fold-right</code>
	              which suggested they should wrap the result in an array, contrary to all examples, notes, and test cases.</p></item></olist></div2><div2 id="changes-since-Jan-2017" diff="add" at="G"><head>Changes since the Proposed Recommendation of 17 January 2017</head><p>The following corrections have been made:</p><olist><item><p>Bug 30052: corrected ill-formed markup in an example of the <code>fn:xml-to-json</code> function.</p></item><item><p>Bug 30053: an example showing the effect of supplying <code>fn:parse-xml-fragment</code> with ill-formed XML markup contained
	              errors other than the one being illustrated.</p></item><item><p>Bug 30069: corrected any suggestion that XPTY0004 was the only error that could occur
	           when applying the function conversion rules to option parameters.</p></item></olist></div2></inform-div1><inform-div1 id="back-compatibility" diff="chg" at="A"><head>Compatibility with Previous Versions</head><p>This section summarizes the extent to which this specification is compatible with previous versions.</p><p diff="chg" at="C">Version 3.1 of this function library is fully backwards compatible with version 3.0, with the following caveats:</p><olist diff="add" at="C"><item><p>The return type of the result of <code>fn:min</code> and <code>fn:max</code> is more strictly prescribed
            than in earlier versions.</p></item><item><p>The behavior of functions when the static base URI is absent is more strictly prescribed than
            in earlier versions.</p></item><item><p>In the <code>fn:format-number</code> function, some picture strings that previously were permitted 
               but had no defined meaning are now disallowed.</p></item><item><p diff="add" at="D">In the <code>fn:format-number</code> function, the rules as given in XPath/XQuery 3.0, and before that in XSLT 2.0,
               resulted in the number zero being formatted as a zero-length string under certain pictures (for example <code>".#"</code>).
               This has been deemed a bug rather than a feature, and has been corrected in this version of the specification.
            </p></item><item><p>The return type of the result of <code>fn:collection</code> is now broader, which may result in errors
               when strict static typing is used.</p></item><item><p diff="add" at="E">In the <code>fn:format-time</code> and <code>fn:format-dateTime</code> functions,
            fractional seconds are now truncated towards zero rather than being rounded when necessary to fit in the 
            maximum width (previous versions of the specification prescribed rounding, but did not say what should happen
            when a fraction such as <code>0.999</code> rounded to <code>1</code>).</p></item></olist><p>For compatibility issues regarding earlier versions, see the 3.0 version of this specification.</p></inform-div1></back></spec>